Skip to content

Environments

EnvParams

Bases: _StructBase

Dataclass to hold environment parameters. Parameters are immutable.

Parameters:

Name Type Description Default
max_requests Scalar

Maximum number of requests in an episode

required
incremental_loading Scalar

Incremental increase in traffic load (non-expiring requests)

required
end_first_blocking Scalar

End episode on first blocking event

required
continuous_operation Scalar

If True, do not reset the environment at the end of an episode

required
edges Array

Two column array defining source-dest node-pair edges of the graph

required
slot_size Scalar

Spectral width of frequency slot in GHz

required
consider_modulation_format Scalar

If True, consider modulation format to determine required slots

required
link_length_array Array

Array of link lengths

required
aggregate_slots Scalar

Number of slots to aggregate into a single action (First-Fit with aggregation)

required
guardband Scalar

Guard band in slots

required
directed_graph bool

Whether graph is directed (one fibre per link per transmission direction)

required
temperature Scalar

Temp. used for softmax differentiable approximation

required
window_size Scalar

Window size for weighted average of neighbouring cells in differentiable indexing

required
Source code in xlron/environments/dataclasses.py
 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@struct.dataclass
class EnvParams(_StructBase):
    """Dataclass to hold environment parameters. Parameters are immutable.

    Args:
        max_requests (chex.Scalar): Maximum number of requests in an episode
        incremental_loading (chex.Scalar): Incremental increase in traffic load (non-expiring requests)
        end_first_blocking (chex.Scalar): End episode on first blocking event
        continuous_operation (chex.Scalar): If True, do not reset the environment at the end of an episode
        edges (Array): Two column array defining source-dest node-pair edges of the graph
        slot_size (chex.Scalar): Spectral width of frequency slot in GHz
        consider_modulation_format (chex.Scalar): If True, consider modulation format to determine required slots
        link_length_array (Array): Array of link lengths
        aggregate_slots (chex.Scalar): Number of slots to aggregate into a single action (First-Fit with aggregation)
        guardband (chex.Scalar): Guard band in slots
        directed_graph (bool): Whether graph is directed (one fibre per link per transmission direction)
        temperature (chex.Scalar): Temp. used for softmax differentiable approximation
        window_size (chex.Scalar): Window size for weighted average of neighbouring cells in differentiable indexing
    """

    num_nodes: int = struct.field(pytree_node=False)
    num_links: int = struct.field(pytree_node=False)
    max_requests: int = struct.field(pytree_node=False)
    incremental_loading: bool = struct.field(pytree_node=False)
    end_first_blocking: bool = struct.field(pytree_node=False)
    terminate_on_episode_end: bool = struct.field(pytree_node=False)
    continuous_operation: bool = struct.field(pytree_node=False)
    edges: Array = struct.field(pytree_node=True)
    slot_size: int = struct.field(pytree_node=False)
    consider_modulation_format: bool = struct.field(pytree_node=False)
    link_length_array: Array = struct.field(pytree_node=True)
    aggregate_slots: int = struct.field(pytree_node=False)
    guardband: int = struct.field(pytree_node=False)
    directed_graph: bool = struct.field(pytree_node=False)
    maximise_throughput: bool = struct.field(pytree_node=False)
    reward_type: str = struct.field(pytree_node=False)
    values_bw: Array = struct.field(pytree_node=True)
    # Smallest/largest bandwidth request, static for host-side sizing under jit
    min_bw: float = struct.field(pytree_node=False)
    max_bw: float = struct.field(pytree_node=False)
    values_bw_probs: Array | None = struct.field(pytree_node=True)
    truncate_holding_time: bool = struct.field(pytree_node=False)
    traffic_array: bool = struct.field(pytree_node=False)
    pack_path_bits: bool = struct.field(pytree_node=False)
    relative_arrival_times: bool = struct.field(pytree_node=False)
    temperature: float = struct.field(pytree_node=False)
    differentiable: bool = struct.field(pytree_node=False)
    num_spectral_features: int = struct.field(pytree_node=False)
    line_graph_spectral_features: Array | None = struct.field(pytree_node=True)
    path_link_array: Array = struct.field(pytree_node=True)
    path_se_array: Array = struct.field(pytree_node=True)
    unique_se_values: Array = struct.field(pytree_node=True)
    k_paths: int = struct.field(pytree_node=False)
    link_resources: int = struct.field(pytree_node=False)
    k_paths: int = struct.field(pytree_node=False)
    mean_service_holding_time: float = struct.field(pytree_node=False)
    load: float = struct.field(pytree_node=False)
    arrival_rate: float = struct.field(pytree_node=False)
    random_traffic: bool = struct.field(pytree_node=False)
    include_no_op: bool = struct.field(pytree_node=False)  # Include a "no op" action
    transformer_obs_type: str = struct.field(pytree_node=False)
    use_gnn: bool = struct.field(pytree_node=False)
    profile: bool = struct.field(pytree_node=False)
    render: bool = struct.field(pytree_node=False)
    # Pre-computed CDF of the flattened traffic matrix for inverse-CDF source-dest
    # sampling in generate_request_rsa/_rwalr (avoids a per-step cumsum). None when
    # the matrix is not fixed across resets (random_traffic) or unused (traffic_array).
    traffic_cdf: Array | None = struct.field(pytree_node=True)

EnvState

Bases: _StructBase

Dataclass to hold environment state. State is mutable and arrays are traced on JIT compilation.

Parameters:

Name Type Description Default
current_time Scalar

Current time in environment

required
holding_time Scalar

Holding time of current request

required
total_timesteps Scalar

Total timesteps in environment

required
total_requests Scalar

Total requests in environment

required
graph GraphsTuple

Graph tuple representing network state

required
full_link_slot_mask Array

Action mask for link slot action (including if slot actions are aggregated)

required
accepted_services Array

Number of accepted services

required
accepted_bitrate Array

Accepted bitrate

required
arrival_rate Scalar

Arrival rate (load / mean_service_holding_time), traced for recompilation-free load sweeps

required
mean_service_holding_time Scalar

Mean service holding time, traced for recompilation-free load sweeps

required
Source code in xlron/environments/dataclasses.py
32
33
34
35
36
37
38
39
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
@struct.dataclass
class EnvState(_StructBase):
    """Dataclass to hold environment state. State is mutable and arrays are traced on JIT compilation.

    Args:
        current_time (chex.Scalar): Current time in environment
        holding_time (chex.Scalar): Holding time of current request
        total_timesteps (chex.Scalar): Total timesteps in environment
        total_requests (chex.Scalar): Total requests in environment
        graph (jraph.GraphsTuple): Graph tuple representing network state
        full_link_slot_mask (Array): Action mask for link slot action (including if slot actions are aggregated)
        accepted_services (Array): Number of accepted services
        accepted_bitrate (Array): Accepted bitrate
        arrival_rate (chex.Scalar): Arrival rate (load / mean_service_holding_time), traced for recompilation-free load sweeps
        mean_service_holding_time (chex.Scalar): Mean service holding time, traced for recompilation-free load sweeps
    """

    current_time: Array
    holding_time: Array
    arrival_time: Array
    total_timesteps: Array
    total_requests: Array
    graph: jraph.GraphsTuple
    full_link_slot_mask: Array
    accepted_services: Array
    accepted_bitrate: Array
    total_bitrate: Array
    list_of_requests: Array
    link_slot_array: Array
    request_array: Array
    link_slot_departure_array: Array
    link_slot_mask: Array
    traffic_matrix: Array
    valid_mass: Array
    arrival_rate: Array
    mean_service_holding_time: Array

RSAMultibandEnvParams

Bases: RSAEnvParams

Dataclass to hold environment parameters for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
464
465
466
467
468
469
@struct.dataclass
class RSAMultibandEnvParams(RSAEnvParams):
    """Dataclass to hold environment parameters for MultiBandRSA (RBSA)."""

    gap_starts: Array = struct.field(pytree_node=True)
    gap_widths: Array = struct.field(pytree_node=True)

RSAMultibandEnvState

Bases: RSAEnvState

Dataclass to hold environment state for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
457
458
459
460
461
@struct.dataclass
class RSAMultibandEnvState(RSAEnvState):
    """Dataclass to hold environment state for MultiBandRSA (RBSA)."""

    pass

Dataclasses

DeepRMSAEnvState

Bases: RSAEnvState

Dataclass to hold environment state for DeepRMSA.

Parameters:

Name Type Description Default
path_stats Array

Path stats array containing

required
Source code in xlron/environments/dataclasses.py
227
228
229
230
231
232
233
234
235
236
237
238
239
@struct.dataclass
class DeepRMSAEnvState(RSAEnvState):
    """Dataclass to hold environment state for DeepRMSA.

    Args:
        path_stats (Array): Path stats array containing
        1. Required slots on path
        2. Total available slots on path
        3. Size of 1st free spectrum block
        4. Avg. free block size
    """

    path_stats: Array

EnvParams

Bases: _StructBase

Dataclass to hold environment parameters. Parameters are immutable.

Parameters:

Name Type Description Default
max_requests Scalar

Maximum number of requests in an episode

required
incremental_loading Scalar

Incremental increase in traffic load (non-expiring requests)

required
end_first_blocking Scalar

End episode on first blocking event

required
continuous_operation Scalar

If True, do not reset the environment at the end of an episode

required
edges Array

Two column array defining source-dest node-pair edges of the graph

required
slot_size Scalar

Spectral width of frequency slot in GHz

required
consider_modulation_format Scalar

If True, consider modulation format to determine required slots

required
link_length_array Array

Array of link lengths

required
aggregate_slots Scalar

Number of slots to aggregate into a single action (First-Fit with aggregation)

required
guardband Scalar

Guard band in slots

required
directed_graph bool

Whether graph is directed (one fibre per link per transmission direction)

required
temperature Scalar

Temp. used for softmax differentiable approximation

required
window_size Scalar

Window size for weighted average of neighbouring cells in differentiable indexing

required
Source code in xlron/environments/dataclasses.py
 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@struct.dataclass
class EnvParams(_StructBase):
    """Dataclass to hold environment parameters. Parameters are immutable.

    Args:
        max_requests (chex.Scalar): Maximum number of requests in an episode
        incremental_loading (chex.Scalar): Incremental increase in traffic load (non-expiring requests)
        end_first_blocking (chex.Scalar): End episode on first blocking event
        continuous_operation (chex.Scalar): If True, do not reset the environment at the end of an episode
        edges (Array): Two column array defining source-dest node-pair edges of the graph
        slot_size (chex.Scalar): Spectral width of frequency slot in GHz
        consider_modulation_format (chex.Scalar): If True, consider modulation format to determine required slots
        link_length_array (Array): Array of link lengths
        aggregate_slots (chex.Scalar): Number of slots to aggregate into a single action (First-Fit with aggregation)
        guardband (chex.Scalar): Guard band in slots
        directed_graph (bool): Whether graph is directed (one fibre per link per transmission direction)
        temperature (chex.Scalar): Temp. used for softmax differentiable approximation
        window_size (chex.Scalar): Window size for weighted average of neighbouring cells in differentiable indexing
    """

    num_nodes: int = struct.field(pytree_node=False)
    num_links: int = struct.field(pytree_node=False)
    max_requests: int = struct.field(pytree_node=False)
    incremental_loading: bool = struct.field(pytree_node=False)
    end_first_blocking: bool = struct.field(pytree_node=False)
    terminate_on_episode_end: bool = struct.field(pytree_node=False)
    continuous_operation: bool = struct.field(pytree_node=False)
    edges: Array = struct.field(pytree_node=True)
    slot_size: int = struct.field(pytree_node=False)
    consider_modulation_format: bool = struct.field(pytree_node=False)
    link_length_array: Array = struct.field(pytree_node=True)
    aggregate_slots: int = struct.field(pytree_node=False)
    guardband: int = struct.field(pytree_node=False)
    directed_graph: bool = struct.field(pytree_node=False)
    maximise_throughput: bool = struct.field(pytree_node=False)
    reward_type: str = struct.field(pytree_node=False)
    values_bw: Array = struct.field(pytree_node=True)
    # Smallest/largest bandwidth request, static for host-side sizing under jit
    min_bw: float = struct.field(pytree_node=False)
    max_bw: float = struct.field(pytree_node=False)
    values_bw_probs: Array | None = struct.field(pytree_node=True)
    truncate_holding_time: bool = struct.field(pytree_node=False)
    traffic_array: bool = struct.field(pytree_node=False)
    pack_path_bits: bool = struct.field(pytree_node=False)
    relative_arrival_times: bool = struct.field(pytree_node=False)
    temperature: float = struct.field(pytree_node=False)
    differentiable: bool = struct.field(pytree_node=False)
    num_spectral_features: int = struct.field(pytree_node=False)
    line_graph_spectral_features: Array | None = struct.field(pytree_node=True)
    path_link_array: Array = struct.field(pytree_node=True)
    path_se_array: Array = struct.field(pytree_node=True)
    unique_se_values: Array = struct.field(pytree_node=True)
    k_paths: int = struct.field(pytree_node=False)
    link_resources: int = struct.field(pytree_node=False)
    k_paths: int = struct.field(pytree_node=False)
    mean_service_holding_time: float = struct.field(pytree_node=False)
    load: float = struct.field(pytree_node=False)
    arrival_rate: float = struct.field(pytree_node=False)
    random_traffic: bool = struct.field(pytree_node=False)
    include_no_op: bool = struct.field(pytree_node=False)  # Include a "no op" action
    transformer_obs_type: str = struct.field(pytree_node=False)
    use_gnn: bool = struct.field(pytree_node=False)
    profile: bool = struct.field(pytree_node=False)
    render: bool = struct.field(pytree_node=False)
    # Pre-computed CDF of the flattened traffic matrix for inverse-CDF source-dest
    # sampling in generate_request_rsa/_rwalr (avoids a per-step cumsum). None when
    # the matrix is not fixed across resets (random_traffic) or unused (traffic_array).
    traffic_cdf: Array | None = struct.field(pytree_node=True)

EnvState

Bases: _StructBase

Dataclass to hold environment state. State is mutable and arrays are traced on JIT compilation.

Parameters:

Name Type Description Default
current_time Scalar

Current time in environment

required
holding_time Scalar

Holding time of current request

required
total_timesteps Scalar

Total timesteps in environment

required
total_requests Scalar

Total requests in environment

required
graph GraphsTuple

Graph tuple representing network state

required
full_link_slot_mask Array

Action mask for link slot action (including if slot actions are aggregated)

required
accepted_services Array

Number of accepted services

required
accepted_bitrate Array

Accepted bitrate

required
arrival_rate Scalar

Arrival rate (load / mean_service_holding_time), traced for recompilation-free load sweeps

required
mean_service_holding_time Scalar

Mean service holding time, traced for recompilation-free load sweeps

required
Source code in xlron/environments/dataclasses.py
32
33
34
35
36
37
38
39
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
@struct.dataclass
class EnvState(_StructBase):
    """Dataclass to hold environment state. State is mutable and arrays are traced on JIT compilation.

    Args:
        current_time (chex.Scalar): Current time in environment
        holding_time (chex.Scalar): Holding time of current request
        total_timesteps (chex.Scalar): Total timesteps in environment
        total_requests (chex.Scalar): Total requests in environment
        graph (jraph.GraphsTuple): Graph tuple representing network state
        full_link_slot_mask (Array): Action mask for link slot action (including if slot actions are aggregated)
        accepted_services (Array): Number of accepted services
        accepted_bitrate (Array): Accepted bitrate
        arrival_rate (chex.Scalar): Arrival rate (load / mean_service_holding_time), traced for recompilation-free load sweeps
        mean_service_holding_time (chex.Scalar): Mean service holding time, traced for recompilation-free load sweeps
    """

    current_time: Array
    holding_time: Array
    arrival_time: Array
    total_timesteps: Array
    total_requests: Array
    graph: jraph.GraphsTuple
    full_link_slot_mask: Array
    accepted_services: Array
    accepted_bitrate: Array
    total_bitrate: Array
    list_of_requests: Array
    link_slot_array: Array
    request_array: Array
    link_slot_departure_array: Array
    link_slot_mask: Array
    traffic_matrix: Array
    valid_mass: Array
    arrival_rate: Array
    mean_service_holding_time: Array

GNModelEnvParams

Bases: RSAEnvParams

Dataclass to hold environment state for GN model environments.

Source code in xlron/environments/dataclasses.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
@struct.dataclass
class GNModelEnvParams(RSAEnvParams):
    """Dataclass to hold environment state for GN model environments."""

    # Padded constituent link indices, (num_paths, max_path_hops); num_links is padding.
    path_link_indices: Array = struct.field(pytree_node=True)
    # Per-path total length (metres) and its maxima, precomputed so that steps never
    # reduce over the whole path table (it is a runtime argument, not a folded constant).
    path_length_array: Array = struct.field(pytree_node=True)
    max_path_length: chex.Scalar = struct.field(pytree_node=False)
    max_path_hops: chex.Scalar = struct.field(pytree_node=False)
    ref_lambda: chex.Scalar = struct.field(pytree_node=False)
    max_spans: chex.Scalar = struct.field(pytree_node=False)
    max_span_length: chex.Scalar = struct.field(pytree_node=False)
    nonlinear_coeff: chex.Scalar = struct.field(pytree_node=False)
    raman_gain_slope: chex.Scalar = struct.field(pytree_node=False)
    attenuation: chex.Scalar = struct.field(pytree_node=False)
    attenuation_bar: chex.Scalar = struct.field(pytree_node=False)
    dispersion_coeff: chex.Scalar = struct.field(pytree_node=False)
    dispersion_slope: chex.Scalar = struct.field(pytree_node=False)
    transceiver_snr: Array = struct.field(pytree_node=True)
    amplifier_noise_figure: Array = struct.field(pytree_node=True)
    coherent: bool = struct.field(pytree_node=False)
    num_roadms: chex.Scalar = struct.field(pytree_node=False)
    roadm_loss: chex.Scalar = struct.field(pytree_node=False)
    span_lumped_loss_db: chex.Scalar | None = struct.field(pytree_node=False)
    roadm_express_loss: Array = struct.field(pytree_node=True)
    roadm_add_drop_loss: Array = struct.field(pytree_node=True)
    roadm_noise_figure: Array = struct.field(pytree_node=True)
    num_spans: chex.Scalar = struct.field(pytree_node=False)
    launch_power_type: str = struct.field(pytree_node=False)
    snr_margin: chex.Scalar = struct.field(pytree_node=False)
    max_snr: chex.Scalar = struct.field(pytree_node=False)
    max_power: chex.Scalar = struct.field(pytree_node=False)
    min_power: chex.Scalar = struct.field(pytree_node=False)
    step_power: chex.Scalar = struct.field(pytree_node=False)
    last_fit: bool = struct.field(pytree_node=False)
    max_power_per_fibre: chex.Scalar = struct.field(pytree_node=False)
    default_launch_power: chex.Scalar = struct.field(pytree_node=False)
    power_per_channel: chex.Scalar = struct.field(pytree_node=False)  # linear Watts
    slot_launch_power_array: Array = struct.field(
        pytree_node=True
    )  # (link_resources,): per-slot launch power in linear Watts
    mod_format_correction: bool = struct.field(pytree_node=False)
    gap_starts: Array = struct.field(pytree_node=True)
    gap_widths: Array = struct.field(pytree_node=True)
    uniform_spans: bool = struct.field(pytree_node=False)
    min_snr: chex.Scalar = struct.field(pytree_node=False)
    fec_threshold: chex.Scalar = struct.field(pytree_node=False)
    band_slot_order_ff: Array = struct.field(
        pytree_node=True
    )  # Slot permutation for band-preference first-fit (empty if unused)
    band_slot_order_lf: Array = struct.field(
        pytree_node=True
    )  # Slot permutation for band-preference last-fit (empty if unused)
    slot_centre_freq_array: Array = struct.field(
        pytree_node=True
    )  # Per-slot centre frequencies in relative GHz offset from ref_lambda
    num_subchannels: int = struct.field(pytree_node=False)  # Nyquist subchannels per slot for SPM
    # Distributed Raman Amplification fields
    use_raman_amp: bool = struct.field(pytree_node=False)
    raman_fit_params: Array = struct.field(
        pytree_node=True
    )  # (6, num_channels, max_spans) — [C_f, a_f, C_b, a_b, a, raman_gain] Neper-scale + linear
    raman_pump_power_fw: Array = struct.field(
        pytree_node=True
    )  # (max_spans, num_pumps_fw) — forward pump powers [W]
    raman_pump_power_bw: Array = struct.field(
        pytree_node=True
    )  # (max_spans, num_pumps_bw) — backward pump powers [W]
    raman_pump_freq_fw: Array = struct.field(
        pytree_node=True
    )  # (max_spans, num_pumps_fw) — forward pump frequencies [Hz]
    raman_pump_freq_bw: Array = struct.field(
        pytree_node=True
    )  # (max_spans, num_pumps_bw) — backward pump frequencies [Hz]

GNModelEnvState

Bases: RSAEnvState

Dataclass to hold environment state for RSA with GN model.

The blocked_* fields count blocked requests by cause (cumulative within an episode, like accepted_services). Causes are attributed with spectrum > SNR > power priority, so the counters are mutually exclusive and sum to the total number of blocked requests.

Source code in xlron/environments/dataclasses.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
@struct.dataclass
class GNModelEnvState(RSAEnvState):
    """Dataclass to hold environment state for RSA with GN model.

    The blocked_* fields count blocked requests by cause (cumulative within an episode,
    like accepted_services). Causes are attributed with spectrum > SNR > power priority,
    so the counters are mutually exclusive and sum to the total number of blocked requests.
    """

    blocked_spectrum: Array  # Count of requests blocked by spectrum contention
    blocked_snr: Array  # Count of requests blocked by insufficient SNR
    blocked_power: Array  # Count of requests blocked by the per-fibre power budget
    link_snr_array: Array  # Available SNR on each link
    channel_centre_bw_array: Array  # Channel centre bandwidth for each active connection
    path_index_array: (
        Array  # Contains indices of lightpaths in use on slots (used for lightpath SNR calculation)
    )
    channel_power_array: Array  # Channel power for each active connection
    channel_centre_bw_array_prev: (
        Array  # Channel centre bandwidth for each active connection in previous timestep
    )
    path_index_array_prev: (
        Array  # Contains indices of lightpaths in use on slots in previous timestep
    )
    channel_power_array_prev: Array  # Channel power for each active connection in previous timestep
    channel_centre_freq_array: Array  # Per-slot centre frequency in GHz
    channel_centre_freq_array_prev: Array  # Previous timestep centre frequency for undo
    link_snr_array_prev: Array  # Link SNR array in previous timestep (blocked-request restore)
    launch_power_array: Array  # Launch power array

LogEnvState

Dataclass to hold environment state for logging.

Parameters:

Name Type Description Default
env_state EnvState

Environment state

required
lengths Scalar

Lengths

required
returns Scalar

Returns

required
cum_returns Scalar

Cumulative returns

required
accepted_services Scalar

Accepted services

required
accepted_bitrate Scalar

Accepted bitrate

required
total_bitrate Scalar

Total bitrate requested

required
utilisation Scalar

Network utilisation

required
fragmentation Scalar

Mean external spectrum fragmentation across links

required
blocked_spectrum Scalar

Requests blocked by spectrum contention (GN-model envs, else 0)

required
blocked_snr Scalar

Requests blocked by insufficient SNR (GN-model envs, else 0)

required
blocked_power Scalar

Requests blocked by the per-fibre power budget (GN-model envs, else 0)

required
terminal Scalar

Terminal flag (true termination condition met)

required
truncated Scalar

Truncated flag (max steps reached)

required
Source code in xlron/environments/dataclasses.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@struct.dataclass
class LogEnvState:
    """Dataclass to hold environment state for logging.

    Args:
        env_state (EnvState): Environment state
        lengths (chex.Scalar): Lengths
        returns (chex.Scalar): Returns
        cum_returns (chex.Scalar): Cumulative returns
        accepted_services (chex.Scalar): Accepted services
        accepted_bitrate (chex.Scalar): Accepted bitrate
        total_bitrate (chex.Scalar): Total bitrate requested
        utilisation (chex.Scalar): Network utilisation
        fragmentation (chex.Scalar): Mean external spectrum fragmentation across links
        blocked_spectrum (chex.Scalar): Requests blocked by spectrum contention (GN-model envs, else 0)
        blocked_snr (chex.Scalar): Requests blocked by insufficient SNR (GN-model envs, else 0)
        blocked_power (chex.Scalar): Requests blocked by the per-fibre power budget (GN-model envs, else 0)
        terminal (chex.Scalar): Terminal flag (true termination condition met)
        truncated (chex.Scalar): Truncated flag (max steps reached)
    """

    env_state: EnvState
    lengths: Array
    returns: Array
    cum_returns: Array
    accepted_services: Array
    accepted_bitrate: Array
    total_bitrate: Array
    utilisation: Array
    fragmentation: Array
    blocked_spectrum: Array
    blocked_snr: Array
    blocked_power: Array
    terminal: Array
    truncated: Array

MultiBandRSAEnvParams

Bases: RSAEnvParams

Dataclass to hold environment parameters for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
276
277
278
279
280
281
@struct.dataclass
class MultiBandRSAEnvParams(RSAEnvParams):
    """Dataclass to hold environment parameters for MultiBandRSA (RBSA)."""

    gap_start: chex.Scalar = struct.field(pytree_node=False)
    gap_width: chex.Scalar = struct.field(pytree_node=False)

MultiBandRSAEnvState

Bases: RSAEnvState

Dataclass to hold environment state for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
269
270
271
272
273
@struct.dataclass
class MultiBandRSAEnvState(RSAEnvState):
    """Dataclass to hold environment state for MultiBandRSA (RBSA)."""

    pass

RMSAGNModelEnvParams

Bases: GNModelEnvParams

Dataclass to hold environment params for RMSA with GN model.

Parameters:

Name Type Description Default
link_snr_array Array

Link SNR array

required
Source code in xlron/environments/dataclasses.py
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
@struct.dataclass
class RMSAGNModelEnvParams(GNModelEnvParams):
    """Dataclass to hold environment params for RMSA with GN model.

    Args:
        link_snr_array (Array): Link SNR array
    """

    modulations_array: Array = struct.field(pytree_node=True)
    fec_rate: chex.Scalar = struct.field(pytree_node=False)
    gn_mask_mode: str = struct.field(pytree_node=False, default="ff_lf")
    gn_mask_batch_size: int = struct.field(pytree_node=False, default=8)
    gn_mask_env_batch_size: int = struct.field(pytree_node=False, default=0)
    existing_snr_margin: float = struct.field(pytree_node=False, default=0.0)
    # "jax" or "pallas" (GN kernels plus the screened all_slots mask; hard dynamics only).
    gn_kernel_backend: str = struct.field(pytree_node=False, default="jax")
    # Candidates per endpoint-screen batch in the Pallas all_slots mask.
    gn_mask_screen_batch_size: int = struct.field(pytree_node=False, default=512)
    # "immediate" or "safe_release" (hold expired lightpaths until switching them off
    # keeps every live lightpath above threshold; issue #67).
    departure_policy: str = struct.field(pytree_node=False, default="safe_release")
    # Heuristics read state.mod_format_mask instead of recomputing the physical
    # mask. Only for callers that have just computed it for state.request_array
    # (select_action_eval sets this on the params it passes to heuristics).
    heuristic_mask_from_state: bool = struct.field(pytree_node=False, default=False)
    # all_slots masks mark only first-fit starts (band preference order), stopping
    # early: "first_path" only the first path with a valid start (exact for
    # ksp_ff), "every_path" each path's first valid start (exact for ff_ksp); ""
    # gives the full mask. select_action_eval sets it for those heuristics.
    gn_mask_first_fit: str = struct.field(pytree_node=False, default="")

RMSAGNModelEnvState

Bases: GNModelEnvState

Dataclass to hold environment state for RMSA with GN model.

Parameters:

Name Type Description Default
link_snr_array Array

Link SNR array

required
Source code in xlron/environments/dataclasses.py
442
443
444
445
446
447
448
449
450
451
452
453
454
@struct.dataclass
class RMSAGNModelEnvState(GNModelEnvState):
    """Dataclass to hold environment state for RMSA with GN model.

    Args:
        link_snr_array (Array): Link SNR array
    """

    modulation_format_index_array: Array  # Modulation format index for each active connection
    modulation_format_index_array_prev: (
        Array  # Modulation format index for each active connection in previous timestep
    )
    mod_format_mask: Array  # Modulation format mask

RSAEnvParams

Bases: EnvParams

Dataclass to hold environment parameters for RSA.

Parameters:

Name Type Description Default
num_nodes Scalar

Number of nodes

required
num_links Scalar

Number of links

required
link_resources Scalar

Number of link resources

required
k_paths Scalar

Number of paths

required
mean_service_holding_time Scalar

Mean service holding time

required
load Scalar

Load

required
arrival_rate Scalar

Arrival rate

required
path_link_array Array

Path link array

required
random_traffic bool

Random traffic matrix for RSA on each reset (else uniform or custom)

required
max_slots Scalar

Maximum number of slots

required
path_se_array Array

Path spectral efficiency array

required
deterministic_requests bool

If True, use deterministic requests

required
multiple_topologies bool

If True, use multiple topologies

required
mscl_interfering_k int

Stored routes per node pair in the interfering route set of the multi-route MSCL heuristics (0 = all k paths)

required
arbr_alpha float

Tuning parameter alpha of the ARBR heuristic (0 = static cost only, 1 = dynamic utilisation only)

required
Source code in xlron/environments/dataclasses.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
@struct.dataclass
class RSAEnvParams(EnvParams):
    """Dataclass to hold environment parameters for RSA.

    Args:
        num_nodes (chex.Scalar): Number of nodes
        num_links (chex.Scalar): Number of links
        link_resources (chex.Scalar): Number of link resources
        k_paths (chex.Scalar): Number of paths
        mean_service_holding_time (chex.Scalar): Mean service holding time
        load (chex.Scalar): Load
        arrival_rate (chex.Scalar): Arrival rate
        path_link_array (Array): Path link array
        random_traffic (bool): Random traffic matrix for RSA on each reset (else uniform or custom)
        max_slots (chex.Scalar): Maximum number of slots
        path_se_array (Array): Path spectral efficiency array
        deterministic_requests (bool): If True, use deterministic requests
        multiple_topologies (bool): If True, use multiple topologies
        mscl_interfering_k (int): Stored routes per node pair in the interfering
            route set of the multi-route MSCL heuristics (0 = all k paths)
        arbr_alpha (float): Tuning parameter alpha of the ARBR heuristic
            (0 = static cost only, 1 = dynamic utilisation only)
    """

    max_slots: chex.Scalar = struct.field(pytree_node=False)
    # Least spectral efficiency any request can be served at (1 without modulation)
    min_se: float = struct.field(pytree_node=False)
    deterministic_requests: bool = struct.field(pytree_node=False)
    multiple_topologies: bool = struct.field(pytree_node=False)
    log_actions: bool = struct.field(pytree_node=False)
    disable_node_features: bool = struct.field(pytree_node=False)
    mscl_interfering_k: int = struct.field(pytree_node=False)
    arbr_alpha: float = struct.field(pytree_node=False)

RSAEnvState

Bases: EnvState

Dataclass to hold environment state for RSA.

Parameters:

Name Type Description Default
link_slot_array Array

Link slot array

required
request_array Array

Request array

required
link_slot_departure_array Array

Link slot departure array

required
link_slot_mask Array

Link slot mask

required
traffic_matrix Array

Traffic matrix

required
Source code in xlron/environments/dataclasses.py
177
178
179
180
181
182
183
184
185
186
187
188
189
@struct.dataclass
class RSAEnvState(EnvState):
    """Dataclass to hold environment state for RSA.

    Args:
        link_slot_array (Array): Link slot array
        request_array (Array): Request array
        link_slot_departure_array (Array): Link slot departure array
        link_slot_mask (Array): Link slot mask
        traffic_matrix (Array): Traffic matrix
    """

    pass

RSAGNModelEnvParams

Bases: GNModelEnvParams

Dataclass to hold environment params for RSA with GN model.

Source code in xlron/environments/dataclasses.py
393
394
395
396
397
398
@struct.dataclass
class RSAGNModelEnvParams(GNModelEnvParams):
    """Dataclass to hold environment params for RSA with GN model."""

    # "jax" or "pallas" (GN kernels for XPM / path SNR; hard dynamics only).
    gn_kernel_backend: str = struct.field(pytree_node=False, default="jax")

RSAGNModelEnvState

Bases: GNModelEnvState

Dataclass to hold environment state for RSA with GN model.

Source code in xlron/environments/dataclasses.py
401
402
403
404
405
406
407
@struct.dataclass
class RSAGNModelEnvState(GNModelEnvState):
    """Dataclass to hold environment state for RSA with GN model."""

    active_lightpaths_array: Array  # Active lightpath array. 1 x M array. Each value is a lightpath index. Used to calculate total throughput.
    active_lightpaths_array_departure: Array  # Active lightpath array departure time.
    throughput: Array  # Current network throughput

RSAMultibandEnvParams

Bases: RSAEnvParams

Dataclass to hold environment parameters for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
464
465
466
467
468
469
@struct.dataclass
class RSAMultibandEnvParams(RSAEnvParams):
    """Dataclass to hold environment parameters for MultiBandRSA (RBSA)."""

    gap_starts: Array = struct.field(pytree_node=True)
    gap_widths: Array = struct.field(pytree_node=True)

RSAMultibandEnvState

Bases: RSAEnvState

Dataclass to hold environment state for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
457
458
459
460
461
@struct.dataclass
class RSAMultibandEnvState(RSAEnvState):
    """Dataclass to hold environment state for MultiBandRSA (RBSA)."""

    pass

RWALightpathReuseEnvState

Bases: RSAEnvState

Dataclass to hold environment state for RWA with lightpath reuse.

Parameters:

Name Type Description Default
path_index_array Array

Contains indices of lightpaths in use on slots

required
path_capacity_array Array

Contains remaining capacity of each lightpath

required
link_capacity_array Array

Contains remaining capacity of lightpath on each link-slot

required
Source code in xlron/environments/dataclasses.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
@struct.dataclass
class RWALightpathReuseEnvState(RSAEnvState):
    """Dataclass to hold environment state for RWA with lightpath reuse.

    Args:
        path_index_array (Array): Contains indices of lightpaths in use on slots
        path_capacity_array (Array): Contains remaining capacity of each lightpath
        link_capacity_array (Array): Contains remaining capacity of lightpath on each link-slot
    """

    path_index_array: Array  # Contains indices of lightpaths in use on slots
    path_capacity_array: Array  # Contains remaining capacity of each lightpath
    link_capacity_array: Array  # Contains remaining capacity of lightpath on each link-slot
    time_since_last_departure: Array  # Time since last departure

VONEEnvParams

Bases: RSAEnvParams

Dataclass to hold environment parameters for VONE.

Parameters:

Name Type Description Default
node_resources Scalar

Number of node resources

required
max_edges Scalar

Maximum number of edges

required
min_node_resources Scalar

Minimum number of node resources

required
max_node_resources Scalar

Maximum number of node resources

required
Source code in xlron/environments/dataclasses.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
@struct.dataclass
class VONEEnvParams(RSAEnvParams):
    """Dataclass to hold environment parameters for VONE.

    Args:
        node_resources (chex.Scalar): Number of node resources
        max_edges (chex.Scalar): Maximum number of edges
        min_node_resources (chex.Scalar): Minimum number of node resources
        max_node_resources (chex.Scalar): Maximum number of node resources
    """

    node_resources: chex.Scalar = struct.field(pytree_node=False)
    max_edges: chex.Scalar = struct.field(pytree_node=False)
    min_node_resources: chex.Scalar = struct.field(pytree_node=False)
    max_node_resources: chex.Scalar = struct.field(pytree_node=False)

VONEEnvState

Bases: RSAEnvState

Dataclass to hold environment state for VONE.

Parameters:

Name Type Description Default
node_capacity_array Array

Node capacity array

required
node_resource_array Array

Node resource array

required
node_departure_array Array

Node departure array

required
action_counter Array

Action counter

required
action_history Array

Action history

required
node_mask_s Array

Node mask for source node

required
node_mask_d Array

Node mask for destination node

required
virtual_topology_patterns Array

Virtual topology patterns

required
values_nodes Array

Values for nodes

required
Source code in xlron/environments/dataclasses.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
@struct.dataclass
class VONEEnvState(RSAEnvState):
    """Dataclass to hold environment state for VONE.

    Args:
        node_capacity_array (Array): Node capacity array
        node_resource_array (Array): Node resource array
        node_departure_array (Array): Node departure array
        action_counter (Array): Action counter
        action_history (Array): Action history
        node_mask_s (Array): Node mask for source node
        node_mask_d (Array): Node mask for destination node
        virtual_topology_patterns (Array): Virtual topology patterns
        values_nodes (Array): Values for nodes
    """

    node_capacity_array: Array
    node_resource_array: Array
    node_departure_array: Array
    action_counter: Array
    action_history: Array
    node_mask_s: Array
    node_mask_d: Array
    virtual_topology_patterns: Array
    values_nodes: Array

Environment wrappers

JitProfiler

Wall-clock profiler for JAX JIT-compiled code.

On CPU

• Uses host callbacks for fine-grained section timing.

On GPU

• Automatically switches to first-call-only timing. • Measures compilation + first execution latency. • Fine-grained per-call timings are intentionally disabled to avoid misleading synchronization artifacts.

This profiler records host-side timestamps using jax.debug.callback, allowing coarse wall-clock profiling of sections inside JIT-compiled code. Profiling is designed to be gated by a static Python boolean (e.g. params.profile) so that all profiling logic is resolved at trace time and introduces zero runtime overhead when disabled.

Features

• Manual markers via mark(), start(), and end() • Function-level profiling via call() • Automatic jax.named_scope integration for clearer JAX traces • Safety checks to ensure the profiling flag is static at trace time • Aggregation across repeated calls with a readable summary table

Basic usage inside JIT (manual markers):

if params.profile:
    jit_profiler.mark("process_action:start")
with jax.named_scope("process_action"):
    ...
if params.profile:
    jit_profiler.mark("process_action:end")

Function-wrapping usage inside JIT (recommended):

action_mask = jit_profiler.call(
    params.profile,
    mask_slots,
    state,
    params,
    name="mask_actions",  # optional, defaults to fn.__name__
)

Block-style usage inside JIT:

jit_profiler.start(params.profile, "action_logic")
...
jit_profiler.end(params.profile, "action_logic")

Notes

• The enabled flag must be a Python bool known at trace time (e.g. params.profile with pytree_node=False). • Passing a traced or JAX boolean will raise a TypeError. • All timing is wall-clock time measured on the host, not device time.

After execution (outside JIT):

jit_profiler.summary()
Source code in xlron/environments/wrappers.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
class JitProfiler:
    """Wall-clock profiler for JAX JIT-compiled code.

    On CPU:
        • Uses host callbacks for fine-grained section timing.

    On GPU:
        • Automatically switches to *first-call-only* timing.
        • Measures compilation + first execution latency.
        • Fine-grained per-call timings are intentionally disabled
          to avoid misleading synchronization artifacts.

    This profiler records host-side timestamps using `jax.debug.callback`,
    allowing coarse wall-clock profiling of sections inside JIT-compiled code.
    Profiling is designed to be gated by a *static* Python boolean (e.g.
    `params.profile`) so that all profiling logic is resolved at trace time and
    introduces zero runtime overhead when disabled.

    Features
    --------
    • Manual markers via `mark()`, `start()`, and `end()`
    • Function-level profiling via `call()`
    • Automatic `jax.named_scope` integration for clearer JAX traces
    • Safety checks to ensure the profiling flag is static at trace time
    • Aggregation across repeated calls with a readable summary table

    Basic usage inside JIT (manual markers):

        if params.profile:
            jit_profiler.mark("process_action:start")
        with jax.named_scope("process_action"):
            ...
        if params.profile:
            jit_profiler.mark("process_action:end")

    Function-wrapping usage inside JIT (recommended):

        action_mask = jit_profiler.call(
            params.profile,
            mask_slots,
            state,
            params,
            name="mask_actions",  # optional, defaults to fn.__name__
        )

    Block-style usage inside JIT:

        jit_profiler.start(params.profile, "action_logic")
        ...
        jit_profiler.end(params.profile, "action_logic")

    Notes
    -----
    • The `enabled` flag *must* be a Python `bool` known at trace time
        (e.g. `params.profile` with `pytree_node=False`).
    • Passing a traced or JAX boolean will raise a `TypeError`.
    • All timing is wall-clock time measured on the host, not device time.

    After execution (outside JIT):

        jit_profiler.summary()
    """

    def __init__(self):
        self._timestamps: list[tuple[str, float]] = []
        self._backend = jax.default_backend()
        self._is_gpu = self._backend == "gpu"
        self._warned_gpu = False
        self._seen_first_call: set[str] = set()

        if self._is_gpu and not self._warned_gpu:
            print(
                "JitProfiler warning:\n"
                "  GPU backend detected. Fine-grained host-side timings inside JIT\n"
                "  are unreliable due to asynchronous execution.\n"
                "  `call()` will record ONLY first-call (compile + first execution)\n"
                "  latency per section.\n"
                "  Use jax.profiler / TensorBoard / Nsight for steady-state GPU timing."
            )
            self._warned_gpu = True

    def _record(self, label):
        self._timestamps.append((str(label), time.time()))

    @staticmethod
    def _assert_static_bool(x, name="enabled"):
        if not isinstance(x, bool):
            raise TypeError(
                f"JitProfiler.call(): `{name}` must be a Python bool "
                "(static at trace time), e.g. params.profile"
            )

    def mark(self, label: str):
        """Insert a timing marker. Safe to call inside JIT."""
        jax.debug.callback(self._record, label)

    def reset(self):
        """Clear all recorded timestamps and first-call tracking."""
        self._timestamps.clear()
        self._seen_first_call.clear()

    def start(self, enabled: bool, name: str):
        """Insert a start marker for a block."""
        self._assert_static_bool(enabled)
        if enabled:
            self.mark(f"{name}:start")

    def end(self, enabled: bool, name: str):
        """Insert an end marker for a block."""
        self._assert_static_bool(enabled)
        if enabled:
            self.mark(f"{name}:end")

    # -----------------------
    # GPU-only first-call path
    # -----------------------

    def _call_first_only(self, enabled: bool, fn, *args, name=None, **kwargs):
        """Record compile + first execution latency (GPU only)."""
        self._assert_static_bool(enabled)

        section = name or fn.__name__

        if section in self._seen_first_call or not enabled:
            return fn(*args, **kwargs)

        self._seen_first_call.add(section)

        start_time = time.time()
        out = fn(*args, **kwargs)
        out = jax.block_until_ready(out)
        elapsed = time.time() - start_time

        # Append synthetic start/end entries so summary sees them
        self._timestamps.append((f"{section}:start", start_time))
        self._timestamps.append((f"{section}:end", start_time + elapsed))

        # Also keep a :first entry for clarity
        self._timestamps.append((f"{section}:first", elapsed))

        return out

    # -----------------------
    # Public API
    # -----------------------

    def call(self, enabled: bool, fn, *args, name: str | None = None, **kwargs):
        """Profile a function call inside JIT-compiled code.

        CPU:
            Fine-grained section timing via callbacks.

        GPU:
            Records only first-call (compile + first execution) latency.
        """
        self._assert_static_bool(enabled)

        if self._is_gpu:
            return self._call_first_only(enabled, fn, *args, name=name, **kwargs)

        # CPU path
        section = name or fn.__name__
        if enabled:
            self.mark(f"{section}:start")
        with jax.named_scope(section):
            out = fn(*args, **kwargs)
        if enabled:
            self.mark(f"{section}:end")
        return out

    # -----------------------
    # Summary
    # -----------------------

    def summary(self):
        """Print timing breakdown from collected start/end marker pairs.

        Expects markers in the format "name:start" and "name:end".
        Aggregates across repeated calls (e.g. many step_env invocations).

        Also reports GPU `:first` entries if present.
        """
        if len(self._timestamps) < 2:
            print("JitProfiler: not enough markers recorded.")
            return

        totals: dict[str, float] = defaultdict(float)
        counts: dict[str, int] = defaultdict(int)
        order: list[str] = []
        pending: dict[str, float] = {}

        # Aggregate :start / :end
        for label, ts in self._timestamps:
            if label.endswith(":start"):
                name = label[: -len(":start")]
                pending[name] = ts
            elif label.endswith(":end"):
                name = label[: -len(":end")]
                if name in pending:
                    elapsed = ts - pending.pop(name)
                    totals[name] += elapsed
                    counts[name] += 1
                    if name not in order:
                        order.append(name)

        # Include any :first entries for GPU
        for label, val in self._timestamps:
            if label.endswith(":first"):
                name = label[: -len(":first")]
                totals[name] += val
                counts[name] += 1
                if name not in order:
                    order.append(name)

        if not totals:
            print("JitProfiler: no matched start/end pairs found.")
            return

        total_wall = sum(totals.values())
        header = f"{'Section':<30} {'Calls':>8} {'Total (s)':>10} {'Mean (us)':>10} {'%':>6}"
        print("\n" + "=" * len(header))
        print("JIT PROFILER SUMMARY")
        if self._backend.upper() == "GPU":
            print("  (GPU backend --> profile only indicates first-call latencies)")
        print("=" * len(header))
        print(header)
        print("-" * len(header))
        for name in order:
            n = counts[name]
            total_t = totals[name]
            mean_us = 1e6 * total_t / n
            pct = 100.0 * total_t / total_wall if total_wall > 0 else 0.0
            print(f"{name:<30} {n:>8} {total_t:>10.4f} {mean_us:>10.1f} {pct:>5.1f}%")
        print("-" * len(header))
        print(f"{'TOTAL':<30} {'':>8} {total_wall:>10.4f}")
        print("=" * len(header) + "\n")

call(enabled, fn, *args, name=None, **kwargs)

Profile a function call inside JIT-compiled code.

CPU

Fine-grained section timing via callbacks.

GPU

Records only first-call (compile + first execution) latency.

Source code in xlron/environments/wrappers.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def call(self, enabled: bool, fn, *args, name: str | None = None, **kwargs):
    """Profile a function call inside JIT-compiled code.

    CPU:
        Fine-grained section timing via callbacks.

    GPU:
        Records only first-call (compile + first execution) latency.
    """
    self._assert_static_bool(enabled)

    if self._is_gpu:
        return self._call_first_only(enabled, fn, *args, name=name, **kwargs)

    # CPU path
    section = name or fn.__name__
    if enabled:
        self.mark(f"{section}:start")
    with jax.named_scope(section):
        out = fn(*args, **kwargs)
    if enabled:
        self.mark(f"{section}:end")
    return out

end(enabled, name)

Insert an end marker for a block.

Source code in xlron/environments/wrappers.py
436
437
438
439
440
def end(self, enabled: bool, name: str):
    """Insert an end marker for a block."""
    self._assert_static_bool(enabled)
    if enabled:
        self.mark(f"{name}:end")

mark(label)

Insert a timing marker. Safe to call inside JIT.

Source code in xlron/environments/wrappers.py
421
422
423
def mark(self, label: str):
    """Insert a timing marker. Safe to call inside JIT."""
    jax.debug.callback(self._record, label)

reset()

Clear all recorded timestamps and first-call tracking.

Source code in xlron/environments/wrappers.py
425
426
427
428
def reset(self):
    """Clear all recorded timestamps and first-call tracking."""
    self._timestamps.clear()
    self._seen_first_call.clear()

start(enabled, name)

Insert a start marker for a block.

Source code in xlron/environments/wrappers.py
430
431
432
433
434
def start(self, enabled: bool, name: str):
    """Insert a start marker for a block."""
    self._assert_static_bool(enabled)
    if enabled:
        self.mark(f"{name}:start")

summary()

Print timing breakdown from collected start/end marker pairs.

Expects markers in the format "name:start" and "name:end". Aggregates across repeated calls (e.g. many step_env invocations).

Also reports GPU :first entries if present.

Source code in xlron/environments/wrappers.py
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
535
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
def summary(self):
    """Print timing breakdown from collected start/end marker pairs.

    Expects markers in the format "name:start" and "name:end".
    Aggregates across repeated calls (e.g. many step_env invocations).

    Also reports GPU `:first` entries if present.
    """
    if len(self._timestamps) < 2:
        print("JitProfiler: not enough markers recorded.")
        return

    totals: dict[str, float] = defaultdict(float)
    counts: dict[str, int] = defaultdict(int)
    order: list[str] = []
    pending: dict[str, float] = {}

    # Aggregate :start / :end
    for label, ts in self._timestamps:
        if label.endswith(":start"):
            name = label[: -len(":start")]
            pending[name] = ts
        elif label.endswith(":end"):
            name = label[: -len(":end")]
            if name in pending:
                elapsed = ts - pending.pop(name)
                totals[name] += elapsed
                counts[name] += 1
                if name not in order:
                    order.append(name)

    # Include any :first entries for GPU
    for label, val in self._timestamps:
        if label.endswith(":first"):
            name = label[: -len(":first")]
            totals[name] += val
            counts[name] += 1
            if name not in order:
                order.append(name)

    if not totals:
        print("JitProfiler: no matched start/end pairs found.")
        return

    total_wall = sum(totals.values())
    header = f"{'Section':<30} {'Calls':>8} {'Total (s)':>10} {'Mean (us)':>10} {'%':>6}"
    print("\n" + "=" * len(header))
    print("JIT PROFILER SUMMARY")
    if self._backend.upper() == "GPU":
        print("  (GPU backend --> profile only indicates first-call latencies)")
    print("=" * len(header))
    print(header)
    print("-" * len(header))
    for name in order:
        n = counts[name]
        total_t = totals[name]
        mean_us = 1e6 * total_t / n
        pct = 100.0 * total_t / total_wall if total_wall > 0 else 0.0
        print(f"{name:<30} {n:>8} {total_t:>10.4f} {mean_us:>10.1f} {pct:>5.1f}%")
    print("-" * len(header))
    print(f"{'TOTAL':<30} {'':>8} {total_wall:>10.4f}")
    print("=" * len(header) + "\n")

LogWrapper

Bases: GymnaxWrapper

Log the episode returns and lengths. Modified from: https://github.com/RobertTLange/gymnax/blob/master/gymnax/wrappers/purerl.py

Source code in xlron/environments/wrappers.py
 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
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
class LogWrapper(GymnaxWrapper):
    """Log the episode returns and lengths.
    Modified from: https://github.com/RobertTLange/gymnax/blob/master/gymnax/wrappers/purerl.py
    """

    def __init__(self, env: environment.Environment):
        super().__init__(env)

    @partial(jax.jit, static_argnums=(0,))
    def reset(
        self,
        key: chex.PRNGKey,
        params: Optional[RSAEnvParams] = None,
        state: Optional[RSAEnvState] = None,
    ) -> Tuple[Array, LogEnvState]:
        obs, env_state = self._env.reset(key, params, state)
        log_state = LogEnvState(
            env_state=env_state,
            lengths=jnp.array(0, dtype=dtype_config.LARGE_INT_DTYPE),
            returns=jnp.array(0, dtype=dtype_config.REWARD_DTYPE),
            cum_returns=jnp.array(0, dtype=dtype_config.LARGE_FLOAT_DTYPE),
            accepted_services=jnp.array(0, dtype=dtype_config.LARGE_INT_DTYPE),
            accepted_bitrate=jnp.array(0, dtype=dtype_config.LARGE_FLOAT_DTYPE),
            total_bitrate=jnp.array(0, dtype=dtype_config.LARGE_FLOAT_DTYPE),
            utilisation=jnp.array(0, dtype=dtype_config.LARGE_FLOAT_DTYPE),
            fragmentation=jnp.array(0, dtype=dtype_config.LARGE_FLOAT_DTYPE),
            blocked_spectrum=jnp.array(0, dtype=dtype_config.LARGE_INT_DTYPE),
            blocked_snr=jnp.array(0, dtype=dtype_config.LARGE_INT_DTYPE),
            blocked_power=jnp.array(0, dtype=dtype_config.LARGE_INT_DTYPE),
            terminal=jnp.array(False),
            truncated=jnp.array(False),
        )
        return obs, log_state

    @partial(jax.jit, static_argnums=(0,))
    def step(
        self,
        key: chex.PRNGKey,
        log_state: LogEnvState,
        action: Union[int, float] | Tuple[Union[int, float], Union[int, float]],
        params: RSAEnvParams,
    ) -> Tuple[Array, LogEnvState, float, bool, bool, dict]:
        # Keep the pre-step state: the action/request fields logged below must describe
        # the request the action was taken for, but step_env's generate_request replaces
        # request_array/current_time/holding_time with the next request's values
        prev_env_state = log_state.env_state
        obs, env_state, reward, terminal, truncated, info = self._env.step(
            key, log_state.env_state, action, params
        )
        done = jnp.logical_or(terminal, truncated)
        # Use pre-reset metrics from info (stashed in step_env before auto-reset)
        accepted_services = info.pop("_accepted_services")
        accepted_bitrate = info.pop("_accepted_bitrate")
        total_bitrate = info.pop("_total_bitrate")
        # Defaults: RSA-family envs no longer stash per-step utilisation or
        # fragmentation (log_metrics computes both per increment from the final
        # state); VONE still stashes utilisation.
        utilisation = info.pop("_utilisation", jnp.array(0, dtype=dtype_config.LARGE_FLOAT_DTYPE))
        fragmentation = info.pop(
            "_fragmentation", jnp.array(0, dtype=dtype_config.LARGE_FLOAT_DTYPE)
        )
        # Blocking-cause counters are only stashed by GN-model envs; default to 0 elsewhere
        zero_count = jnp.array(0, dtype=dtype_config.LARGE_INT_DTYPE)
        blocked_spectrum = info.pop("_blocked_spectrum", zero_count)
        blocked_snr = info.pop("_blocked_snr", zero_count)
        blocked_power = info.pop("_blocked_power", zero_count)
        # Compute final episode length (for reporting) before resetting
        episode_length = log_state.lengths + 1
        cum_returns = log_state.cum_returns + reward
        log_state = LogEnvState(
            env_state=env_state,
            # Reset lengths for next episode on done, otherwise keep accumulating
            lengths=episode_length * (1 - done),
            returns=jnp.asarray(reward, dtype=dtype_config.REWARD_DTYPE),
            cum_returns=cum_returns * (1 - done),
            accepted_services=accepted_services,
            accepted_bitrate=accepted_bitrate,
            total_bitrate=total_bitrate,
            utilisation=utilisation,
            fragmentation=fragmentation,
            blocked_spectrum=blocked_spectrum,
            blocked_snr=blocked_snr,
            blocked_power=blocked_power,
            terminal=terminal,
            truncated=truncated,
        )
        # Report the pre-reset values so the done step carries the correct
        # final episode metrics (no shift workaround needed in process_metrics)
        info["lengths"] = episode_length
        info["returns"] = log_state.returns
        info["cum_returns"] = cum_returns
        info["accepted_services"] = log_state.accepted_services
        info["accepted_bitrate"] = log_state.accepted_bitrate
        info["total_bitrate"] = log_state.total_bitrate
        info["utilisation"] = log_state.utilisation
        info["fragmentation"] = log_state.fragmentation
        # Report the blocking-cause breakdown for GN-model envs only (params is static,
        # so info keys are consistent for a given env type)
        if isinstance(params, GNModelEnvParams):
            info["blocked_spectrum"] = log_state.blocked_spectrum
            info["blocked_snr"] = log_state.blocked_snr
            info["blocked_power"] = log_state.blocked_power
        info["terminal"] = terminal
        info["truncated"] = truncated
        # First check if we're dealing with a GN-model env (RSA or RMSA variant; both
        # params classes derive from GNModelEnvParams)
        is_gn_params = isinstance(params, GNModelEnvParams)

        # For GN-model params, unpack the action. The action is [path_slot_action,
        # launch_power] when the RL agent controls launch power, or a bare
        # path_slot_action otherwise (e.g. GNN path policy with fixed launch power)
        # - mirror process_action's handling.
        if is_gn_params:
            action = jnp.atleast_1d(action)
            power_action = (
                action[1]
                if action.shape[0] > 1
                else jnp.asarray(
                    params.default_launch_power,
                    dtype=dtype_config.LARGE_FLOAT_DTYPE,
                )
            )
            action = action[0]
            info["launch_power"] = power_action

        # Now, if we need to log actions OR we have RSA params, compute the common fields
        if is_gn_params or params.log_actions:
            # Compute common fields from the pre-step state (see prev_env_state above)
            nodes_sd, dr_request = read_rsa_request(prev_env_state.request_array)
            source, dest = nodes_sd
            i = get_path_indices(
                params,
                source,
                dest,
                params.k_paths,
                params.num_nodes,
                directed=params.directed_graph,
            ).astype(jnp.int32)
            path_index, slot_index = process_path_action(prev_env_state, params, action)

            # Set common info
            info["path_index"] = i + path_index
            info["slot_index"] = slot_index
            info["source"] = source
            info["dest"] = dest
            info["data_rate"] = dr_request

            # RSA-GN-specific throughput info (use pre-reset value from step_env; only
            # the RSA-GN state tracks throughput, so the RMSA variant has no "_throughput")
            if is_gn_params and "_throughput" in info:
                info["throughput"] = info.pop("_throughput")

            # Logging-specific info
            if params.log_actions:
                # RSA-specific logging
                if is_gn_params:
                    # Index with the global path row (node-pair offset + k-index),
                    # unpacking bits if the path-link array is bit-packed
                    path = params.path_link_array[(i + path_index).astype(jnp.int32)]
                    if params.pack_path_bits:
                        path = jnp.unpackbits(path)[: params.num_links]
                    # Post-step link_snr_array so the placement is reflected; pass the
                    # state so the logged SNR includes path-level ROADM ASE, matching
                    # the SNR used by the masking/acceptance checks
                    info["path_snr"] = get_snr_for_path(
                        path, env_state.link_snr_array, params, env_state
                    )[slot_index.astype(jnp.int32)]
                # Common logging fields: use the pre-step state so the times belong to
                # the request being logged (step_env's generate_request advances them)
                info["arrival_time"] = prev_env_state.current_time[0]
                info["departure_time"] = (
                    prev_env_state.current_time[0] + prev_env_state.holding_time[0]
                )
        return obs, log_state, reward, terminal, truncated, info

    def _tree_flatten(self) -> Tuple[Tuple[Any, ...], Tuple[Any, ...]]:
        children = ()  # arrays / dynamic values
        aux_data = (self._env,)  # static values, e.g. env params
        return (children, aux_data)

    @classmethod
    def _tree_unflatten(cls, aux_data: Tuple[Any, ...], children: Tuple[Any, ...]) -> "LogWrapper":
        return cls(*children, *aux_data)

Profiler

Simple wall-clock profiler that tracks named sections.

Usage

profiler = Profiler()

with profiler.section("compilation"): ...

for i in range(10): with profiler.section("training_step", frames=1000): ...

profiler.summary()

Source code in xlron/environments/wrappers.py
233
234
235
236
237
238
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
273
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
299
300
301
302
303
304
class Profiler:
    """Simple wall-clock profiler that tracks named sections.

    Usage:
        profiler = Profiler()

        with profiler.section("compilation"):
            ...

        for i in range(10):
            with profiler.section("training_step", frames=1000):
                ...

        profiler.summary()
    """

    def __init__(self, enabled: bool = True):
        self.enabled = enabled
        # Each key maps to a list of (elapsed_secs, frames) tuples
        self._records: dict[str, list[tuple[float, int | None]]] = {}
        self._order: list[str] = []  # Insertion order of section names

    def section(self, tag: str, frames: int | None = None) -> "_ProfileSection":
        """Return a context manager that times the enclosed block.

        Args:
            tag: Name for this section. Repeated uses accumulate.
            frames: Optional work-unit count (e.g. timesteps) for throughput.
        """
        return _ProfileSection(self, tag, frames)

    def record(self, tag: str, elapsed: float, frames: int | None = None):
        """Record and print a section timed elsewhere (e.g. overlapping other work)."""
        self._record(tag, elapsed, frames)
        msg = tag + (": Elapsed time=%.2fs" % elapsed)
        if frames:
            msg += ", FPS=%.2e" % (frames / elapsed)
        print(msg)

    def _record(self, tag: str, elapsed: float, frames: int | None):
        if not self.enabled:
            return
        if tag not in self._records:
            self._records[tag] = []
            self._order.append(tag)
        self._records[tag].append((elapsed, frames))

    def summary(self):
        """Print a table summarising all recorded sections."""
        if not self._records:
            return
        total_wall = sum(e for entries in self._records.values() for e, _ in entries)
        header = (
            f"{'Section':<30} {'Calls':>6} {'Total (s)':>10} {'Mean (s)':>10} {'%':>6} {'FPS':>12}"
        )
        print("\n" + "=" * len(header))
        print("PROFILER SUMMARY")
        print("=" * len(header))
        print(header)
        print("-" * len(header))
        for tag in self._order:
            entries = self._records[tag]
            n = len(entries)
            total_t = sum(e for e, _ in entries)
            mean_t = total_t / n
            pct = 100.0 * total_t / total_wall if total_wall > 0 else 0.0
            total_frames = sum(f for _, f in entries if f is not None)
            fps_str = f"{total_frames / total_t:.2e}" if total_frames and total_t > 0 else ""
            print(f"{tag:<30} {n:>6} {total_t:>10.2f} {mean_t:>10.4f} {pct:>5.1f}% {fps_str:>12}")
        print("-" * len(header))
        print(f"{'TOTAL':<30} {'':>6} {total_wall:>10.2f}")
        print("=" * len(header) + "\n")

record(tag, elapsed, frames=None)

Record and print a section timed elsewhere (e.g. overlapping other work).

Source code in xlron/environments/wrappers.py
264
265
266
267
268
269
270
def record(self, tag: str, elapsed: float, frames: int | None = None):
    """Record and print a section timed elsewhere (e.g. overlapping other work)."""
    self._record(tag, elapsed, frames)
    msg = tag + (": Elapsed time=%.2fs" % elapsed)
    if frames:
        msg += ", FPS=%.2e" % (frames / elapsed)
    print(msg)

section(tag, frames=None)

Return a context manager that times the enclosed block.

Parameters:

Name Type Description Default
tag str

Name for this section. Repeated uses accumulate.

required
frames int | None

Optional work-unit count (e.g. timesteps) for throughput.

None
Source code in xlron/environments/wrappers.py
255
256
257
258
259
260
261
262
def section(self, tag: str, frames: int | None = None) -> "_ProfileSection":
    """Return a context manager that times the enclosed block.

    Args:
        tag: Name for this section. Repeated uses accumulate.
        frames: Optional work-unit count (e.g. timesteps) for throughput.
    """
    return _ProfileSection(self, tag, frames)

summary()

Print a table summarising all recorded sections.

Source code in xlron/environments/wrappers.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def summary(self):
    """Print a table summarising all recorded sections."""
    if not self._records:
        return
    total_wall = sum(e for entries in self._records.values() for e, _ in entries)
    header = (
        f"{'Section':<30} {'Calls':>6} {'Total (s)':>10} {'Mean (s)':>10} {'%':>6} {'FPS':>12}"
    )
    print("\n" + "=" * len(header))
    print("PROFILER SUMMARY")
    print("=" * len(header))
    print(header)
    print("-" * len(header))
    for tag in self._order:
        entries = self._records[tag]
        n = len(entries)
        total_t = sum(e for e, _ in entries)
        mean_t = total_t / n
        pct = 100.0 * total_t / total_wall if total_wall > 0 else 0.0
        total_frames = sum(f for _, f in entries if f is not None)
        fps_str = f"{total_frames / total_t:.2e}" if total_frames and total_t > 0 else ""
        print(f"{tag:<30} {n:>6} {total_t:>10.2f} {mean_t:>10.4f} {pct:>5.1f}% {fps_str:>12}")
    print("-" * len(header))
    print(f"{'TOTAL':<30} {'':>6} {total_wall:>10.2f}")
    print("=" * len(header) + "\n")

TimeIt

Context manager for timing execution of code blocks.

Source code in xlron/environments/wrappers.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
class TimeIt:
    """Context manager for timing execution of code blocks."""

    def __init__(self, tag, frames=None):
        self.tag = tag
        self.frames = frames

    def __enter__(self):
        self.start = timeit.default_timer()
        return self

    def __exit__(self, *args):
        self.elapsed_secs = timeit.default_timer() - self.start
        msg = self.tag + (": Elapsed time=%.2fs" % self.elapsed_secs)
        if self.frames:
            msg += ", FPS=%.2e" % (self.frames / self.elapsed_secs)
        print(msg)

Environment functions

aggregate_slots(full_mask, params)

Aggregate slot mask via max-pooling.

Source code in xlron/environments/env_funcs.py
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
@jax.jit
def aggregate_slots(full_mask: Array, params: EnvParams) -> Array:
    """Aggregate slot mask via max-pooling."""
    num_actions = math.ceil(params.link_resources / params.aggregate_slots)

    # Full mask has shape (k_paths * link_resources,)
    # Pad to make divisible by aggregate_slots
    pad_size = num_actions * params.aggregate_slots - params.link_resources
    if pad_size > 0:
        full_mask = full_mask.reshape((params.k_paths, params.link_resources))
        full_mask = jnp.pad(full_mask, ((0, 0), (0, pad_size)), constant_values=0)

    # Reshape to (k_paths, num_actions, aggregate_slots) and max over windows
    reshaped = full_mask.reshape(params.k_paths, num_actions, params.aggregate_slots)
    agg_mask = jnp.max(reshaped, axis=2).reshape(-1)

    return agg_mask

calculate_fragmentation(link_slot_array)

Calculate mean external spectrum fragmentation across links.

External fragmentation per link = 1 - largest_free_block / total_free_slots. It is 0 when each link's free capacity is contiguous (or the link is completely full/empty) and approaches 1 as free slots are scattered into many small blocks.

Occupancy follows the same convention as the utilisation metric: any non-zero value counts as occupied (in-service slots are stored as negative values). Uses an O(links x slots) cumulative-max scan (no NxN block-size matrices as in find_block_sizes), so it is cheap enough to compute on the hot path every step.

Parameters:

Name Type Description Default
link_slot_array Array

Link-slot occupancy array of shape (num_links, num_slots)

required

Returns:

Type Description
Array

Scalar mean external fragmentation across links

Source code in xlron/environments/env_funcs.py
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
def calculate_fragmentation(link_slot_array: Array) -> Array:
    """Calculate mean external spectrum fragmentation across links.

    External fragmentation per link = 1 - largest_free_block / total_free_slots.
    It is 0 when each link's free capacity is contiguous (or the link is completely
    full/empty) and approaches 1 as free slots are scattered into many small blocks.

    Occupancy follows the same convention as the utilisation metric: any non-zero
    value counts as occupied (in-service slots are stored as negative values).
    Uses an O(links x slots) cumulative-max scan (no NxN block-size matrices as in
    find_block_sizes), so it is cheap enough to compute on the hot path every step.

    Args:
        link_slot_array: Link-slot occupancy array of shape (num_links, num_slots)

    Returns:
        Scalar mean external fragmentation across links
    """
    occupied = link_slot_array != 0
    num_slots = link_slot_array.shape[1]
    slot_indices = jnp.arange(num_slots, dtype=dtype_config.INDEX_DTYPE)[None, :]
    # Index of the most recent occupied slot at or before each position (-1 if none),
    # so (slot_index - last_occupied) is the length of the free run ending at each slot
    last_occupied = jax.lax.cummax(jnp.where(occupied, slot_indices, -1), axis=1)
    free_run_lengths = jnp.where(occupied, 0, slot_indices - last_occupied)
    largest_free_block = jnp.max(free_run_lengths, axis=1)
    total_free_slots = jnp.sum(~occupied, axis=1)
    # Fully-occupied links have no free capacity to fragment, so report 0
    fragmentation_per_link = jnp.where(
        total_free_slots > 0,
        1.0 - largest_free_block / jnp.maximum(total_free_slots, 1),
        0.0,
    )
    return jnp.mean(fragmentation_per_link).astype(dtype_config.LARGE_FLOAT_DTYPE)

calculate_utilisation(link_slot_array)

Spectrum utilisation over usable slots.

Band-gap sentinels (-1) are neither occupied nor usable spectrum, so positively-occupied slots are counted over the usable (non-gap) slots only. Computed per logging increment from the final state (not per step: the two full-array reductions cost measurable time on the hot path and the value is a slowly-varying state property).

Source code in xlron/environments/env_funcs.py
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
@jax.jit
def calculate_utilisation(link_slot_array: Array) -> Array:
    """Spectrum utilisation over usable slots.

    Band-gap sentinels (-1) are neither occupied nor usable spectrum, so
    positively-occupied slots are counted over the usable (non-gap) slots only.
    Computed per logging increment from the final state (not per step: the two
    full-array reductions cost measurable time on the hot path and the value is
    a slowly-varying state property).
    """
    occupied_slots = jnp.count_nonzero(link_slot_array > 0)
    usable_slots = jnp.count_nonzero(link_slot_array >= 0)
    return (occupied_slots / jnp.maximum(usable_slots, 1)).astype(dtype_config.LARGE_FLOAT_DTYPE)

channel_entries(bandwidth, power, centre, capacity, pallas=False)

Compact one link's per-slot channel row to one GN entry per channel.

Returns (take, expand): take(x, fill) gathers a per-slot array x (..., slots) at each channel's first signal slot, giving (..., capacity) entries in slot order, with fill beyond the last channel; expand(values, broadcast, fill) maps (capacity,) per-channel values back to slots: to every signal slot of the channel with broadcast, else to its first signal slot only, and fill on the other slots. capacity must bound the link's channels (max_channels_per_link); the GN model then evaluates capacity entries instead of one per slot, and the gather from the compact result is also the broadcast to the channel's slots. With pallas, the index and owner come from one compaction kernel (kernels.compact) instead of a scan and a search.

Source code in xlron/environments/env_funcs.py
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
def channel_entries(
    bandwidth: Array, power: Array, centre: Array, capacity: int, pallas: bool = False
):
    """Compact one link's per-slot channel row to one GN entry per channel.

    Returns (take, expand): take(x, fill) gathers a per-slot array x (..., slots)
    at each channel's first signal slot, giving (..., capacity) entries in slot
    order, with fill beyond the last channel; expand(values, broadcast, fill)
    maps (capacity,) per-channel values back to slots: to every signal slot of
    the channel with broadcast, else to its first signal slot only, and fill on
    the other slots. capacity must bound the link's channels
    (max_channels_per_link); the GN model then evaluates capacity entries
    instead of one per slot, and the gather from the compact result is also the
    broadcast to the channel's slots. With pallas, the index and owner come from
    one compaction kernel (kernels.compact) instead of a scan and a search.
    """
    from xlron.kernels.compact import MAX_ELEMENTS

    _, _, first, signal = channel_physics_rows(bandwidth, power, centre)
    slots = bandwidth.shape[-1]
    if pallas and slots <= MAX_ELEMENTS:
        from xlron.kernels.compact import compact_true_indices

        index, total, owner = compact_true_indices(first, ranks=True)
        index = index[:capacity]
        valid = jnp.arange(capacity) < total
    else:
        count = jnp.cumsum(first.astype(jnp.int32))  # channels starting at or before each slot
        owner = count - 1
        index = jnp.searchsorted(
            count, jnp.arange(1, capacity + 1, dtype=jnp.int32), side="left", method="scan_unrolled"
        )
        valid = index < slots
        index = jnp.minimum(index, slots - 1)

    def take(x, fill=None):
        entries = jnp.take(x, index, axis=-1)
        return entries if fill is None else jnp.where(valid, entries, jnp.asarray(fill, x.dtype))

    def expand(values, broadcast=True, fill=-1e5):
        keep = signal if broadcast else first
        entry = values[jnp.clip(owner, 0, capacity - 1)]
        return jnp.where(keep, entry, jnp.asarray(fill, values.dtype))

    return take, expand

channel_physics_rows(bandwidth, power, centre)

One GN entry per channel from per-slot channel rows (last axis = slots).

Returns (bandwidth, power, first, signal): bandwidth and power kept only on each channel's first signal slot (first) and zero elsewhere, and signal, True on every signal slot. A channel is a run of signal slots (nonzero bandwidth) with one centre frequency; two channels on a link never share a centre, so a change of centre separates adjacent ones.

Source code in xlron/environments/env_funcs.py
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
def channel_physics_rows(bandwidth: Array, power: Array, centre: Array):
    """One GN entry per channel from per-slot channel rows (last axis = slots).

    Returns (bandwidth, power, first, signal): bandwidth and power kept only on
    each channel's first signal slot (`first`) and zero elsewhere, and `signal`,
    True on every signal slot. A channel is a run of signal slots (nonzero
    bandwidth) with one centre frequency; two channels on a link never share a
    centre, so a change of centre separates adjacent ones.
    """
    signal = bandwidth != 0
    previous_signal = jnp.concatenate((jnp.zeros_like(signal[..., :1]), signal[..., :-1]), axis=-1)
    previous_centre = jnp.concatenate((centre[..., :1], centre[..., :-1]), axis=-1)
    first = signal & ~(previous_signal & (previous_centre == centre))
    return (
        jnp.where(first, bandwidth, jnp.zeros((), bandwidth.dtype)),
        jnp.where(first, power, jnp.zeros((), power.dtype)),
        first,
        signal,
    )

channel_slot_mask(initial_slot_index, num_slots, params)

(link_resources,) True on the signal slots of a channel (its guard slots excluded).

Source code in xlron/environments/env_funcs.py
4092
4093
4094
4095
4096
4097
4098
4099
def channel_slot_mask(
    initial_slot_index: Array, num_slots: Array, params: RSAGNModelEnvParams
) -> Array:
    """(link_resources,) True on the signal slots of a channel (its guard slots excluded)."""
    slots = jnp.arange(params.link_resources)
    return (slots >= initial_slot_index) & (
        slots < initial_slot_index + signal_slot_count(num_slots, params)
    )

check_action_rmsa_gn_model(state, action_info, params)

Check if action is valid for RSA GN model Args: state (EnvState): Environment state params (EnvParams): Environment parameters action (Array): Action array Returns: bool: True if action is invalid, False if action is valid

Source code in xlron/environments/env_funcs.py
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
@jax.jit
def check_action_rmsa_gn_model(
    state: GNModelEnvState, action_info: ActionInfo, params: GNModelEnvParams
) -> bool:
    """Check if action is valid for RSA GN model
    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
        action (Array): Action array
    Returns:
        bool: True if action is invalid, False if action is valid
    """
    rsa_check, snr_sufficient_check, power_check = check_action_rmsa_gn_model_components(
        state, action_info, params
    )
    return jnp.any(
        jnp.stack(
            (
                rsa_check,
                snr_sufficient_check,
                power_check,
            )
        )
    )

check_action_rmsa_gn_model_components(state, action_info, params)

Compute the individual acceptance checks for the RMSA GN model.

The three checks correspond to the possible blocking causes: spectrum contention, insufficient SNR, and per-fibre power budget. step_env uses the components to count blocking causes without recomputing them; check_action_rmsa_gn_model aggregates them into the overall validity check.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
action_info ActionInfo

Action info

required
params EnvParams

Environment parameters

required

Returns: tuple: (rsa_check, snr_sufficient_check, power_check) - each truthy if the corresponding check failed (action invalid)

Source code in xlron/environments/env_funcs.py
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
@jax.jit
def check_action_rmsa_gn_model_components(
    state: GNModelEnvState, action_info: ActionInfo, params: GNModelEnvParams
) -> tuple:
    """Compute the individual acceptance checks for the RMSA GN model.

    The three checks correspond to the possible blocking causes:
    spectrum contention, insufficient SNR, and per-fibre power budget.
    step_env uses the components to count blocking causes without recomputing them;
    check_action_rmsa_gn_model aggregates them into the overall validity check.

    Args:
        state (EnvState): Environment state
        action_info (ActionInfo): Action info
        params (EnvParams): Environment parameters
    Returns:
        tuple: (rsa_check, snr_sufficient_check, power_check) - each truthy if the
        corresponding check failed (action invalid)
    """
    rmsa_params = cast(RMSAGNModelEnvParams, params)
    rmsa_state = cast(RMSAGNModelEnvState, state)
    existing_required = None
    if rmsa_params.existing_snr_margin > 0:
        before = rmsa_state.replace(
            path_index_array=rmsa_state.path_index_array_prev,
            channel_centre_bw_array=rmsa_state.channel_centre_bw_array_prev,
            channel_power_array=rmsa_state.channel_power_array_prev,
            channel_centre_freq_array=rmsa_state.channel_centre_freq_array_prev,
            modulation_format_index_array=rmsa_state.modulation_format_index_array_prev,
        )
        existing_required = get_existing_snr_requirements(before, rmsa_params)
    snr_sufficient_check = check_snr_sufficient(
        rmsa_state, rmsa_params, existing_required=existing_required
    )
    rsa_check = check_action_rsa(state, action_info, params)
    # Check total power per link doesn't exceed max_power_per_fibre
    total_power = compute_total_power_per_link(
        state.channel_power_array, state.path_index_array, state.channel_centre_freq_array
    )
    power_check = jnp.any(total_power > params.max_power_per_fibre)
    return rsa_check, snr_sufficient_check, power_check

check_action_rsa(state, action_info, params)

Differentiable version of check_action_rsa.

Parameters:

Name Type Description Default
state

Current environment state

required
temperature

Controls sharpness of sigmoid

required

Returns:

Type Description

Continuous value that behaves like the original boolean check

Source code in xlron/environments/env_funcs.py
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
def check_action_rsa(state, action_info, params):
    """
    Differentiable version of check_action_rsa.

    Args:
        state: Current environment state
        temperature: Controls sharpness of sigmoid

    Returns:
        Continuous value that behaves like the original boolean check
    """
    # Calculate differentiable version of each check
    spectrum_reuse_check = differentiable_check_no_spectrum_reuse(state, action_info, params)
    overflow_check = check_slot_overflow(state, action_info, params)
    no_action_check = check_no_op(state, action_info, params)
    unique_path_check = check_real_path(state, action_info, params)
    # For multiple checks, use a differentiable version of "any"
    # Instead of jnp.any, use max to combine checks
    combined_check = jnp.max(
        jnp.stack(
            [
                spectrum_reuse_check,
                overflow_check,
                no_action_check,
                unique_path_check,
            ]
        )
    )
    return combined_check

check_action_rsa_prestate(state, action_info, params)

Validity check for plain RSA/RMSA/RWA actions, evaluated on the PRE-implementation state (non-differentiable mode only; the differentiable mode needs the soft implement/check/undo flow for gradients).

Semantically identical to check_action_rsa run after implement_path_action: a plain-RSA action fails iff (a) any slot in the requested window [initial_slot, initial_slot + num_slots) is occupied (nonzero) on any path link -- exactly when the speculative allocation would produce a value > 1 -- or (b) the window overflows the spectrum end, or (c) the action is the no-op (path_index >= k_paths), or (d) the path is a dummy. Reads only a (num_links, max_slots) window of link_slot_array instead of speculatively writing and rescanning the full (num_links, link_resources) array. Relies on the same invariant as mask_slots: required slots for any request never exceed params.max_slots (max_slots is computed in make_env from max_bw at the worst spectral efficiency).

Source code in xlron/environments/env_funcs.py
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
def check_action_rsa_prestate(state: EnvState, action_info: ActionInfo, params: RSAEnvParams):
    """Validity check for plain RSA/RMSA/RWA actions, evaluated on the PRE-implementation
    state (non-differentiable mode only; the differentiable mode needs the soft
    implement/check/undo flow for gradients).

    Semantically identical to check_action_rsa run after implement_path_action: a plain-RSA
    action fails iff (a) any slot in the requested window [initial_slot, initial_slot +
    num_slots) is occupied (nonzero) on any path link -- exactly when the speculative
    allocation would produce a value > 1 -- or (b) the window overflows the spectrum end,
    or (c) the action is the no-op (path_index >= k_paths), or (d) the path is a dummy.
    Reads only a (num_links, max_slots) window of link_slot_array instead of speculatively
    writing and rescanning the full (num_links, link_resources) array. Relies on the same
    invariant as mask_slots: required slots for any request never exceed params.max_slots
    (max_slots is computed in make_env from max_bw at the worst spectral efficiency).
    """
    # Windowed spectrum-reuse check on the pre-implementation state
    window_cols = action_info.initial_slot_index.astype(dtype_config.INDEX_DTYPE) + jnp.arange(
        params.max_slots, dtype=dtype_config.INDEX_DTYPE
    )
    # Out-of-range columns read as 0 (free); the overflow check below rejects windows
    # that extend past the spectrum end.
    window = jnp.take(
        state.link_slot_array, window_cols, axis=1, mode="fill", fill_value=0
    )  # (num_links, max_slots)
    in_window = jnp.arange(params.max_slots) < action_info.num_slots  # (max_slots,)
    on_path = action_info.path != 0  # (num_links,)
    spectrum_reuse_check = jnp.any((window != 0) & in_window[None, :] & on_path[:, None])

    overflow_check = check_slot_overflow(state, action_info, params)
    no_action_check = check_no_op(state, action_info, params)
    unique_path_check = check_real_path(state, action_info, params)
    return jnp.max(
        jnp.stack(
            [
                spectrum_reuse_check,
                overflow_check,
                no_action_check,
                unique_path_check,
            ]
        )
    )

check_no_op(state, action_info, params)

Check for the "NO OP" action. This will be the maximum valid action idex + 1, resulting in a path index exceeding K paths.

Source code in xlron/environments/env_funcs.py
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
def check_no_op(state: EnvState, action_info: ActionInfo, params: EnvParams):
    """Check for the "NO OP" action.
    This will be the maximum valid action idex + 1,
    resulting in a path index exceeding K paths."""
    overflow = differentiable_compare(
        action_info.path_index,
        params.k_paths,
        op_type=">=",
        temperature=params.temperature,
        differentiable=params.differentiable,
    )
    return overflow

check_no_spectrum_reuse(state, action_info, params)

slot-=1 when used, should be zero when unoccupied, so check if any < -1 in slot array.

Parameters:

Name Type Description Default
link_slot_array

Link slot array (L x S) where L is number of links and S is number of slots

required

Returns:

Name Type Description
bool bool

True if check failed, False if check passed

Source code in xlron/environments/env_funcs.py
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
def check_no_spectrum_reuse(state: EnvState, action_info: ActionInfo, params: EnvParams) -> bool:
    """slot-=1 when used, should be zero when unoccupied, so check if any < -1 in slot array.

    Args:
        link_slot_array: Link slot array (L x S) where L is number of links and S is number of slots

    Returns:
        bool: True if check failed, False if check passed
    """
    path_mask = action_info.path[:, None]  # (num_links, 1)
    slots = path_mask * state.link_slot_array  # (num_links, link_resources)
    check = differentiable_compare(
        jnp.max(jnp.max(slots, axis=0)), 1, ">", params.temperature, params.differentiable
    )
    return check

check_real_path(state, action_info, params)

Check if path is a dummy (all-zeros). A valid path always uses at least one link.

Source code in xlron/environments/env_funcs.py
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
def check_real_path(state: EnvState, action_info: ActionInfo, params: EnvParams):
    """Check if path is a dummy (all-zeros). A valid path always uses at least one link."""
    is_dummy = differentiable_compare(
        jnp.max(action_info.path),
        0,
        op_type="==",
        temperature=params.temperature,
        differentiable=params.differentiable,
    )
    return is_dummy

check_slot_overflow(state, action_info, params)

If the action selects slot near the end, then the required slots can overflow and start filling from the start of the array, which might be free! To prevent this, we check the action index + required slots

Source code in xlron/environments/env_funcs.py
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
def check_slot_overflow(state: EnvState, action_info: ActionInfo, params: EnvParams):
    """If the action selects slot near the end, then the required slots can
    overflow and start filling from the start of the array, which might be free!
    To prevent this, we check the action index + required slots
    """
    overflow = differentiable_compare(
        action_info.initial_slot_index + action_info.num_slots,
        params.link_resources,
        op_type=">",
        temperature=params.temperature,
        differentiable=params.differentiable,
    )
    return overflow

check_snr_sufficient(state, params, *, existing_required=None, live=None)

Check if SNR is sufficient for all active connections.

live optionally supplies live_lightpath_mask(state) (e.g. a baseline mask plus one inserted channel) to avoid recomputing it. Args: state (EnvState): Environment state params (EnvParams): Environment parameters Returns: jnp.array: 1 if any active connection has insufficient SNR, else 0

Source code in xlron/environments/env_funcs.py
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
def check_snr_sufficient(
    state: RMSAGNModelEnvState,
    params: RMSAGNModelEnvParams,
    *,
    existing_required: Array | None = None,
    live: Array | None = None,
) -> Array:
    """Check if SNR is sufficient for all active connections.

    live optionally supplies live_lightpath_mask(state) (e.g. a baseline mask
    plus one inserted channel) to avoid recomputing it.
    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: 1 if any active connection has insufficient SNR, else 0
    """
    required_snr_array = get_required_snr_se_kurtosis_array(
        state.modulation_format_index_array, 2, params
    )
    if existing_required is not None:
        required_snr_array = jnp.maximum(required_snr_array, existing_required)
    lightpath_snr_array = get_lightpath_snr(state, params)
    # Only check slots that are actually occupied (have nonzero channel bandwidth)
    is_occupied = live_lightpath_mask(state, params) if live is None else live
    snr_insufficient = jnp.where(lightpath_snr_array >= required_snr_array, 0, 1)
    snr_insufficient = jnp.where(is_occupied, snr_insufficient, 0)
    return jnp.any(snr_insufficient)

complete_step_rmsa_gn_model(state, action_info, check, params)

Complete step for RMSA GN-model environments.

Same as RSA GN-model, plus modulation_format_index_array restoration.

Source code in xlron/environments/env_funcs.py
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
def complete_step_rmsa_gn_model(
    state: RMSAGNModelEnvState,
    action_info: ActionInfo,
    check: Array,
    params: RMSAGNModelEnvParams,
) -> RMSAGNModelEnvState:
    """Complete step for RMSA GN-model environments.

    Same as RSA GN-model, plus modulation_format_index_array restoration.
    """
    fail = check
    success = 1 - check

    fail_f_dep = fail.astype(state.link_slot_departure_array.dtype)
    fail_f_slots = fail.astype(state.link_slot_array.dtype)

    # --- Undo partial RSA allocation on failure ---
    state = state.replace(
        link_slot_array=(
            state.link_slot_array - (fail_f_slots * action_info.affected_slots_mask)
        ).astype(state.link_slot_array.dtype),
        link_slot_departure_array=state.link_slot_departure_array
        - (
            fail_f_dep * action_info.affected_slots_mask * (state.current_time + state.holding_time)
        ),
    )

    # --- Restore GN-model-specific state on failure ---
    one_m_fail = 1 - fail
    one_m_fail_f = one_m_fail.astype(state.channel_power_array.dtype)

    state = state.replace(
        channel_centre_bw_array=state.channel_centre_bw_array * one_m_fail_f
        + state.channel_centre_bw_array_prev * fail.astype(state.channel_centre_bw_array.dtype),
        channel_power_array=state.channel_power_array * one_m_fail_f
        + state.channel_power_array_prev * fail.astype(state.channel_power_array.dtype),
        channel_centre_freq_array=state.channel_centre_freq_array * one_m_fail_f
        + state.channel_centre_freq_array_prev * fail.astype(state.channel_centre_freq_array.dtype),
        path_index_array=state.path_index_array * one_m_fail.astype(state.path_index_array.dtype)
        + state.path_index_array_prev * fail.astype(state.path_index_array.dtype),
        modulation_format_index_array=state.modulation_format_index_array
        * one_m_fail.astype(state.modulation_format_index_array.dtype)
        + state.modulation_format_index_array_prev
        * fail.astype(state.modulation_format_index_array.dtype),
        # implement_action_rmsa_gn_model recomputed link_snr_array from the tentative
        # placement, so restore the pre-action SNR when the request is blocked
        link_snr_array=state.link_snr_array * one_m_fail.astype(state.link_snr_array.dtype)
        + state.link_snr_array_prev * fail.astype(state.link_snr_array.dtype),
    )

    # --- Book-keeping (always) ---
    state = state.replace(
        accepted_services=state.accepted_services + success,
        accepted_bitrate=state.accepted_bitrate + (success * action_info.requested_datarate),
        total_bitrate=state.total_bitrate + action_info.requested_datarate,
        total_timesteps=state.total_timesteps + 1,
    )
    return state

complete_step_rsa(state, action_info, check, params)

If the request is unsuccessful i.e. checks fail, then remove the partial (unfinalised) resource allocation. Partial resource allocation is indicated by negative time in link slot departure array. Check for values in link_slot_departure_array that are less than zero. If found, increase link_slot_array by +1 and link_slot_departure_array by current_time + holding_time of current request.

Parameters:

Name Type Description Default
state EnvState

Environment state

required

Returns:

Type Description
EnvState

Updated environment state

Source code in xlron/environments/env_funcs.py
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
def complete_step_rsa(
    state: EnvState, action_info: ActionInfo, check: Array, params: EnvParams
) -> EnvState:
    """If the request is unsuccessful i.e. checks fail, then remove the partial (unfinalised) resource allocation.
    Partial resource allocation is indicated by negative time in link slot departure array.
    Check for values in link_slot_departure_array that are less than zero.
    If found, increase link_slot_array by +1 and link_slot_departure_array by current_time + holding_time of current request.

    Args:
        state: Environment state

    Returns:
        Updated environment state
    """
    fail = check
    success = 1 - check
    state = state.replace(
        # Cast per-write: the fail*mask blend promotes; cast back to the occupancy dtype
        link_slot_array=(state.link_slot_array - (fail * action_info.affected_slots_mask)).astype(
            state.link_slot_array.dtype
        ),
        link_slot_departure_array=state.link_slot_departure_array
        - (fail * action_info.affected_slots_mask * (state.current_time + state.holding_time)),
        accepted_services=state.accepted_services + success,
        accepted_bitrate=state.accepted_bitrate + (success * action_info.requested_datarate),
        total_bitrate=state.total_bitrate + action_info.requested_datarate,
        total_timesteps=state.total_timesteps + 1,
    )
    return state

complete_step_rsa_gn_model(state, action_info, check, params)

Complete step for RSA GN-model environments.

On failure (check==1), undo partial slot allocation and restore GN-model auxiliary arrays from their *_prev snapshots.

Source code in xlron/environments/env_funcs.py
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
def complete_step_rsa_gn_model(
    state: RSAGNModelEnvState,
    action_info: ActionInfo,
    check: Array,
    params: RSAGNModelEnvParams,
) -> RSAGNModelEnvState:
    """Complete step for RSA GN-model environments.

    On failure (check==1), undo partial slot allocation and restore GN-model
    auxiliary arrays from their *_prev snapshots.
    """
    fail = check
    success = 1 - check

    # Cast once for broadcasting/multiplication
    fail_f_dep = fail.astype(state.link_slot_departure_array.dtype)
    fail_f_slots = fail.astype(state.link_slot_array.dtype)

    # --- Undo partial RSA allocation on failure (same pattern as complete_step_rsa) ---
    state = state.replace(
        link_slot_array=(
            state.link_slot_array - (fail_f_slots * action_info.affected_slots_mask)
        ).astype(state.link_slot_array.dtype),
        link_slot_departure_array=state.link_slot_departure_array
        - (
            fail_f_dep * action_info.affected_slots_mask * (state.current_time + state.holding_time)
        ),
    )

    # --- Restore GN-model-specific state on failure (blend current vs *_prev) ---
    one_m_fail = 1 - fail
    one_m_fail_f = one_m_fail.astype(state.channel_power_array.dtype)

    state = state.replace(
        channel_centre_bw_array=state.channel_centre_bw_array * one_m_fail_f
        + state.channel_centre_bw_array_prev * fail.astype(state.channel_centre_bw_array.dtype),
        channel_power_array=state.channel_power_array * one_m_fail_f
        + state.channel_power_array_prev * fail.astype(state.channel_power_array.dtype),
        channel_centre_freq_array=state.channel_centre_freq_array * one_m_fail_f
        + state.channel_centre_freq_array_prev * fail.astype(state.channel_centre_freq_array.dtype),
        path_index_array=state.path_index_array * one_m_fail.astype(state.path_index_array.dtype)
        + state.path_index_array_prev * fail.astype(state.path_index_array.dtype),
        link_snr_array=state.link_snr_array * one_m_fail.astype(state.link_snr_array.dtype)
        + state.link_snr_array_prev * fail.astype(state.link_snr_array.dtype),
    )

    # --- Resolve the pending registry entry (departure inserted negative by implement) ---
    # Confirmed entries carry positive departures, so exactly one row (the just-added one)
    # is negative here. On success flip it positive; on failure zero it and clear the row.
    dep_arr = state.active_lightpaths_array_departure
    neg = (dep_arr < zero).astype(dep_arr.dtype)
    success_dep = success.astype(dep_arr.dtype)
    fail_dep = fail.astype(dep_arr.dtype)
    # pending+success: *(1-2) flips the sign; pending+fail: *(1-1) zeroes; others unchanged
    new_dep_arr = dep_arr * (1 - 2 * neg * success_dep - neg * fail_dep)
    do_undo_lp = (neg * fail_dep).astype(state.active_lightpaths_array.dtype)

    state = state.replace(
        active_lightpaths_array=state.active_lightpaths_array * (1 - do_undo_lp)
        + jnp.array(-1, dtype=state.active_lightpaths_array.dtype) * do_undo_lp,
        active_lightpaths_array_departure=new_dep_arr,
    )

    # --- Book-keeping (always) ---
    state = state.replace(
        accepted_services=state.accepted_services + success,
        accepted_bitrate=state.accepted_bitrate + (success * action_info.requested_datarate),
        total_bitrate=state.total_bitrate + action_info.requested_datarate,
        total_timesteps=state.total_timesteps + 1,
    )
    return state

complete_step_rwalr(state, action_info, check, params)

Complete step for RWA-LR environments. Unlike complete_step_rsa, this does not modify link_slot_array on failure, because implement_action_rwalr already handles the undo via blending and link_slot_array stores a capacity mask (not an occupancy counter).

Source code in xlron/environments/env_funcs.py
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
def complete_step_rwalr(
    state: EnvState, action_info: ActionInfo, check: Array, params: EnvParams
) -> EnvState:
    """Complete step for RWA-LR environments.
    Unlike complete_step_rsa, this does not modify link_slot_array on failure,
    because implement_action_rwalr already handles the undo via blending and
    link_slot_array stores a capacity mask (not an occupancy counter).
    """
    fail = check
    success = 1 - check
    state = state.replace(
        link_slot_departure_array=state.link_slot_departure_array
        - (fail * action_info.affected_slots_mask * (state.current_time + state.holding_time)),
        accepted_services=state.accepted_services + success,
        accepted_bitrate=state.accepted_bitrate + (success * action_info.requested_datarate),
        total_bitrate=state.total_bitrate + action_info.requested_datarate,
        total_timesteps=state.total_timesteps + 1,
    )
    return state

compute_band_gaps_from_csv(link_resources, ref_lambda, slot_size, band_data_filepath=None)

Compute band gap slot positions from band definition CSV data.

Reads the band data CSV which defines frequency ranges for each optical band. Any slot whose centre frequency falls between bands is marked as a gap slot.

Parameters:

Name Type Description Default
link_resources int

Number of frequency slots per link.

required
ref_lambda float

Reference wavelength (m).

required
slot_size float

Slot width in GHz.

required
band_data_filepath str | None

Optional path to band data CSV file. Defaults to built-in band_data.csv.

None

Returns:

Type Description
Tuple[list, list]

Tuple of (gap_start_slots, gap_width_slots) as Python lists of ints.

Source code in xlron/environments/env_funcs.py
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
def compute_band_gaps_from_csv(
    link_resources: int,
    ref_lambda: float,
    slot_size: float,
    band_data_filepath: str | None = None,
) -> Tuple[list, list]:
    """Compute band gap slot positions from band definition CSV data.

    Reads the band data CSV which defines frequency ranges for each optical band.
    Any slot whose centre frequency falls between bands is marked as a gap slot.

    Args:
        link_resources: Number of frequency slots per link.
        ref_lambda: Reference wavelength (m).
        slot_size: Slot width in GHz.
        band_data_filepath: Optional path to band data CSV file. Defaults to
            built-in ``band_data.csv``.

    Returns:
        Tuple of (gap_start_slots, gap_width_slots) as Python lists of ints.
    """
    f = (
        pathlib.Path(band_data_filepath)
        if band_data_filepath
        else (
            pathlib.Path(__file__).parents[1].absolute()
            / "data"
            / "gn_model"
            / "band_data"
            / "band_data.csv"
        )
    )
    band_data = np.genfromtxt(f, delimiter=",", skip_header=1, usecols=(1, 2, 3, 4))
    # Columns: wavelength_min_nm, wavelength_max_nm, frequency_min_ghz, frequency_max_ghz
    band_freq_lo = band_data[:, 2]  # frequency_min_ghz
    band_freq_hi = band_data[:, 3]  # frequency_max_ghz

    # Compute per-slot absolute frequencies in GHz
    slot_centres = (np.arange(link_resources) - (link_resources - 1) / 2) * slot_size
    ref_frequency_ghz = c / ref_lambda / 1e9
    slot_frequencies_ghz = ref_frequency_ghz + slot_centres

    # Mark each slot as covered if its centre falls within any band's frequency range
    covered = np.zeros(link_resources, dtype=bool)
    for i, freq in enumerate(slot_frequencies_ghz):
        for j in range(len(band_freq_lo)):
            if band_freq_lo[j] <= freq <= band_freq_hi[j]:
                covered[i] = True
                break

    # Find contiguous runs of uncovered slots
    gap_start_slots = []
    gap_width_slots = []
    in_gap = False
    gap_start = 0
    for i in range(link_resources):
        if not covered[i] and not in_gap:
            gap_start = i
            in_gap = True
        elif covered[i] and in_gap:
            gap_start_slots.append(gap_start)
            gap_width_slots.append(i - gap_start)
            in_gap = False
    if in_gap:
        gap_start_slots.append(gap_start)
        gap_width_slots.append(link_resources - gap_start)

    return gap_start_slots, gap_width_slots

compute_band_layout(slot_size, band_preference, inter_band_gap_ghz=25.0, band_data_filepath=None, max_bandwidth_ghz=None, slots_per_band=None)

Compute band layout: link_resources, ref_lambda, slot centre frequencies, gaps, and orderings.

Given a slot size and selected bands, this function: 1. Determines how many slots fit in each band 2. Inserts 1 gap slot per inter-band boundary (representing inter_band_gap_ghz) 3. Computes absolute centre frequencies for every slot 4. Optionally trims bands to fit within a maximum bandwidth (e.g. for DRA) 5. Returns all derived quantities needed by make_env

Parameters:

Name Type Description Default
slot_size float

Spectral width of a frequency slot in GHz.

required
band_preference str

Comma-separated band names in preference order (e.g. "C,L,S").

required
inter_band_gap_ghz float

Physical spectral width of inter-band gap in GHz (~0.2 nm).

25.0
band_data_filepath str | None

Optional path to band data CSV. Defaults to built-in.

None
max_bandwidth_ghz float | None

If set, trim lowest-priority bands from the high-frequency end to keep total modulated bandwidth within this limit (e.g. 15000 for DRA).

None
slots_per_band str | None

If set, comma-separated slot counts per band (e.g. "45,45"). Overrides the default of filling each band's full spectral width.

None

Returns:

Type Description
dict

Dict with keys: link_resources, ref_lambda, slot_centre_freq_array (relative GHz),

dict

gap_start_slots, gap_width_slots, band_slot_order_ff, band_slot_order_lf.

Source code in xlron/environments/env_funcs.py
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
def compute_band_layout(
    slot_size: float,
    band_preference: str,
    inter_band_gap_ghz: float = 25.0,
    band_data_filepath: str | None = None,
    max_bandwidth_ghz: float | None = None,
    slots_per_band: str | None = None,
) -> dict:
    """Compute band layout: link_resources, ref_lambda, slot centre frequencies, gaps, and orderings.

    Given a slot size and selected bands, this function:
    1. Determines how many slots fit in each band
    2. Inserts 1 gap slot per inter-band boundary (representing ``inter_band_gap_ghz``)
    3. Computes absolute centre frequencies for every slot
    4. Optionally trims bands to fit within a maximum bandwidth (e.g. for DRA)
    5. Returns all derived quantities needed by make_env

    Args:
        slot_size: Spectral width of a frequency slot in GHz.
        band_preference: Comma-separated band names in preference order (e.g. "C,L,S").
        inter_band_gap_ghz: Physical spectral width of inter-band gap in GHz (~0.2 nm).
        band_data_filepath: Optional path to band data CSV. Defaults to built-in.
        max_bandwidth_ghz: If set, trim lowest-priority bands from the high-frequency end
            to keep total modulated bandwidth within this limit (e.g. 15000 for DRA).
        slots_per_band: If set, comma-separated slot counts per band (e.g. "45,45").
            Overrides the default of filling each band's full spectral width.

    Returns:
        Dict with keys: link_resources, ref_lambda, slot_centre_freq_array (relative GHz),
        gap_start_slots, gap_width_slots, band_slot_order_ff, band_slot_order_lf.
    """
    f = (
        pathlib.Path(band_data_filepath)
        if band_data_filepath
        else (
            pathlib.Path(__file__).parents[1].absolute()
            / "data"
            / "gn_model"
            / "band_data"
            / "band_data.csv"
        )
    )
    band_names_raw = np.genfromtxt(f, delimiter=",", skip_header=1, usecols=(0,), dtype=str)
    band_data_num = np.genfromtxt(f, delimiter=",", skip_header=1, usecols=(1, 2, 3, 4))
    band_freq_lo = band_data_num[:, 2]  # frequency_min_ghz
    band_freq_hi = band_data_num[:, 3]  # frequency_max_ghz

    # Build lookup: band_name -> (freq_lo, freq_hi)
    band_info = {}
    for i, name in enumerate(band_names_raw):
        band_info[name.upper()] = (band_freq_lo[i], band_freq_hi[i])

    # Parse preference list and filter to selected bands
    preference_list = [b.strip().upper() for b in band_preference.split(",")]
    selected = []
    for name in preference_list:
        if name not in band_info:
            raise ValueError(
                f"Band '{name}' not found in band data CSV. Available: {list(band_info.keys())}"
            )
        selected.append((name, band_info[name][0], band_info[name][1]))

    # Parse slots_per_band override
    slots_override = {}
    slots_per_band_list = None
    if slots_per_band is not None:
        slots_per_band_list = [int(x.strip()) for x in slots_per_band.split(",")]
        if len(slots_per_band_list) != len(preference_list):
            raise ValueError(
                f"slots_per_band has {len(slots_per_band_list)} entries but "
                f"band_preference has {len(preference_list)} bands"
            )
        # Map band name -> requested slot count (before frequency sorting)
        slots_override = dict(zip(preference_list, slots_per_band_list))

    # Sort selected bands by frequency (ascending)
    selected.sort(key=lambda x: x[1])

    # Compute slots per band and build the layout
    slot_centres_abs_ghz = []  # absolute centre frequencies in GHz
    gap_start_slots = []
    gap_width_slots = []
    band_slot_ranges = {}  # band_name -> list of slot indices (for ordering)

    slot_idx = 0
    for i, (name, freq_lo, freq_hi) in enumerate(selected):
        band_width = freq_hi - freq_lo
        max_slots_in_band = int(math.floor(band_width / slot_size))
        if slots_per_band_list is not None:
            num_slots_in_band = slots_override[name]
            if num_slots_in_band > max_slots_in_band:
                raise ValueError(
                    f"slots_per_band requests {num_slots_in_band} slots for {name}-band "
                    f"but only {max_slots_in_band} fit ({band_width:.0f} GHz / "
                    f"{slot_size:.1f} GHz)"
                )
        else:
            num_slots_in_band = max_slots_in_band

        # Slot centres within this band: start half a slot_size from the low edge
        band_start = freq_lo + slot_size / 2
        band_slots_indices = list(range(slot_idx, slot_idx + num_slots_in_band))
        band_slot_ranges[name] = band_slots_indices

        for j in range(num_slots_in_band):
            slot_centres_abs_ghz.append(band_start + j * slot_size)

        slot_idx += num_slots_in_band

        # Insert gap slot between this band and the next (if not the last band)
        if i < len(selected) - 1:
            next_freq_lo = selected[i + 1][1]
            gap_centre = (freq_hi + next_freq_lo) / 2
            gap_start_slots.append(slot_idx)
            gap_width_slots.append(1)
            slot_centres_abs_ghz.append(gap_centre)
            slot_idx += 1

    # Trim bands if total bandwidth exceeds max_bandwidth_ghz (e.g. for DRA)
    if max_bandwidth_ghz is not None:
        total_bw = (
            slot_centres_abs_ghz[-1] + slot_size / 2 - (slot_centres_abs_ghz[0] - slot_size / 2)
        )
        if total_bw > max_bandwidth_ghz:
            # Walk preference list in reverse (lowest priority first), trim from high-freq end
            reverse_pref = list(reversed(preference_list))
            for trim_band in reverse_pref:
                if total_bw <= max_bandwidth_ghz:
                    break
                band_slots = band_slot_ranges.get(trim_band, [])
                if not band_slots:
                    continue
                # How many slots to remove from this band?
                excess_ghz = total_bw - max_bandwidth_ghz
                slots_to_remove = min(len(band_slots), int(math.ceil(excess_ghz / slot_size)))
                if slots_to_remove >= len(band_slots):
                    slots_to_remove = len(band_slots)
                removed = slots_to_remove
                # Remove from high-frequency end of this band
                band_slot_ranges[trim_band] = (
                    band_slots[:-slots_to_remove] if slots_to_remove < len(band_slots) else []
                )
                print(
                    f"DRA bandwidth limit: trimmed {removed} slots "
                    f"({removed * slot_size:.0f} GHz) from high-frequency end of {trim_band}-band"
                )
                total_bw -= removed * slot_size

            # Rebuild slot_centres_abs_ghz and gaps from the trimmed band_slot_ranges
            # Determine which original slot indices to keep (band data slots only)
            kept_band_indices = set()
            for slots in band_slot_ranges.values():
                kept_band_indices.update(slots)
            # Rebuild layout: iterate selected bands in frequency order
            new_slot_centres = []
            new_gap_starts = []
            new_gap_widths = []
            new_band_slot_ranges = {}
            new_slot_idx = 0
            for i, (name, freq_lo, freq_hi) in enumerate(selected):
                old_slots = band_slot_ranges.get(name, [])
                if not old_slots:
                    continue
                num_kept = len(old_slots)
                band_start = freq_lo + slot_size / 2
                new_band_slot_ranges[name] = list(range(new_slot_idx, new_slot_idx + num_kept))
                for j in range(num_kept):
                    new_slot_centres.append(band_start + j * slot_size)
                new_slot_idx += num_kept
                # Insert gap if there's a next band with slots
                remaining_bands = [
                    (n, fl, fh) for n, fl, fh in selected[i + 1 :] if band_slot_ranges.get(n)
                ]
                if remaining_bands:
                    next_freq_lo = remaining_bands[0][1]
                    gap_centre = (freq_hi + next_freq_lo) / 2
                    new_gap_starts.append(new_slot_idx)
                    new_gap_widths.append(1)
                    new_slot_centres.append(gap_centre)
                    new_slot_idx += 1

            slot_centres_abs_ghz = new_slot_centres
            gap_start_slots = new_gap_starts
            gap_width_slots = new_gap_widths
            band_slot_ranges = new_band_slot_ranges
            slot_idx = new_slot_idx

    link_resources = slot_idx
    slot_centres_abs_ghz = np.array(slot_centres_abs_ghz, dtype=np.float64)

    # Compute ref_lambda as centre of the total frequency range
    total_freq_min = slot_centres_abs_ghz[0] - slot_size / 2
    total_freq_max = slot_centres_abs_ghz[-1] + slot_size / 2
    centre_freq_ghz = (total_freq_min + total_freq_max) / 2
    ref_lambda = c / (centre_freq_ghz * 1e9)

    # Convert to relative GHz offsets from ref_lambda
    ref_freq_ghz = c / ref_lambda / 1e9
    slot_centre_freq_rel_ghz = slot_centres_abs_ghz - ref_freq_ghz

    # Build band-preference slot orderings
    order_ff = []
    order_lf = []
    for name in preference_list:
        slots = band_slot_ranges.get(name, [])
        order_ff.extend(slots)
        order_lf.extend(reversed(slots))
    # Add any bands not in preference list (shouldn't happen, but for safety)
    for name, _, _ in selected:
        if name not in preference_list:
            slots = band_slot_ranges.get(name, [])
            order_ff.extend(slots)
            order_lf.extend(reversed(slots))
    # Gap slots last
    for gs in gap_start_slots:
        order_ff.append(gs)
        order_lf.append(gs)

    assert len(order_ff) == link_resources, (
        f"band_slot_order length {len(order_ff)} != link_resources {link_resources}"
    )

    # Build slot_to_band_index: maps each slot to its band index in preference_list order
    # Gap slots get -1
    slot_to_band_index = np.full(link_resources, -1, dtype=np.int32)
    for band_idx, name in enumerate(preference_list):
        for slot_idx_val in band_slot_ranges.get(name, []):
            slot_to_band_index[slot_idx_val] = band_idx

    return {
        "link_resources": link_resources,
        "ref_lambda": ref_lambda,
        "slot_centre_freq_array": slot_centre_freq_rel_ghz.astype(np.float32),
        "gap_start_slots": gap_start_slots,
        "gap_width_slots": gap_width_slots,
        "band_slot_order_ff": np.array(order_ff, dtype=np.int32),
        "band_slot_order_lf": np.array(order_lf, dtype=np.int32),
        "slot_to_band_index": slot_to_band_index,
    }

compute_band_slot_order(link_resources, ref_lambda, slot_size, band_preference, band_data_filepath=None)

Compute band-preference-ordered slot index arrays for first-fit and last-fit.

Parameters:

Name Type Description Default
link_resources int

Number of frequency slots per link.

required
ref_lambda float

Reference wavelength (m).

required
slot_size float

Slot width in GHz.

required
band_preference str

Comma-separated band names in preference order (e.g. "C,L,S").

required
band_data_filepath str | None

Optional path to band data CSV. Defaults to built-in.

None

Returns:

Type Description
ndarray

Tuple of (band_slot_order_ff, band_slot_order_lf) as numpy int32 arrays

ndarray

of shape (link_resources,).

Tuple[ndarray, ndarray]

band_slot_order_ff has slots ascending within each band, bands in preference order.

Tuple[ndarray, ndarray]

band_slot_order_lf has slots descending within each band, bands in preference order.

Source code in xlron/environments/env_funcs.py
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
def compute_band_slot_order(
    link_resources: int,
    ref_lambda: float,
    slot_size: float,
    band_preference: str,
    band_data_filepath: str | None = None,
) -> Tuple[np.ndarray, np.ndarray]:
    """Compute band-preference-ordered slot index arrays for first-fit and last-fit.

    Args:
        link_resources: Number of frequency slots per link.
        ref_lambda: Reference wavelength (m).
        slot_size: Slot width in GHz.
        band_preference: Comma-separated band names in preference order (e.g. "C,L,S").
        band_data_filepath: Optional path to band data CSV. Defaults to built-in.

    Returns:
        Tuple of (band_slot_order_ff, band_slot_order_lf) as numpy int32 arrays
        of shape (link_resources,).
        band_slot_order_ff has slots ascending within each band, bands in preference order.
        band_slot_order_lf has slots descending within each band, bands in preference order.
    """
    f = (
        pathlib.Path(band_data_filepath)
        if band_data_filepath
        else (
            pathlib.Path(__file__).parents[1].absolute()
            / "data"
            / "gn_model"
            / "band_data"
            / "band_data.csv"
        )
    )
    # Read band names (string column)
    band_names_raw = np.genfromtxt(f, delimiter=",", skip_header=1, usecols=(0,), dtype=str)
    band_names = list(band_names_raw)
    # Read numeric columns
    band_data_num = np.genfromtxt(f, delimiter=",", skip_header=1, usecols=(1, 2, 3, 4))
    band_freq_lo = band_data_num[:, 2]  # frequency_min_ghz
    band_freq_hi = band_data_num[:, 3]  # frequency_max_ghz

    # Compute per-slot frequencies
    slot_centres = (np.arange(link_resources) - (link_resources - 1) / 2) * slot_size
    ref_freq_ghz = c / ref_lambda / 1e9
    slot_freq_ghz = ref_freq_ghz + slot_centres

    # Assign each slot to a band
    band_slots = {name: [] for name in band_names}
    uncovered = []
    for i, freq in enumerate(slot_freq_ghz):
        assigned = False
        for j, name in enumerate(band_names):
            if band_freq_lo[j] <= freq <= band_freq_hi[j]:
                band_slots[name].append(i)
                assigned = True
                break
        if not assigned:
            uncovered.append(i)

    preference_list = [b.strip().upper() for b in band_preference.split(",")]

    order_ff = []
    order_lf = []
    # Preferred bands first
    for band_name in preference_list:
        slots = sorted(band_slots.get(band_name, []))
        order_ff.extend(slots)
        order_lf.extend(reversed(slots))
    # Then any bands not in the preference list (in CSV order)
    for name in band_names:
        if name not in preference_list:
            slots = sorted(band_slots.get(name, []))
            order_ff.extend(slots)
            order_lf.extend(reversed(slots))
    # Finally uncovered/gap slots
    order_ff.extend(uncovered)
    order_lf.extend(uncovered)

    assert len(order_ff) == link_resources, (
        f"band_slot_order length {len(order_ff)} != link_resources {link_resources}"
    )

    return np.array(order_ff, dtype=np.int32), np.array(order_lf, dtype=np.int32)

Compute total optical power per link by summing one power value per channel.

Each channel spans multiple contiguous slots with the same power value, path_index and centre frequency. Channel starts are detected where path_index OR centre frequency changes: two concurrent connections on the same k-path in adjacent slot blocks share a path index, but their centre frequencies always differ, so the frequency transition keeps them distinct (path index alone merged them, dropping the second block's power from the max_power_per_fibre checks).

Parameters:

Name Type Description Default
channel_power_array

(num_links, link_resources) per-channel power in linear Watts

required
path_index_array

(num_links, link_resources) lightpath index (-1 for empty)

required
channel_centre_freq_array

(num_links, link_resources) channel centre frequency

required

Returns: (num_links,) total optical power per link in linear Watts

Source code in xlron/environments/env_funcs.py
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
def compute_total_power_per_link(channel_power_array, path_index_array, channel_centre_freq_array):
    """Compute total optical power per link by summing one power value per channel.

    Each channel spans multiple contiguous slots with the same power value, path_index and
    centre frequency. Channel starts are detected where path_index OR centre frequency
    changes: two concurrent connections on the same k-path in adjacent slot blocks share a
    path index, but their centre frequencies always differ, so the frequency transition
    keeps them distinct (path index alone merged them, dropping the second block's power
    from the max_power_per_fibre checks).

    Args:
        channel_power_array: (num_links, link_resources) per-channel power in linear Watts
        path_index_array: (num_links, link_resources) lightpath index (-1 for empty)
        channel_centre_freq_array: (num_links, link_resources) channel centre frequency
    Returns:
        (num_links,) total optical power per link in linear Watts
    """
    occupied = path_index_array >= 0
    num_links = path_index_array.shape[0]
    prev_path_idx = jnp.concatenate(
        [
            jnp.full((num_links, 1), -1, dtype=path_index_array.dtype),
            path_index_array[:, :-1],
        ],
        axis=1,
    )
    prev_freq = jnp.concatenate(
        [
            jnp.full((num_links, 1), -1.0, dtype=channel_centre_freq_array.dtype),
            channel_centre_freq_array[:, :-1],
        ],
        axis=1,
    )
    is_channel_start = occupied & (
        (path_index_array != prev_path_idx) | (channel_centre_freq_array != prev_freq)
    )
    channel_start_powers = jnp.where(is_channel_start, channel_power_array, 0.0)
    return jnp.sum(channel_start_powers, axis=1)

convert_node_probs_to_traffic_matrix(node_probs)

Convert list of node probabilities to symmetric traffic matrix.

Parameters:

Name Type Description Default
node_probs list

node probabilities

required

Returns:

Name Type Description
traffic_matrix Array

traffic matrix

Source code in xlron/environments/env_funcs.py
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
def convert_node_probs_to_traffic_matrix(node_probs: list) -> Array:
    """Convert list of node probabilities to symmetric traffic matrix.

    Args:
        node_probs: node probabilities

    Returns:
        traffic_matrix: traffic matrix
    """
    node_probs = jnp.asarray(node_probs)
    matrix = jnp.outer(node_probs, node_probs).astype(dtype_config.SMALL_FLOAT_DTYPE)
    # Set lead diagonal to zero
    matrix = jnp.where(jnp.eye(matrix.shape[0]) == 1, 0, matrix)
    matrix = normalise_traffic_matrix(matrix)
    return matrix

count_until_next_one(array, position, temperature, differentiable=True)

Counts positions until the next 1 in the array. Made differentiable using straight-through gradient trick.

Parameters:

Name Type Description Default
array Array

Input array

required
position int

Starting position for counting

required
temperature float

Temperature for differentiable approximation

required
differentiable bool

If False, use non-differentiable operations

True

Returns:

Type Description
Array

Number of positions until the next 1

Source code in xlron/environments/env_funcs.py
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
def count_until_next_one(
    array: Array, position: int, temperature: float, differentiable: bool = True
) -> Array:
    """
    Counts positions until the next 1 in the array.
    Made differentiable using straight-through gradient trick.

    Args:
        array: Input array
        position: Starting position for counting
        temperature: Temperature for differentiable approximation
        differentiable: If False, use non-differentiable operations

    Returns:
        Number of positions until the next 1
    """
    # Add 1s to end so that end block is counted and slice shape can be fixed
    shape = array.shape[0]
    array = jnp.concatenate([array, jnp.ones(array.shape[0], dtype=dtype_config.LARGE_INT_DTYPE)])
    # Find the indices of 1 in the array
    one_indices = jax.lax.dynamic_slice(array, (position,), (shape,))
    # Use our differentiable_argmax helper
    next_one_idx = differentiable_argmax(
        one_indices, temperature=temperature, differentiable=differentiable
    )
    return next_one_idx + 1

count_until_previous_one(array, position, temperature, differentiable=True)

Counts positions until the previous 1 in the array. Made differentiable using straight-through gradient trick.

Parameters:

Name Type Description Default
array Array

Input array

required
position int

Starting position for counting backwards

required
temperature float

Temperature for differentiable approximation

required
differentiable bool

If False, use non-differentiable operations

True

Returns:

Type Description
int

Number of positions until the previous 1

Source code in xlron/environments/env_funcs.py
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
def count_until_previous_one(
    array: Array, position: int, temperature: float, differentiable: bool = True
) -> int:
    """
    Counts positions until the previous 1 in the array.
    Made differentiable using straight-through gradient trick.

    Args:
        array: Input array
        position: Starting position for counting backwards
        temperature: Temperature for differentiable approximation
        differentiable: If False, use non-differentiable operations

    Returns:
        Number of positions until the previous 1
    """
    # Add 1s to start so that end block is counted and slice shape can be fixed
    shape = array.shape[0]
    array = jnp.concatenate([jnp.ones(array.shape[0], dtype=dtype_config.LARGE_INT_DTYPE), array])
    # Find the indices of 1 in the array
    one_indices = jax.lax.dynamic_slice(array, (-shape - position,), (shape,))
    one_indices = jnp.flip(one_indices)
    # Use our differentiable_argmax helper
    prev_one_idx = differentiable_argmax(
        one_indices, temperature=temperature, differentiable=differentiable
    )
    return prev_one_idx + 1

create_run_name(config)

Create name for run based on config flags

Source code in xlron/environments/env_funcs.py
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
def create_run_name(config: Union[box.Box, dict]) -> str:
    """Create name for run based on config flags"""
    env_type = config["env_type"]
    topology = config["topology_name"]
    slots = config["link_resources"]
    gnn = "_GNN" if config["USE_GNN"] else ""
    incremental = "_INC" if config["incremental_loading"] else ""
    run_name = f"{env_type}_{topology}_{slots}{gnn}{incremental}".upper()
    if config["EVAL_HEURISTIC"]:
        run_name += f"_{config['path_heuristic']}"
        if env_type.lower() == "vone":
            run_name += f"_{config['node_heuristic']}"
    elif config["EVAL_MODEL"]:
        run_name += "_EVAL"
    return run_name

differentiable_check_no_spectrum_reuse(state, action_info, params)

Differentiable version of check_no_spectrum_reuse with improved gradient properties.

Parameters:

Name Type Description Default
link_slot_array

Link slot array (L x S) where L is number of links and S is number of slots

required
temperature

Controls the sharpness of the gradient response

required
differentiable

If False, return hard result directly without gradient approximation

required

Returns:

Type Description

A value that behaves like the original boolean check in forward pass

but has zero gradient when there are no violations and otherwise

has gradient pointing toward reducing violations

Source code in xlron/environments/env_funcs.py
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
def differentiable_check_no_spectrum_reuse(
    state: EnvState, action_info: ActionInfo, params: EnvParams
):
    """
    Differentiable version of check_no_spectrum_reuse with improved gradient properties.

    Args:
        link_slot_array: Link slot array (L x S) where L is number of links and S is number of slots
        temperature: Controls the sharpness of the gradient response
        differentiable: If False, return hard result directly without gradient approximation

    Returns:
        A value that behaves like the original boolean check in forward pass
        but has zero gradient when there are no violations and otherwise
        has gradient pointing toward reducing violations
    """
    # Hard result for forward pass (original behavior)
    hard_result = check_no_spectrum_reuse(state, action_info, params)

    # If not differentiable mode, return hard result directly
    if not params.differentiable:
        return hard_result

    # Measure violations: a slot value > 1 means double-occupation (collision)
    # After implement_path_action, link_slot_array += mask, so occupied=1, collision=2
    violations = jnp.maximum(0, state.link_slot_array - 1)

    # Any violation is considered a violation (alternatively can sum to discourage more egregious violations)
    # TODO - see if sum vs. max makes a difference in solution quality
    total_violation = jnp.max(violations)

    # Scale violations by temperature
    scaled_violation = params.temperature * total_violation

    # Use a function with zero gradient at zero: x²/(1+x²)
    # This function:
    # - Equals 0 when there are no violations
    # - Has gradient 0 when there are no violations
    # - Grows monotonically toward 1 as violations increase
    soft_result = (scaled_violation**2) / (1 + scaled_violation**2)

    # Apply straight-through trick
    return straight_through(hard_result, soft_result)

find_block_ends(path_slots)

Finds the end positions of blocks in the path slots.

Parameters:

Name Type Description Default
path_slots Array

Array of path slots

required

Returns:

Type Description
Array

Array with 1s at the end positions of blocks

Source code in xlron/environments/env_funcs.py
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
def find_block_ends(path_slots: Array) -> Array:
    """
    Finds the end positions of blocks in the path slots.

    Args:
        path_slots: Array of path slots

    Returns:
        Array with 1s at the end positions of blocks
    """
    transitions = jnp.diff(path_slots, append=1)  # Find transition 0 to 1
    return jnp.clip(transitions, 0, 1)

find_block_starts(path_slots)

Finds the starting positions of blocks in the path slots. Args: path_slots: Array of path slots

Returns:

Type Description
Array

Array with 1s at the starting positions of blocks

Source code in xlron/environments/env_funcs.py
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
def find_block_starts(path_slots: Array) -> Array:
    """
    Finds the starting positions of blocks in the path slots.
    Args:
        path_slots: Array of path slots

    Returns:
        Array with 1s at the starting positions of blocks
    """
    # Add a [1] at the beginning to find transitions from 1 to 0
    transitions = jnp.clip(jnp.diff(path_slots, prepend=1), -1, 0)  # Find transitions (1 to 0)
    return jnp.abs(transitions)

first_true_indices(mask, size)

jnp.nonzero(mask, size=size, fill_value=0)[0] for a 1-D mask, by binary search.

nonzero lowers to a scatter of every element into the output, which costs as much as the whole mask however small size is; the running count is monotone, so the n-th True entry is found by searching it for n.

Source code in xlron/environments/env_funcs.py
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
def first_true_indices(mask: Array, size: int) -> Array:
    """jnp.nonzero(mask, size=size, fill_value=0)[0] for a 1-D mask, by binary search.

    nonzero lowers to a scatter of every element into the output, which costs as
    much as the whole mask however small size is; the running count is monotone,
    so the n-th True entry is found by searching it for n.
    """
    count = jnp.cumsum(mask.astype(jnp.int32))
    indices = jnp.searchsorted(
        count, jnp.arange(1, size + 1, dtype=jnp.int32), side="left", method="scan_unrolled"
    )
    return jnp.where(indices < mask.shape[0], indices, 0).astype(jnp.int32)

generate_arrival_holding_times(key, params, arrival_rate, mean_service_holding_time)

Generate exponential arrival and holding times from a PRNG key.

Draws all required uniforms in a single fused call and applies inverse-transform sampling (see _arrival_holding_from_uniforms for the construction).

Parameters:

Name Type Description Default
key

PRNG key

required
params

Environment parameters

required
arrival_rate

Traced arrival rate (load / mean_service_holding_time)

required
mean_service_holding_time

Traced mean service holding time

required

Returns:

Name Type Description
arrival_time

Arrival time

holding_time

Holding time

Source code in xlron/environments/env_funcs.py
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
@jax.jit
def generate_arrival_holding_times(key, params, arrival_rate, mean_service_holding_time):
    """Generate exponential arrival and holding times from a PRNG key.

    Draws all required uniforms in a single fused call and applies inverse-transform
    sampling (see _arrival_holding_from_uniforms for the construction).

    Args:
        key: PRNG key
        params: Environment parameters
        arrival_rate: Traced arrival rate (load / mean_service_holding_time)
        mean_service_holding_time: Traced mean service holding time

    Returns:
        arrival_time: Arrival time
        holding_time: Holding time
    """
    num_holding = 5 if params.truncate_holding_time else 1
    u = jax.random.uniform(key, shape=(1 + num_holding,), dtype=dtype_config.TIME_DTYPE)
    return _arrival_holding_from_uniforms(
        u[0:1], u[1:], params, arrival_rate, mean_service_holding_time
    )

get_best_modulation_format_simple(state, path, initial_slot_index, params)

Get modulation format for lightpath. Assume worst case (least Gaussian) modulation format when calculating SNR. Args: state (EnvState): Environment state path (Array): Path array initial_slot_index (int): Initial slot index params (EnvParams): Environment parameters Returns: jnp.array: Acceptable modulation format indices

Source code in xlron/environments/env_funcs.py
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
@jax.jit
def get_best_modulation_format_simple(
    state: RMSAGNModelEnvState,
    path: Array,
    initial_slot_index: int,
    params: RMSAGNModelEnvParams,
) -> Array:
    """Get modulation format for lightpath.
    Assume worst case (least Gaussian) modulation format when calculating SNR.
    Args:
        state (EnvState): Environment state
        path (Array): Path array
        initial_slot_index (int): Initial slot index
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: Acceptable modulation format indices
    """
    link_snr_array = get_snr_link_array(state, params)
    snr_value = (
        get_snr_for_path(path, link_snr_array, params, state)[initial_slot_index]
        - params.snr_margin
    )  # Margin
    mod_format_count = params.modulations_array.shape[0]
    acceptable_mod_format_indices = jnp.arange(mod_format_count)
    req_snr = params.modulations_array[:, 2] + params.snr_margin
    acceptable_mod_format_indices = jnp.where(
        snr_value >= req_snr,
        acceptable_mod_format_indices,
        jnp.full((mod_format_count,), -2),
    )
    return acceptable_mod_format_indices

get_candidate_snr_evidence(state, candidate, affected, params, *, old_required=None, unchanged=None)

(minimum new-path SNR over affected slots, all existing paths sufficient).

old_required encodes inactive predicates as -inf; NaN/+inf thresholds keep rejecting. unchanged=(baseline_db, overlap_by_path) reuses the baseline SNR of paths that share no link with the candidate; their predicates still count.

Source code in xlron/environments/env_funcs.py
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
def get_candidate_snr_evidence(
    state: RMSAGNModelEnvState,
    candidate: RMSAGNModelEnvState,
    affected: Array,
    params: RMSAGNModelEnvParams,
    *,
    old_required: Array | None = None,
    unchanged=None,
):
    """(minimum new-path SNR over affected slots, all existing paths sufficient).

    old_required encodes inactive predicates as -inf; NaN/+inf thresholds keep
    rejecting. unchanged=(baseline_db, overlap_by_path) reuses the baseline SNR of
    paths that share no link with the candidate; their predicates still count.
    """
    required = get_required_snr_se_kurtosis_array(state.modulation_format_index_array, 2, params)
    encoded = (
        jnp.where(live_lightpath_mask(state, params), required, -jnp.inf)
        if old_required is None
        else old_required
    )
    if uses_pallas_kernels(params):
        from xlron.kernels.gn_path_snr import path_snr_pallas_from_state

        return path_snr_pallas_from_state(
            candidate, params, evidence=(encoded, affected), unchanged=unchanged
        )
    snr = get_lightpath_snr(candidate, params)
    if unchanged is not None:
        baseline, overlap = unchanged
        snr = jnp.where(overlap[candidate.path_index_array], snr, baseline)
    existing_ok = jnp.all(snr >= encoded)
    new_floor = jnp.min(jnp.where(affected, snr, jnp.inf))
    return new_floor, existing_ok

get_centre_frequency(initial_slot_index, num_slots, params)

Get centre frequency for new lightpath.

Looks up pre-computed per-slot centre frequencies from params.slot_centre_freq_array and returns the midpoint of the first and last slot in the channel. This correctly handles non-uniform slot spacing (e.g. inter-band gap slots).

Parameters:

Name Type Description Default
initial_slot_index Array

Index of the first slot of the channel.

required
num_slots float

Number of slots occupied by the channel.

required
params RSAGNModelEnvParams

Environment parameters.

required

Returns:

Name Type Description
Array Array

Centre frequency for new lightpath (relative GHz offset

Array

from ref_lambda).

Source code in xlron/environments/env_funcs.py
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
@jax.jit
def get_centre_frequency(
    initial_slot_index: int, num_slots: int, params: RSAGNModelEnvParams
) -> Array:
    """Get centre frequency for new lightpath.

    Looks up pre-computed per-slot centre frequencies from
    ``params.slot_centre_freq_array`` and returns the midpoint of the first
    and last slot in the channel.  This correctly handles non-uniform slot
    spacing (e.g. inter-band gap slots).

    Args:
        initial_slot_index (Array): Index of the first slot of the channel.
        num_slots (float): Number of slots occupied by the channel.
        params (RSAGNModelEnvParams): Environment parameters.

    Returns:
        Array: Centre frequency for new lightpath (relative GHz offset
        from ref_lambda).
    """
    slot_centres = params.slot_centre_freq_array  # (link_resources,) relative GHz
    initial_slot_index = jnp.asarray(initial_slot_index, dtype=dtype_config.INDEX_DTYPE)
    num_slots = jnp.asarray(num_slots, dtype=dtype_config.INDEX_DTYPE)
    first_slot_centre = slot_centres[initial_slot_index]
    last_slot_idx = jnp.minimum(initial_slot_index + num_slots - 1, params.link_resources - 1)
    last_slot_centre = slot_centres[last_slot_idx]
    return (first_slot_centre + last_slot_centre) / 2

get_channel_launch_power(state, path_action, power_action, initial_slot_index, num_slots, params)

Launch power [W] of a new channel: get_launch_power x its signal slots.

Configured launch powers (power_per_channel, the per-slot table, tabular and RL powers) are references per slot of signal bandwidth, i.e. a power spectral density, so every channel width launches at the same PSD (GNpy's PSD equalisation). Single-slot channels launch exactly the reference power.

Source code in xlron/environments/env_funcs.py
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
def get_channel_launch_power(
    state: GNModelEnvState,
    path_action: Array,
    power_action: Array,
    initial_slot_index: Array,
    num_slots: Array,
    params: GNModelEnvParams,
) -> Array:
    """Launch power [W] of a new channel: get_launch_power x its signal slots.

    Configured launch powers (power_per_channel, the per-slot table, tabular and
    RL powers) are references per slot of signal bandwidth, i.e. a power spectral
    density, so every channel width launches at the same PSD (GNpy's PSD
    equalisation). Single-slot channels launch exactly the reference power.
    """
    reference = get_launch_power(state, path_action, power_action, initial_slot_index, params)
    return reference * signal_slot_count(num_slots, params).astype(reference.dtype)

get_channel_values(initial_slot_index, num_slots, params)

(signal slots, signal width [GHz], centre frequency [GHz]) of a new channel.

num_slots includes the guard band, which carries no signal, so the centre is that of the signal slots and the width is signal slots x slot_size.

Source code in xlron/environments/env_funcs.py
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
def get_channel_values(
    initial_slot_index: Array, num_slots: Array, params: RSAGNModelEnvParams
) -> tuple[Array, Array, Array]:
    """(signal slots, signal width [GHz], centre frequency [GHz]) of a new channel.

    num_slots includes the guard band, which carries no signal, so the centre is
    that of the signal slots and the width is signal slots x slot_size.
    """
    signal = signal_slot_count(num_slots, params)
    width = signal.astype(jnp.float32) * params.slot_size
    return signal, width, get_centre_frequency(initial_slot_index, signal, params)

get_edge_disjoint_paths(graph)

Get edge disjoint paths between all nodes in graph.

Parameters:

Name Type Description Default
graph Graph

graph

required

Returns:

Name Type Description
dict Dict[int, Dict[int, List[Tuple[int, int]]]]

edge disjoint paths (path is list of edges)

Source code in xlron/environments/env_funcs.py
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
def get_edge_disjoint_paths(graph: nx.Graph) -> Dict[int, Dict[int, List[Tuple[int, int]]]]:
    """Get edge disjoint paths between all nodes in graph.

    Args:
        graph: graph

    Returns:
        dict: edge disjoint paths (path is list of edges)
    """
    result = {n: {} for n in graph}
    for n1, n2 in itertools.combinations(graph, 2):
        # Sort by number of links in path
        # TODO - sort by path length
        result[n1][n2] = sorted(list(nx.edge_disjoint_paths(graph, n1, n2)), key=len)
        result[n2][n1] = sorted(list(nx.edge_disjoint_paths(graph, n2, n1)), key=len)
    return result

get_existing_snr_requirements(state, params, baseline_path_snr=None)

Protect the target reserve, or remaining headroom after a departure.

A fixed reserve on an already depleted, unrelated path would itself freeze global admission. Cap the reserve at fresh pre-admission SNR, while always retaining the modulation minimum. Inactive predicates remain unconditional.

Source code in xlron/environments/env_funcs.py
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
def get_existing_snr_requirements(
    state: RMSAGNModelEnvState,
    params: RMSAGNModelEnvParams,
    baseline_path_snr: Array | None = None,
) -> Array:
    """Protect the target reserve, or remaining headroom after a departure.

    A fixed reserve on an already depleted, unrelated path would itself freeze
    global admission. Cap the reserve at fresh pre-admission SNR, while always
    retaining the modulation minimum. Inactive predicates remain unconditional.
    """
    required = get_required_snr_se_kurtosis_array(state.modulation_format_index_array, 2, params)
    if params.existing_snr_margin > 0:
        if baseline_path_snr is None:
            baseline_path_snr = get_lightpath_snr(
                state.replace(link_snr_array=get_snr_link_array(state, params)), params
            )
        required = jnp.maximum(
            required, jnp.minimum(required + params.existing_snr_margin, baseline_path_snr)
        )
    return jnp.where(live_lightpath_mask(state, params), required, -jnp.inf)

get_launch_power(state, path_action, power_action, initial_slot_index, params)

Get launch power for new lightpath. N.B. launch power is specified in dBm but is converted to linear units when stored in channel_power_array. This func returns linear units (mW). Path action is used to determine the launch power in the case of tabular launch power type. Power action is used to determine the launch power in the case of RL launch power type. During masking, power action is set as state.launch_power_array[0], which is set by the RL agent. Args: state (EnvState): Environment state path_action (Array): Action specifying path index (0 to k_paths-1) power_action (Array): Action specifying launch power in dBm initial_slot_index (Array): Initial slot index of the placement params (EnvParams): Environment parameters Returns: Array: Launch power for new lightpath

Source code in xlron/environments/env_funcs.py
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
@jax.jit
def get_launch_power(
    state: GNModelEnvState,
    path_action: Array,
    power_action: Array,
    initial_slot_index: Array,
    params: GNModelEnvParams,
) -> Array:
    """Get launch power for new lightpath. N.B. launch power is specified in dBm but is converted to linear units
    when stored in channel_power_array. This func returns linear units (mW).
    Path action is used to determine the launch power in the case of tabular launch power type.
    Power action is used to determine the launch power in the case of RL launch power type. During masking,
    power action is set as state.launch_power_array[0], which is set by the RL agent.
    Args:
        state (EnvState): Environment state
        path_action (Array): Action specifying path index (0 to k_paths-1)
        power_action (Array): Action specifying launch power in dBm
        initial_slot_index (Array): Initial slot index of the placement
        params (EnvParams): Environment parameters
    Returns:
        Array: Launch power for new lightpath
    """
    k_path_index, _ = process_path_action(state, params, path_action)
    initial_slot_index = jnp.asarray(initial_slot_index, dtype=jnp.int32)
    if params.launch_power_type == "fixed":
        return params.slot_launch_power_array[initial_slot_index]
    elif params.launch_power_type == "tabular":
        nodes_sd, requested_datarate = read_rsa_request(state.request_array)
        source, dest = nodes_sd
        i = get_path_indices(
            params,
            source,
            dest,
            params.k_paths,
            params.num_nodes,
            directed=params.directed_graph,
        ).astype(jnp.int32)
        return state.launch_power_array[i + k_path_index]
    elif params.launch_power_type == "rl":
        return power_action
    elif params.launch_power_type == "scaled":
        nodes_sd, requested_datarate = read_rsa_request(state.request_array)
        source, dest = nodes_sd
        i = get_path_indices(
            params,
            source,
            dest,
            params.k_paths,
            params.num_nodes,
            directed=params.directed_graph,
        )
        # Path lengths are per-path totals of span-summed link lengths, precomputed at
        # env creation. (Indexing the per-link length vector with a path index, and
        # taking the max over per-span partial sums, both produced garbage scalings here.)
        path_length = params.path_length_array[(i + k_path_index).astype(dtype_config.INDEX_DTYPE)]
        return params.slot_launch_power_array[initial_slot_index] * (
            path_length / params.max_path_length
        )
    else:
        raise ValueError(
            f"Invalid launch_power_type '{params.launch_power_type}'. "
            "Must be 'fixed', 'tabular', 'rl', or 'scaled'."
        )

get_lightpath_snr(state, params)

Accumulate full path SNR only for the paths referenced by link/slot state.

The sparse gather uses (links, slots, max_path_hops) work/storage instead of producing (all_possible_paths, slots) matrices, including during candidate masking. Padding is selected out before summation, so zero-SNR links outside a path cannot contaminate it with 0 * inf NaNs. With the Pallas backend the gather, ROADM ASE and dB conversion run in one kernel.

Source code in xlron/environments/env_funcs.py
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
def get_lightpath_snr(state: GNModelEnvState, params: GNModelEnvParams) -> Array:
    """Accumulate full path SNR only for the paths referenced by link/slot state.

    The sparse gather uses (links, slots, max_path_hops) work/storage instead of
    producing (all_possible_paths, slots) matrices, including during candidate
    masking. Padding is selected out before summation, so zero-SNR links outside
    a path cannot contaminate it with 0 * inf NaNs. With the Pallas backend the
    gather, ROADM ASE and dB conversion run in one kernel.
    """
    if uses_pallas_kernels(params):
        from xlron.kernels.gn_path_snr import path_snr_pallas_from_state

        return path_snr_pallas_from_state(state, params)
    slot_indices = jnp.arange(params.link_resources)[None, :, None]
    links = params.path_link_indices[state.path_index_array]
    valid = links < params.num_links
    safe_links = jnp.minimum(links, params.num_links - 1)
    link_snr = state.link_snr_array[safe_links, slot_indices]
    nsr = jnp.sum(jnp.where(valid, 1.0 / link_snr, 0.0), axis=-1)

    if hasattr(params, "roadm_express_loss"):
        num_express = jnp.maximum(jnp.sum(valid, axis=-1) - 1, 0)
        # Match argmax(incidence) == 0 for the empty/dummy path.
        first_link = jnp.where(valid[..., 0], links[..., 0], 0)
        slots = slot_indices[..., 0]
        ch_power = state.channel_power_array[first_link, slots]
        roadm_ase = isrs_gn_model.calculate_roadm_ase(
            roadm_express_loss=params.roadm_express_loss,
            roadm_add_drop_loss=params.roadm_add_drop_loss,
            roadm_noise_figure=params.roadm_noise_figure,
            num_roadm_express=num_express,
            ref_lambda=params.ref_lambda,
            ch_centre_i=state.channel_centre_freq_array[first_link, slots] * 1e9,
            ch_bandwidth_i=state.channel_centre_bw_array[first_link, slots] * 1e9,
        )
        roadm_ase = jnp.reshape(roadm_ase, ch_power.shape)
        nsr = nsr + jnp.where(ch_power > 0, roadm_ase / ch_power, 0.0)

    # Add transceiver noise once at path level (see get_snr_for_path)
    if hasattr(params, "transceiver_snr"):
        trx_snr_linear = isrs_gn_model.from_db(params.transceiver_snr)
        nsr_trx = jnp.where(trx_snr_linear > 1.0, 1.0 / trx_snr_linear, 0.0)
        nsr = nsr + nsr_trx

    return jnp.nan_to_num(isrs_gn_model.to_db(1 / nsr), nan=-50, neginf=-50, posinf=50)

get_line_graph_laplacian(graph)

Compute the Laplacian matrix of the line graph.

Parameters:

Name Type Description Default
graph Graph

NetworkX graph (original topology)

required

Returns:

Type Description
Array

Laplacian matrix of the line graph as a JAX array

Source code in xlron/environments/env_funcs.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def get_line_graph_laplacian(graph: nx.Graph) -> Array:
    """Compute the Laplacian matrix of the line graph.

    Args:
        graph: NetworkX graph (original topology)

    Returns:
        Laplacian matrix of the line graph as a JAX array
    """
    line_graph = make_line_graph(graph)
    if line_graph.is_directed():
        laplacian = nx.directed_laplacian_matrix(line_graph)
    else:
        laplacian = nx.laplacian_matrix(line_graph).todense()
    return jnp.array(laplacian, dtype=dtype_config.LARGE_FLOAT_DTYPE)

get_line_graph_spectral_features(graph, num_features)

Compute spectral features for edges using the line graph Laplacian.

These features are used as positional encodings for transformer architectures with WiRE (Wavelet-Induced Rotary Encodings).

Parameters:

Name Type Description Default
graph Graph

NetworkX graph (original topology)

required
num_features int

Number of spectral features to compute

required

Returns:

Type Description
Array

Array of shape (num_edges, num_features) containing eigenvectors of the

Array

line graph Laplacian, ordered by ascending eigenvalue magnitude.

Array

These serve as positional encodings for edge/link tokens.

Source code in xlron/environments/env_funcs.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def get_line_graph_spectral_features(graph: nx.Graph, num_features: int) -> Array:
    """Compute spectral features for edges using the line graph Laplacian.

    These features are used as positional encodings for transformer architectures
    with WiRE (Wavelet-Induced Rotary Encodings).

    Args:
        graph: NetworkX graph (original topology)
        num_features: Number of spectral features to compute

    Returns:
        Array of shape (num_edges, num_features) containing eigenvectors of the
        line graph Laplacian, ordered by ascending eigenvalue magnitude.
        These serve as positional encodings for edge/link tokens.
    """
    line_laplacian = get_line_graph_laplacian(graph)
    num_edges = line_laplacian.shape[0]
    # Clamp num_features to available dimensions
    actual_features = min(num_features, num_edges)
    eigenvalues, eigenvectors = jnp.linalg.eigh(line_laplacian)
    return eigenvectors[:, :actual_features].astype(dtype_config.LARGE_FLOAT_DTYPE)

Compute 4 link relevance features for the current request.

Parameters:

Name Type Description Default
paths Array

(k, E) binary path-link indicators

required
paths_quality Array

(k,) per-path quality score (higher = better). For RMSA: 1/required_slots (SE-derived). For RWA-LR: path capacity.

required
params RSAEnvParams

environment parameters

required

Returns:

Type Description

(E, 4) array with columns: 0: weighted_relevance - combined rank/quality weighted sum across paths 1: path_count - fraction of k paths using each link 2: best_rank - 1 - min_rank/k for links on any path, 0 otherwise 3: best_quality - max quality among paths through link, normalized

Source code in xlron/environments/env_funcs.py
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
def get_link_relevance_array(paths: Array, paths_quality: Array, params: RSAEnvParams):
    """Compute 4 link relevance features for the current request.

    Args:
        paths: (k, E) binary path-link indicators
        paths_quality: (k,) per-path quality score (higher = better).
            For RMSA: 1/required_slots (SE-derived). For RWA-LR: path capacity.
        params: environment parameters

    Returns:
        (E, 4) array with columns:
            0: weighted_relevance - combined rank/quality weighted sum across paths
            1: path_count - fraction of k paths using each link
            2: best_rank - 1 - min_rank/k for links on any path, 0 otherwise
            3: best_quality - max quality among paths through link, normalized
    """
    k = params.k_paths
    quality = paths_quality.flatten()  # (k,)

    # --- Feature 1: Weighted relevance ---
    ranks = jnp.arange(k)
    rank_weights = 1.0 / (ranks + 1.0)
    weights = rank_weights * quality
    weights = weights / (jnp.sum(weights) + 1e-8)
    weighted_paths = paths * weights[:, None]
    weighted_relevance = jnp.sum(weighted_paths, axis=0)  # (E,)

    # --- Feature 2: Path count - fraction of k paths using each link ---
    path_count = jnp.sum(paths, axis=0) / k  # (E,)

    # --- Feature 3: Best rank - 1 - min_rank/k for links on any path, 0 otherwise ---
    rank_per_path = jnp.arange(k).reshape(k, 1)  # (k, 1)
    # Where path uses link, use rank; otherwise use k (sentinel)
    rank_masked = jnp.where(paths > 0, rank_per_path, k)  # (k, E)
    min_rank = jnp.min(rank_masked, axis=0)  # (E,)
    on_any_path = (path_count > 0).astype(jnp.float32)  # (E,)
    best_rank = on_any_path * (1.0 - min_rank / k)  # (E,)

    # --- Feature 4: Best quality - max quality among paths through link, normalized ---
    max_quality = jnp.max(quality) + 1e-8
    quality_masked = jnp.where(paths > 0, quality[:, None], 0.0)  # (k, E)
    best_quality = jnp.max(quality_masked, axis=0) / max_quality  # (E,)

    return jnp.stack([weighted_relevance, path_count, best_rank, best_quality], axis=-1)  # (E, 4)

get_minimum_snr_of_channels_on_path(state, path, slot_index, req_slots, params)

Get the path SNR of the channel newly assigned at slot_index. N.B. this requires the link_snr_array to have already been calculated and present in state.

The channel has one SNR, broadcast to all its signal slots, so it is read at its first slot; req_slots (which includes the dark guard band) is kept for the API.

Source code in xlron/environments/env_funcs.py
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
@jax.jit
def get_minimum_snr_of_channels_on_path(
    state: RSAGNModelEnvState,
    path: Array,
    slot_index: Array,
    req_slots: int,
    params: RSAGNModelEnvParams,
) -> Array:
    """Get the path SNR of the channel newly assigned at slot_index.
    N.B. this requires the link_snr_array to have already been calculated and present in state.

    The channel has one SNR, broadcast to all its signal slots, so it is read at its
    first slot; req_slots (which includes the dark guard band) is kept for the API."""
    del req_slots
    return get_snr_for_path(path, state.link_snr_array, params, state)[slot_index]

get_obs_transformer(state, params)

Retrieves observation for transformer model.

Creates tokens for each link/edge. Column order: [wire_features | edge_features | traffic_marginals | request-specific...] where request-specific features are at the end so the critic can strip them.

Request-specific columns (stripped for critic): - holding_time (1 col, departure modes only) - request_size (1 col) - link_relevance (4 cols)

Parameters:

Name Type Description Default
state RSAEnvState

Environment state

required
params RSAEnvParams

Environment parameters

required

Returns:

Name Type Description
tokens Array

Array of shape (num_links, input_size)

Source code in xlron/environments/env_funcs.py
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
@jax.jit
def get_obs_transformer(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """Retrieves observation for transformer model.

    Creates tokens for each link/edge. Column order:
        [wire_features | edge_features | traffic_marginals | request-specific...]
    where request-specific features are at the end so the critic can strip them.

    Request-specific columns (stripped for critic):
        - holding_time (1 col, departure modes only)
        - request_size (1 col)
        - link_relevance (4 cols)

    Args:
        state: Environment state
        params: Environment parameters

    Returns:
        tokens: Array of shape (num_links, input_size)
    """
    # Get line graph spectral features (WiRE positional encodings)
    assert params.line_graph_spectral_features is not None, (
        "line_graph_spectral_features must be set when using transformer observations"
    )
    wire_features = params.line_graph_spectral_features

    # Get edge features based on traffic type (WITHOUT holding time - that's request-specific)
    if params.transformer_obs_type == "occupancy":
        edge_features = state.link_slot_array
    elif params.transformer_obs_type in ("snr", "occupancy_snr", "departure_snr", "lifetime_snr"):
        gn_state = cast(GNModelEnvState, state)
        gn_params = cast(GNModelEnvParams, params)
        # The physical cache is linear SNR. Keep empty channels at zero and
        # normalize finite dB features without modifying the physical values.
        snr_db = 10 * jnp.log10(jnp.maximum(gn_state.link_snr_array, 1e-10))
        snr_features = jnp.where(
            gn_state.channel_power_array > 0,
            jnp.clip(jnp.nan_to_num(snr_db, nan=0.0), 0, gn_params.max_snr) / gn_params.max_snr,
            0.0,
        )
        if params.transformer_obs_type == "lifetime_snr":
            remaining = state.link_slot_departure_array
            if not params.relative_arrival_times:
                remaining = remaining - state.current_time
            lifetime = 1.0 + jnp.log1p(jnp.maximum(remaining, 0) / state.mean_service_holding_time)
            status = jnp.where(
                state.link_slot_array < 0,
                -1.0,
                jnp.where(state.link_slot_array > 0, lifetime, 0.0),
            )
            # Smoothly compress finite tails without the legacy 0/30 dB clipping.
            finite_db = jnp.nan_to_num(snr_db, nan=0.0, posinf=100.0, neginf=-100.0)
            quality = jnp.where(
                gn_state.channel_power_array > 0,
                jnp.arcsinh(2.0 * finite_db / gn_params.max_snr - 1.0),
                0.0,
            )
            edge_features = jnp.concatenate((status, quality), axis=-1)
        elif params.transformer_obs_type == "occupancy_snr":
            edge_features = jnp.concatenate((state.link_slot_array, snr_features), axis=-1)
        elif params.transformer_obs_type == "departure_snr":
            departures = state.link_slot_departure_array / state.mean_service_holding_time
            edge_features = jnp.concatenate((departures, snr_features), axis=-1)
        else:
            edge_features = snr_features
    elif params.transformer_obs_type == "capacity":
        # 0 where no active lightpath, normalized remaining capacity otherwise
        # capacity mode is only used with RWA-LR which carries link_capacity_array.
        # Occupancy is keyed off path_index_array: RWA-LR's link_slot_array is nonzero only
        # where capacity is EXHAUSTED, so it cannot indicate active lightpaths.
        rwalr_state = cast(RWALightpathReuseEnvState, state)
        active_mask = (rwalr_state.path_index_array != -1).astype(dtype_config.LARGE_FLOAT_DTYPE)
        edge_features = (
            active_mask * rwalr_state.link_capacity_array / (jnp.mean(params.values_bw) * 100)
        )
    else:
        # Dynamic traffic: normalized departure times only
        edge_features = state.link_slot_departure_array / state.mean_service_holding_time

    # --- Traffic matrix node marginal features (NOT request-specific) ---
    send_load = jnp.sum(state.traffic_matrix, axis=1)  # (N,) row marginals
    recv_load = jnp.sum(state.traffic_matrix, axis=0)  # (N,) col marginals
    send_load = send_load / (jnp.sum(send_load) + 1e-8)
    recv_load = recv_load / (jnp.sum(recv_load) + 1e-8)
    link_src = params.edges[:, 0].astype(jnp.int32)  # (E,)
    link_dst = params.edges[:, 1].astype(jnp.int32)  # (E,)
    endpoint_send = (send_load[link_src] + send_load[link_dst]).reshape(-1, 1)  # (E, 1)
    endpoint_recv = (recv_load[link_src] + recv_load[link_dst]).reshape(-1, 1)  # (E, 1)
    traffic_marginal_features = jnp.concatenate([endpoint_send, endpoint_recv], axis=-1)  # (E, 2)

    # --- Request-specific features (critic should NOT see these) ---
    nodes_sd, requested_datarate = read_rsa_request(state.request_array)

    # Normalized request size
    max_bw = jnp.max(params.values_bw)
    request_size_feature = jnp.full(
        (params.num_links, 1),
        requested_datarate / (max_bw + 1e-8),
    )  # (E, 1)

    # Link relevance (4 features)
    paths = get_paths(params, nodes_sd)
    if params.transformer_obs_type == "capacity":
        # RWA-LR: use path capacity as quality (SE is always 1, meaningless)
        index_array = get_path_index_array(params, nodes_sd)
        rwalr_state = cast(RWALightpathReuseEnvState, state)
        paths_quality = jnp.take(
            rwalr_state.path_capacity_array.flatten(),
            index_array.flatten(),
        )
        paths_quality = paths_quality / (jnp.max(paths_quality) + 1e-8)  # normalize
    else:
        # SE-based envs: quality = 1/required_slots
        paths_se = get_paths_se(params, nodes_sd)
        num_slots = jax.vmap(
            lambda x: required_slots(
                requested_datarate,
                x,
                params.slot_size,
                guardband=params.guardband,
                temperature=params.temperature,
            )
        )(paths_se.flatten())
        paths_quality = 1.0 / num_slots
    link_relevance_features = get_link_relevance_array(paths, paths_quality, params)  # (E, 4)

    # Concatenation: shared features first, request-specific features last
    # Shared: wire_features, edge_features, traffic_marginals
    # Request-specific: [holding_time (departure only),] request_size, link_relevance
    shared = [wire_features, edge_features, traffic_marginal_features]
    request_specific = [request_size_feature, link_relevance_features]
    if params.transformer_obs_type in ("departure", "departure_snr", "lifetime_snr"):
        holding_time = state.holding_time / state.mean_service_holding_time
        if params.transformer_obs_type == "lifetime_snr":
            holding_time = jnp.log1p(jnp.maximum(holding_time, 0))
        holding_time_col = jnp.full(
            (params.num_links, 1),
            holding_time,
        )  # (E, 1)
        request_specific = [holding_time_col] + request_specific

    tokens = jnp.concatenate(shared + request_specific, axis=-1)

    return tokens

get_path(params, nodes, k_path_index)

Get k paths between source and destination

Source code in xlron/environments/env_funcs.py
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
@jax.jit
def get_path(params: EnvParams, nodes: Array, k_path_index: int) -> Array:
    """Get k paths between source and destination"""
    path_index = get_path_index(params, nodes, k_path_index)
    path = differentiable_indexing(
        params.path_link_array,
        path_index,
        params.temperature,
        params.differentiable,
    )
    if params.pack_path_bits:
        path = jnp.unpackbits(path)[: params.num_links]
    return path

get_path_and_se(params, nodes, k_path_index)

Get k paths and their spectral efficiencies between source and destination

Source code in xlron/environments/env_funcs.py
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
def get_path_and_se(params: EnvParams, nodes: Array, k_path_index: int) -> Tuple[Array, Array]:
    """Get k paths and their spectral efficiencies between source and destination"""
    path_index = get_path_index(params, nodes, k_path_index)
    path = differentiable_indexing(
        params.path_link_array,
        path_index,
        params.temperature,
        params.differentiable,
    )
    if params.pack_path_bits:
        path = jnp.unpackbits(path)[: params.num_links]
    se = differentiable_indexing(
        params.path_se_array, path_index, params.temperature, params.differentiable
    )
    return path, se

get_path_from_path_index_array(path_index_array, path_link_array)

Get path from path index array. Args: path_index_array (Array): Path index array path_link_array (Array): Path link array

Returns:

Type Description
Array

jnp.array: path index values replaced with binary path-link arrays

Source code in xlron/environments/env_funcs.py
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
@jax.jit
def get_path_from_path_index_array(path_index_array: Array, path_link_array: Array) -> Array:
    """Get path from path index array.
    Args:
        path_index_array (Array): Path index array
        path_link_array (Array): Path link array

    Returns:
        jnp.array: path index values replaced with binary path-link arrays
    """

    # TODO - support unpacking bits (if this function ends up being used)
    def get_index_from_link(link):
        return jax.vmap(lambda x: path_link_array[x], in_axes=(0,))(link)

    return jax.vmap(get_index_from_link, in_axes=(0,))(path_index_array)

get_path_index(params, nodes, k_path_index)

Get k paths between source and destination

Source code in xlron/environments/env_funcs.py
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
@jax.jit
def get_path_index(params: EnvParams, nodes: Array, k_path_index: int) -> Array:
    """Get k paths between source and destination"""
    source, dest = nodes
    starting_index = get_path_indices(
        params,
        source,
        dest,
        params.k_paths,
        params.num_nodes,
        directed=params.directed_graph,
    ).astype(jnp.int32)
    path_index = starting_index + k_path_index
    return path_index

get_path_index_array(params, nodes)

Indices of paths between source and destination from path array

Source code in xlron/environments/env_funcs.py
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
@jax.jit
def get_path_index_array(params: EnvParams, nodes: Array) -> Array:
    """Indices of paths between source and destination from path array"""
    # get source and destination nodes in order (for accurate indexing of path-link array)
    source, dest = nodes.astype(dtype_config.LARGE_INT_DTYPE)
    i = get_path_indices(
        params, source, dest, params.k_paths, params.num_nodes, directed=params.directed_graph
    )
    if not params.differentiable:
        # The gather through an identity arange is the identity: the k path
        # indices are just i, i+1, ..., i+k-1. Keep everything integer.
        return i.astype(dtype_config.INDEX_DTYPE) + jnp.arange(
            params.k_paths, dtype=dtype_config.INDEX_DTYPE
        )
    index_array = differentiable_indexing(
        jnp.arange(0, params.path_link_array.shape[0], dtype=dtype_config.LARGE_INT_DTYPE),
        i + jnp.arange(params.k_paths, dtype=dtype_config.LARGE_FLOAT_DTYPE),
        params.temperature,
        params.differentiable,
    )
    return index_array

get_path_se(params, nodes, k_path_index)

Get k paths between source and destination

Source code in xlron/environments/env_funcs.py
1566
1567
1568
1569
1570
1571
1572
@jax.jit
def get_path_se(params, nodes, k_path_index):
    """Get k paths between source and destination"""
    path_index = get_path_index(params, nodes, k_path_index)
    return differentiable_indexing(
        params.path_se_array, path_index, params.temperature, params.differentiable
    )

get_path_slots(link_slot_array, params, nodes_sd, i, agg_func='max')

Get slots on each constitutent link of path from link_slot_array (L x S), then aggregate to get (S x 1) representation of slots on path.

Parameters:

Name Type Description Default
link_slot_array Array

link-slot array

required
params EnvParams

environment parameters

required
nodes_sd Array

source-destination nodes

required
i int

path index

required
agg_func str

aggregation function (max or sum). If max, result will be available slots on path. If sum, result will contain information on edge features. if mean, will be mean.

'max'

Returns:

Name Type Description
slots Array

slots on path

Source code in xlron/environments/env_funcs.py
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
@partial(jax.jit, static_argnums=(4,))
def get_path_slots(
    link_slot_array: Array,
    params: EnvParams,
    nodes_sd: Array,
    i: int,
    agg_func: str = "max",
) -> Array:
    """Get slots on each constitutent link of path from link_slot_array (L x S),
    then aggregate to get (S x 1) representation of slots on path.

    Args:
        link_slot_array: link-slot array
        params: environment parameters
        nodes_sd: source-destination nodes
        i: path index
        agg_func: aggregation function (max or sum).
            If max, result will be available slots on path.
            If sum, result will contain information on edge features.
            if mean, will be mean.

    Returns:
        slots: slots on path
    """
    path = get_path(params, nodes_sd, i)
    slots = path[:, None] * link_slot_array
    # Make any -1s positive then get max for each slot across links
    if agg_func == "max":
        # Use this for getting slots from link_slot_array
        slots = jnp.max(jnp.absolute(slots), axis=0)
    elif agg_func == "sum":
        # TODO - consider using an RNN (or S5) to aggregate edge features
        # Use this (or alternative) for aggregating edge features from GNN
        slots = jnp.sum(slots, axis=0, promote_integers=False)
    elif agg_func == "mean":
        # Use this for getting mean value in slot index along path
        slots = jnp.mean(slots, axis=0)
    elif agg_func == "min":
        # Use this for getting slots from link_slot_array
        slots = jnp.min(slots, axis=0)
    else:
        raise ValueError("agg_func must be 'max' or 'sum' or 'mean' or min")
    return slots

get_paths(params, nodes)

Get k paths between source and destination

Source code in xlron/environments/env_funcs.py
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
@jax.jit
def get_paths(params: EnvParams, nodes: Array) -> Array:
    """Get k paths between source and destination"""
    index_array = get_path_index_array(params, nodes)
    paths = differentiable_indexing(
        params.path_link_array,
        index_array,
        params.temperature,
        params.differentiable,
    )
    if params.pack_path_bits:
        paths = jnp.unpackbits(paths, axis=1)[:, : params.num_links]
    return paths

get_paths_obs_gn_model(state, params)

Get observation space for launch power optimization (with numerical stability).

Source code in xlron/environments/env_funcs.py
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
@jax.jit
def get_paths_obs_gn_model(state: RSAGNModelEnvState, params: RSAGNModelEnvParams) -> Array:
    # TODO - make this just show the stats from just one path at a time
    """Get observation space for launch power optimization (with numerical stability)."""
    request_array = state.request_array.reshape((-1,))
    path_stats = calculate_path_stats(state, params, request_array)
    # Remove first 3 items of path stats for each path
    path_stats = path_stats[:, 3:]
    lightpath_snr_array = get_lightpath_snr(state, params)
    nodes_sd, requested_datarate = read_rsa_request(request_array)
    source, dest = nodes_sd

    def calculate_gn_path_stats(k_path_index):
        # Get path index
        path_index = (
            get_path_indices(
                params,
                source,
                dest,
                params.k_paths,
                params.num_nodes,
                directed=params.directed_graph,
            )
            + k_path_index
        )
        path_index = path_index.astype(dtype_config.INDEX_DTYPE)
        path = params.path_link_array[path_index]
        if params.pack_path_bits:
            path = jnp.unpackbits(path)[: params.num_links]
        # Lengths and maxima are precomputed: reducing over the whole path table here
        # would run every step now that the table is a runtime argument.
        path_length_norm = params.path_length_array[path_index] / params.max_path_length
        path_length_hops_norm = (
            jnp.sum(path, promote_integers=False).astype(dtype_config.LARGE_FLOAT_DTYPE)
            / params.max_path_hops
        )
        # Connections on path
        num_connections = jnp.where(
            path == 1,
            jnp.where(state.channel_power_array > 0, one, zero).sum(axis=1),
            zero,
        ).sum()
        num_connections_norm = num_connections / jnp.array(
            params.link_resources, dtype=dtype_config.LARGE_FLOAT_DTYPE
        )
        # Mean power of connections on path
        # make path with row length equal to link_resource (+1 to avoid zero division)
        mean_power_norm = jnp.where(
            path == one, state.channel_power_array.sum(axis=1), zero
        ).sum() / (jnp.where(num_connections > zero, num_connections, one) * params.max_power)
        # Mean SNR of connections on the path links
        max_snr = jnp.array(
            50, dtype=dtype_config.LARGE_FLOAT_DTYPE
        )  # Nominal value for max GSNR in dB
        mean_snr_norm = jnp.where(path == one, lightpath_snr_array.sum(axis=1), zero).sum(
            promote_integers=False
        ) / (jnp.where(num_connections > zero, num_connections, one) * max_snr)
        return jnp.array(
            [
                path_length_norm,
                path_length_hops_norm,
                num_connections_norm,
                mean_power_norm,
                mean_snr_norm,
            ],
            dtype=dtype_config.LARGE_FLOAT_DTYPE,
        )

    # Paths are independent, so batch the per-path stats with vmap rather than
    # serialising k iterations through a fori_loop (see calculate_path_stats)
    gn_path_stats = jax.vmap(calculate_gn_path_stats)(jnp.arange(params.k_paths))
    all_stats = jnp.concatenate([path_stats, gn_path_stats], axis=1)
    return jnp.concatenate(
        (
            jnp.array([source]),
            jnp.reshape(requested_datarate / 100.0, (-1,)),
            jnp.array([dest]),
            jnp.reshape(state.holding_time, (-1,)),
            jnp.reshape(all_stats, (-1,)),
        ),
        axis=0,
    )

get_paths_se(params, nodes)

Get max. spectral efficiency of modulation format on k paths between source and destination

Source code in xlron/environments/env_funcs.py
1575
1576
1577
1578
1579
1580
1581
1582
@jax.jit
def get_paths_se(params, nodes):
    """Get max. spectral efficiency of modulation format on k paths between source and destination"""
    # get source and destination nodes in order (for accurate indexing of path-link array)
    index_array = get_path_index_array(params, nodes)
    return differentiable_indexing(
        params.path_se_array, index_array, params.temperature, params.differentiable
    )

get_required_snr_se_kurtosis_array(modulation_format_index_array, col_index, params)

Convert modulation format index to required SNR or spectral efficiency. Modulation format index array contains the index of the modulation format used by the channel. The modulation index references a row in the modulations array, which contains SNR and SE values.

Parameters:

Name Type Description Default
modulation_format_index_array Array

Modulation format index array

required
col_index int

Column index for required SNR or spectral efficiency

required
params RSAGNModelEnvParams

Environment parameters

required

Returns:

Type Description
Array

jnp.array: Required SNR for each channel (min. SNR for empty channel (mod. index 0))

Source code in xlron/environments/env_funcs.py
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
@partial(jax.jit, static_argnums=(1,))
def get_required_snr_se_kurtosis_array(
    modulation_format_index_array: Array,
    col_index: int,
    params: RSAGNModelEnvParams,
) -> Array:
    """Convert modulation format index to required SNR or spectral efficiency.
    Modulation format index array contains the index of the modulation format used by the channel.
    The modulation index references a row in the modulations array, which contains SNR and SE values.

    Args:
        modulation_format_index_array (Array): Modulation format index array
        col_index (int): Column index for required SNR or spectral efficiency
        params (RSAGNModelEnvParams): Environment parameters

    Returns:
        jnp.array: Required SNR for each channel (min. SNR for empty channel (mod. index 0))
    """
    return jax.vmap(get_required_snr_se_kurtosis_on_link, in_axes=(0, None, None))(
        modulation_format_index_array, col_index, params
    )

Get SNR per link Args: state (EnvState): Environment state params (EnvParams): Environment parameters link_indices: Optional subset of link rows; preserves their order and duplicates. rows: Optional (bandwidth, power, centre, modulation format) channel rows for link_indices, replacing the state's (e.g. a candidate insertion). A fifth entry, the rows' XPM before span accumulation (Pallas backend only), replaces the XPM calculation (see inserted_link_xpm). broadcast: copy each channel's SNR to all its signal slots. Without it only each channel's first signal slot holds its SNR (the other signal slots hold the empty-slot sentinel), which is all the admission checks read (live_lightpath_mask); the GN masks skip the copy for speed. Returns: jnp.array: SNR per link

Source code in xlron/environments/env_funcs.py
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
@partial(jax.jit, static_argnames=("broadcast",))
def get_snr_link_array(
    state: GNModelEnvState,
    params: GNModelEnvParams,
    link_indices: Array | None = None,
    rows: tuple[Array, Array, Array, Array] | None = None,
    broadcast: bool = True,
) -> Array:
    """Get SNR per link
    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
        link_indices: Optional subset of link rows; preserves their order and duplicates.
        rows: Optional (bandwidth, power, centre, modulation format) channel rows for
            link_indices, replacing the state's (e.g. a candidate insertion). A fifth
            entry, the rows' XPM before span accumulation (Pallas backend only),
            replaces the XPM calculation (see inserted_link_xpm).
        broadcast: copy each channel's SNR to all its signal slots. Without it only
            each channel's first signal slot holds its SNR (the other signal slots
            hold the empty-slot sentinel), which is all the admission checks read
            (live_lightpath_mask); the GN masks skip the copy for speed.
    Returns:
        jnp.array: SNR per link
    """
    # The Pallas XPM kernel covers uniform spans without modulation corrections.
    xpm_backend = (
        "pallas"
        if uses_pallas_kernels(params) and params.uniform_spans and not params.mod_format_correction
        else "jax"
    )

    slots = params.link_resources
    capacity = max_channels_per_link(params)

    def get_link_snr(link_index, row):
        # Get channel power, channel centre, bandwidth, and noise figure
        link_lengths = params.link_length_array[link_index, :]  # in metres
        num_spans = jnp.ceil(jnp.sum(link_lengths) / params.max_span_length).astype(
            dtype_config.LARGE_INT_DTYPE
        )
        slot_bw_link, slot_power_link, slot_centres_link, mod_format_link, *xpm_link = row
        # The GN model evaluates one entry per channel (channel_entries); its SNR
        # is mapped back to the channel's slots below.
        take, expand = channel_entries(
            slot_bw_link, slot_power_link, slot_centres_link, capacity, xpm_backend == "pallas"
        )
        bw_link, ch_power_link = take(slot_bw_link, 0), take(slot_power_link, 0)
        ch_centres_link = take(slot_centres_link)
        if xpm_link:
            if xpm_backend != "pallas":
                raise ValueError("Precomputed XPM rows require the Pallas XPM backend")
            xpm_entries = take(xpm_link[0], 0)
            backend = lambda *_: xpm_entries
        else:
            backend = xpm_backend
        if params.mod_format_correction:
            kurtosis_link = take(get_required_snr_se_kurtosis_on_link(mod_format_link, 4, params))
        else:
            kurtosis_link = jnp.zeros(capacity).astype(jnp.float32)

        # Calculate SNR
        P = dict(
            num_channels=capacity,
            num_spans=num_spans,
            max_spans=params.max_spans,
            ref_lambda=params.ref_lambda,
            length=link_lengths,
            attenuation_i=jnp.array(params.attenuation),
            attenuation_bar_i=jnp.array(params.attenuation_bar),
            nonlinear_coeff=jnp.array(params.nonlinear_coeff),
            raman_gain_slope_i=jnp.array(params.raman_gain_slope),
            dispersion_coeff=jnp.array(params.dispersion_coeff),
            dispersion_slope=jnp.array(params.dispersion_slope),
            coherent=params.coherent,
            amplifier_noise_figure=take(jnp.broadcast_to(params.amplifier_noise_figure, (slots,))),
            transceiver_snr=take(jnp.broadcast_to(params.transceiver_snr, (slots,))),
            ch_power_w_i=ch_power_link,
            ch_centre_i=ch_centres_link * 1e9,
            ch_bandwidth_i=bw_link * 1e9,
            excess_kurtosis_i=kurtosis_link,
            uniform_spans=params.uniform_spans,
            num_subchannels=params.num_subchannels,
            span_lumped_loss_db=params.span_lumped_loss_db,
        )
        if params.use_raman_amp:
            snr = isrs_gn_model_dra.get_snr_dra(
                **P,
                fit_params_ij=take(jnp.moveaxis(params.raman_fit_params, 1, -1)).swapaxes(1, -1)
                if params.raman_fit_params.shape[1] == slots
                else params.raman_fit_params,
                raman_pump_power_fw=params.raman_pump_power_fw,
                raman_pump_power_bw=params.raman_pump_power_bw,
                raman_pump_freq_fw=params.raman_pump_freq_fw,
                raman_pump_freq_bw=params.raman_pump_freq_bw,
            )[0]
        else:
            snr = isrs_gn_model.get_snr(
                **P,
                num_roadms=params.num_roadms,
                roadm_loss=params.roadm_loss,
                mod_format_correction=params.mod_format_correction,
                xpm_backend=backend,
            )[0]

        return expand(snr, broadcast)

    if link_indices is None:
        link_indices = jnp.arange(params.num_links)
    if rows is None:
        modulation = (
            cast(RMSAGNModelEnvState, state).modulation_format_index_array
            if params.mod_format_correction
            else state.channel_centre_bw_array  # unused placeholder
        )
        rows = tuple(
            x[link_indices]
            for x in (
                state.channel_centre_bw_array,
                state.channel_power_array,
                state.channel_centre_freq_array,
                modulation,
            )
        )
    link_snr_array = jax.vmap(get_link_snr)(link_indices, rows)
    link_snr_array = jnp.nan_to_num(link_snr_array, nan=1e-5)
    return link_snr_array

Get SNR per link using fused computation (uniform spans, no mod_format_correction).

Drop-in replacement for get_snr_link_array that uses get_snr_fused to reduce XLA op count and kernel launch overhead on GPU.

Source code in xlron/environments/env_funcs.py
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
@partial(jax.jit, static_argnames=("broadcast",))
def get_snr_link_array_fused(
    state: GNModelEnvState,
    params: GNModelEnvParams,
    link_indices: Array | None = None,
    broadcast: bool = True,
) -> Array:
    """Get SNR per link using fused computation (uniform spans, no mod_format_correction).

    Drop-in replacement for get_snr_link_array that uses get_snr_fused to
    reduce XLA op count and kernel launch overhead on GPU.
    """
    # Raman amplification has per-span varying fit_params — fused uniform-span path doesn't apply
    if params.use_raman_amp:
        return get_snr_link_array(state, params, link_indices, broadcast=broadcast)

    # Precompute per-link num_spans and span_length from static link_length_array
    # link_length_array is (L, max_spans) in metres
    if link_indices is None:
        link_indices = jnp.arange(params.num_links)
    link_lengths_m = params.link_length_array[link_indices]  # (L, max_spans)
    total_link_length_m = jnp.sum(link_lengths_m, axis=1)  # (L,)
    num_spans_per_link = jnp.ceil(total_link_length_m / params.max_span_length).astype(
        dtype_config.LARGE_INT_DTYPE
    )  # (L,)
    # span_length in metres to match GN model expectations
    span_length_per_link = total_link_length_m / jnp.maximum(num_spans_per_link, 1).astype(
        jnp.float32
    )  # (L,) in metres

    # Per-link per-slot channel rows: (L, N)
    slots = params.link_resources
    capacity = max_channels_per_link(params)
    amp_nf = jnp.broadcast_to(params.amplifier_noise_figure, (slots,))
    trx_snr = jnp.broadcast_to(params.transceiver_snr, (slots,))

    def _link_snr_fused(slot_bw, slot_pow, slot_centre, n_spans, s_length):
        # One GN entry per channel (channel_entries), mapped back to its slots.
        take, expand = channel_entries(
            slot_bw, slot_pow, slot_centre, capacity, uses_pallas_kernels(params)
        )
        snr = isrs_gn_model.get_snr_fused(
            ch_power_w_i=take(slot_pow, 0),
            ch_centre_i=take(slot_centre) * 1e9,
            ch_bandwidth_i=take(slot_bw, 0) * 1e9,
            num_spans=n_spans,
            span_length=s_length,
            num_channels=capacity,
            ref_lambda=params.ref_lambda,
            attenuation=params.attenuation,
            attenuation_bar=params.attenuation_bar,
            nonlinear_coeff=params.nonlinear_coeff,
            raman_gain_slope=params.raman_gain_slope,
            dispersion_coeff=params.dispersion_coeff,
            dispersion_slope=params.dispersion_slope,
            amplifier_noise_figure=take(amp_nf),
            transceiver_snr=take(trx_snr),
            roadm_loss=params.roadm_loss,
            num_roadms=params.num_roadms,
            coherent=params.coherent,
            num_subchannels=params.num_subchannels,
            span_lumped_loss_db=params.span_lumped_loss_db,
            # Compaction wins in the measured 420/1376-slot workloads. Preserve
            # dense fusion for smaller spectra and reverse-mode AD callers.
            compact_xpm=not params.differentiable and capacity >= 420,
            xpm_backend="pallas" if uses_pallas_kernels(params) else "jax",
        )
        return expand(snr, broadcast)

    link_snr_array = jax.vmap(_link_snr_fused)(
        state.channel_centre_bw_array[link_indices],
        state.channel_power_array[link_indices],
        state.channel_centre_freq_array[link_indices],
        num_spans_per_link,
        span_length_per_link,
    )
    link_snr_array = jnp.nan_to_num(link_snr_array, nan=1e-5)
    return link_snr_array

get_spectral_features(laplacian, num_features)

Compute spectral node features from symmetric normalized graph Laplacian.

Parameters:

Name Type Description Default
adj

Adjacency matrix of the graph

required
num_features int

Number of eigenvector features to extract

required

Returns:

Type Description
Array

Array of shape (n_nodes, num_features) containing eigenvectors corresponding

Array

to the smallest non-zero eigenvalues of the graph Laplacian. If the graph has

Array

fewer nodes than num_features, the result is zero-padded to have num_features columns.

Notes
  • Skips trivial eigenvectors (those with near-zero eigenvalues)
  • Eigenvectors are ordered by ascending eigenvalue magnitude
  • Runtime is O(n^3) - use only for small/medium graphs
  • Eigenvector signs are arbitrary (may vary between runs)
Source code in xlron/environments/env_funcs.py
62
63
64
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
@partial(jax.jit, static_argnums=(1,))
def get_spectral_features(laplacian: Array, num_features: int) -> Array:
    """Compute spectral node features from symmetric normalized graph Laplacian.

    Args:
        adj: Adjacency matrix of the graph
        num_features: Number of eigenvector features to extract

    Returns:
        Array of shape (n_nodes, num_features) containing eigenvectors corresponding
        to the smallest non-zero eigenvalues of the graph Laplacian. If the graph has
        fewer nodes than num_features, the result is zero-padded to have num_features columns.

    Notes:
        - Skips trivial eigenvectors (those with near-zero eigenvalues)
        - Eigenvectors are ordered by ascending eigenvalue magnitude
        - Runtime is O(n^3) - use only for small/medium graphs
        - Eigenvector signs are arbitrary (may vary between runs)
    """
    eigenvalues, eigenvectors = jnp.linalg.eigh(laplacian)
    n_nodes = laplacian.shape[0]
    # If graph has fewer nodes than requested features, pad with zeros
    if n_nodes < num_features:
        padding = jnp.zeros((n_nodes, num_features - n_nodes), dtype=dtype_config.LARGE_FLOAT_DTYPE)
        return jnp.concatenate([eigenvectors, padding], axis=-1).astype(
            dtype_config.LARGE_FLOAT_DTYPE
        )
    return eigenvectors[:, :num_features].astype(dtype_config.LARGE_FLOAT_DTYPE)

held_lightpath_mask(state, params)

(links, slots) cells of lightpaths whose traffic has ended but are still lit.

Only the safe_release departure policy holds lightpaths (issue #67): an expired lightpath keeps its optical signal, and so its spectrum, power and interference, until switching it off leaves every live lightpath above its SNR threshold. Held cells are identified by an elapsed departure time on an occupied cell: departure <= current_time with absolute times, departure <= 0 with relative times (remaining time). Newly admitted lightpaths always depart in the future.

Source code in xlron/environments/env_funcs.py
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
def held_lightpath_mask(state: GNModelEnvState, params: GNModelEnvParams) -> Array:
    """(links, slots) cells of lightpaths whose traffic has ended but are still lit.

    Only the safe_release departure policy holds lightpaths (issue #67): an expired
    lightpath keeps its optical signal, and so its spectrum, power and interference,
    until switching it off leaves every live lightpath above its SNR threshold.
    Held cells are identified by an elapsed departure time on an occupied cell:
    departure <= current_time with absolute times, departure <= 0 with relative
    times (remaining time). Newly admitted lightpaths always depart in the future.
    """
    present = state.channel_centre_bw_array != 0
    if getattr(params, "departure_policy", "immediate") != "safe_release":
        return jnp.zeros_like(present)
    now = 0.0 if params.relative_arrival_times else state.current_time
    return present & (state.link_slot_departure_array <= now)

implement_action_rmsa_gn_model(state, action_info, params)

Implement action for RSA GN model. Update following arrays: - link_slot_array - link_slot_departure_array - link_snr_array - modulation_format_index_array - channel_power_array - active_path_array Args: state (EnvState): Environment state action (Array): Action tuple (first is path action, second is launch_power) params (EnvParams): Environment parameters Returns: EnvState: Updated environment state

Source code in xlron/environments/env_funcs.py
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
@jax.jit
def implement_action_rmsa_gn_model(
    state: RMSAGNModelEnvState, action_info: ActionInfo, params: RMSAGNModelEnvParams
) -> RMSAGNModelEnvState:
    """Implement action for RSA GN model. Update following arrays:
    - link_slot_array
    - link_slot_departure_array
    - link_snr_array
    - modulation_format_index_array
    - channel_power_array
    - active_path_array
    Args:
        state (EnvState): Environment state
        action (Array): Action tuple (first is path action, second is launch_power)
        params (EnvParams): Environment parameters
    Returns:
        EnvState: Updated environment state
    """
    # Snapshot the GN auxiliary arrays before the tentative write (see
    # implement_action_rsa_gn_model; rmsa additionally restores the modulation format array).
    state = state.replace(
        path_index_array_prev=state.path_index_array,
        channel_centre_bw_array_prev=state.channel_centre_bw_array,
        channel_power_array_prev=state.channel_power_array,
        channel_centre_freq_array_prev=state.channel_centre_freq_array,
        modulation_format_index_array_prev=state.modulation_format_index_array,
        link_snr_array_prev=state.link_snr_array,
    )
    path_action = action_info.action.astype(dtype_config.LARGE_INT_DTYPE)
    lightpath_index = get_lightpath_index(params, action_info.nodes_sd, action_info.path_index)
    launch_power = get_channel_launch_power(
        state,
        path_action,
        action_info.power_action,
        action_info.initial_slot_index,
        action_info.num_slots,
        params,
    )
    _, channel_width, channel_centre = get_channel_values(
        action_info.initial_slot_index, action_info.num_slots, params
    )
    # Power and width on the signal slots only: the guard band is dark.
    signal_slots_mask = action_info.affected_slots_mask * channel_slot_mask(
        action_info.initial_slot_index, action_info.num_slots, params
    ).astype(action_info.affected_slots_mask.dtype)
    # TODO(GN MODEL) - get mod. format based on maximum reach
    # mod_format_mask is full-resolution (k * link_resources); under slot aggregation the raw
    # action indexes the aggregated space, so rebuild the flat index from the decoded path/slot
    # (identical to the raw action when aggregate_slots == 1).
    full_res_action = (
        action_info.path_index * params.link_resources + action_info.initial_slot_index
    ).astype(dtype_config.LARGE_INT_DTYPE)
    mod_format_index = jax.lax.dynamic_slice(
        state.mod_format_mask, (full_res_action,), (1,)
    ).astype(dtype_config.LARGE_INT_DTYPE)[0]
    # Update link_slot_array and link_slot_departure_array, then other arrays
    state = implement_path_action(state, action_info, params)
    state = state.replace(
        path_index_array=set_path_links(
            state.path_index_array,
            action_info.affected_slots_mask,
            lightpath_index,
        ),
        channel_power_array=set_path_links(
            state.channel_power_array,
            signal_slots_mask,
            launch_power,
        ),
        modulation_format_index_array=set_path_links(
            state.modulation_format_index_array,
            action_info.affected_slots_mask,
            mod_format_index,
        ),
        channel_centre_bw_array=set_path_links(
            state.channel_centre_bw_array,
            signal_slots_mask,
            channel_width,
        ),
        channel_centre_freq_array=set_path_links(
            state.channel_centre_freq_array,
            action_info.affected_slots_mask,
            channel_centre,
        ),
    )
    if link_snr_cache_is_fresh(params):
        # Only the new lightpath's links changed; the other rows are already exact.
        path_links = params.path_link_indices[lightpath_index]
        state = state.replace(
            link_snr_array=state.link_snr_array.at[path_links].set(
                get_snr_link_array(state, params, path_links), mode="drop"
            )
        )
    else:
        state = state.replace(link_snr_array=get_snr_link_array(state, params))
    # jax.debug.print("launch_power {}", launch_power, ordered=True)
    # jax.debug.print("mod_format_index {}", mod_format_index, ordered=True)
    # jax.debug.print("initial_slot_index {}", initial_slot_index, ordered=True)
    # jax.debug.print("state.mod_format_mask {}", state.mod_format_mask, ordered=True)
    # jax.debug.print("path_snr {}", get_snr_for_path(path, state.link_snr_array, params, state), ordered=True)
    # jax.debug.print("required_snr {}", params.modulations_array[mod_format_index][2] + params.snr_margin, ordered=True)
    return state

implement_action_rsa(state, action_info, params)

Implement action to assign slots on links.

Parameters:

Name Type Description Default
state RSAEnvState

current state

required
action

action to implement

required
params RSAEnvParams

environment parameters

required

Returns:

Name Type Description
state EnvState

updated state

Source code in xlron/environments/env_funcs.py
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
@partial(jax.jit, donate_argnums=(0,))
def implement_action_rsa(
    state: RSAEnvState,
    action_info: ActionInfo,
    params: RSAEnvParams,
) -> EnvState:
    """Implement action to assign slots on links.

    Args:
        state: current state
        action: action to implement
        params: environment parameters

    Returns:
        state: updated state
    """
    # RWA-LR dispatches to implement_action_rwalr in step_env, never here (the old RWALR
    # branch in this function was dead and carried an inverted capacity update)
    state = implement_path_action(state, action_info, params)
    return state

implement_action_rsa_gn_model(state, action_info, params)

Implement action for RSA GN model. Update following arrays: - link_slot_array - link_slot_departure_array - link_snr_array - modulation_format_index_array - channel_power_array - active_path_array Args: state (EnvState): Environment state action (Array): Action tuple (first is path action, second is launch_power) params (EnvParams): Environment parameters Returns: EnvState: Updated environment state

Source code in xlron/environments/env_funcs.py
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
@jax.jit
def implement_action_rsa_gn_model(
    state: RSAGNModelEnvState, action_info: ActionInfo, params: RSAGNModelEnvParams
) -> EnvState:
    """Implement action for RSA GN model. Update following arrays:
    - link_slot_array
    - link_slot_departure_array
    - link_snr_array
    - modulation_format_index_array
    - channel_power_array
    - active_path_array
    Args:
        state (EnvState): Environment state
        action (Array): Action tuple (first is path action, second is launch_power)
        params (EnvParams): Environment parameters
    Returns:
        EnvState: Updated environment state
    """
    # Snapshot the GN auxiliary arrays before the tentative write so complete_step's
    # failure path restores the exact pre-action state. (These *_prev fields were never
    # written after init, so the failure restore wiped the whole network's GN state on
    # any blocked request.)
    state = state.replace(
        path_index_array_prev=state.path_index_array,
        channel_centre_bw_array_prev=state.channel_centre_bw_array,
        channel_power_array_prev=state.channel_power_array,
        channel_centre_freq_array_prev=state.channel_centre_freq_array,
        link_snr_array_prev=state.link_snr_array,
    )
    path_action = action_info.action.astype(dtype_config.LARGE_INT_DTYPE)
    lightpath_index = get_lightpath_index(params, action_info.nodes_sd, action_info.path_index)
    launch_power = get_channel_launch_power(
        state,
        path_action,
        action_info.power_action,
        action_info.initial_slot_index,
        action_info.num_slots,
        params,
    )
    _, channel_width, channel_centre = get_channel_values(
        action_info.initial_slot_index, action_info.num_slots, params
    )
    # Power and width on the signal slots only: the guard band is dark.
    signal_slots_mask = action_info.affected_slots_mask * channel_slot_mask(
        action_info.initial_slot_index, action_info.num_slots, params
    ).astype(action_info.affected_slots_mask.dtype)
    # Update link_slot_array and link_slot_departure_array, then other arrays
    state = implement_path_action(state, action_info, params)
    state = state.replace(
        path_index_array=set_path_links(
            state.path_index_array,
            action_info.affected_slots_mask,
            lightpath_index,
        ),
        channel_power_array=set_path_links(
            state.channel_power_array,
            signal_slots_mask,
            launch_power,
        ),
        channel_centre_bw_array=set_path_links(
            state.channel_centre_bw_array,
            signal_slots_mask,
            channel_width,
        ),
        channel_centre_freq_array=set_path_links(
            state.channel_centre_freq_array,
            action_info.affected_slots_mask,
            channel_centre,
        ),
    )
    state = state.replace(
        active_lightpaths_array=update_active_lightpaths_array(
            state,
            lightpath_index,
            action_info.initial_slot_index,
            action_info.num_slots - params.guardband,
        ),
        active_lightpaths_array_departure=update_active_lightpaths_array_departure(
            state, -state.current_time - state.holding_time
        ),
    )
    # No need to check SNR until end of episode
    return state

implement_and_complete_rsa(state, action_info, check, params)

Fused implement + finalise for the non-differentiable plain-RSA/RMSA/RWA step.

Equivalent to implement_path_action followed by complete_step_rsa, given check already computed on the PRE-implementation state (check_action_rsa_prestate): the allocation is applied exactly once, gated on success, so the speculative write + undo passes of the implement/check/undo flow are not needed. On success the arithmetic is bit-identical to the old flow (mask * 1 == mask, and 0-valued deltas add exactly); on failure the state is left untouched (the old flow's add-then-subtract round trip could perturb occupied departure entries by float rounding; here they are never written).

Source code in xlron/environments/env_funcs.py
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
def implement_and_complete_rsa(
    state: EnvState, action_info: ActionInfo, check: Array, params: EnvParams
) -> EnvState:
    """Fused implement + finalise for the non-differentiable plain-RSA/RMSA/RWA step.

    Equivalent to implement_path_action followed by complete_step_rsa, given `check`
    already computed on the PRE-implementation state (check_action_rsa_prestate):
    the allocation is applied exactly once, gated on success, so the speculative
    write + undo passes of the implement/check/undo flow are not needed.
    On success the arithmetic is bit-identical to the old flow
    (mask * 1 == mask, and 0-valued deltas add exactly); on failure the state is
    left untouched (the old flow's add-then-subtract round trip could perturb
    occupied departure entries by float rounding; here they are never written).
    """
    success = 1 - check
    delta = action_info.affected_slots_mask * success
    departure_delta = state.current_time + state.holding_time
    return state.replace(
        # Cast the delta (not the occupancy array) to the occupancy dtype: the add stays
        # narrow and the carried array avoids an upcast+downcast round trip
        link_slot_array=state.link_slot_array + delta.astype(state.link_slot_array.dtype),
        link_slot_departure_array=state.link_slot_departure_array + delta * departure_delta,
        accepted_services=state.accepted_services + success,
        accepted_bitrate=state.accepted_bitrate + (success * action_info.requested_datarate),
        total_bitrate=state.total_bitrate + action_info.requested_datarate,
        total_timesteps=state.total_timesteps + 1,
    )

init_active_lightpaths_array(params)

Initialise active lightpath registry: rows of [path_index, initial_slot, num_slots].

Parameters:

Name Type Description Default
params RSAGNModelEnvParams

Environment parameters

required

Returns: jnp.array: (M, 3) registry (default value -1, empty row)

Source code in xlron/environments/env_funcs.py
4263
4264
4265
4266
4267
4268
4269
4270
4271
def init_active_lightpaths_array(params: RSAGNModelEnvParams):
    """Initialise active lightpath registry: rows of [path_index, initial_slot, num_slots].

    Args:
        params (RSAGNModelEnvParams): Environment parameters
    Returns:
        jnp.array: (M, 3) registry (default value -1, empty row)
    """
    return jnp.full((_max_active_lightpaths(params), 3), -1, dtype=dtype_config.LARGE_INT_DTYPE)

init_active_lightpaths_array_departure(params)

Initialise per-lightpath departure times, aligned row-wise with the registry.

Lifecycle: inserted NEGATIVE (-(current+holding)) as a pending marker by implement_action_rsa_gn_model; complete_step_rsa_gn_model flips it positive on success or zeroes the row on failure; remove_expired_services_rsa_gn_model expires 0 < dep <= t rows.

Parameters:

Name Type Description Default
params RSAGNModelEnvParams

Environment parameters

required

Returns: jnp.array: (M, 3) departure times (0 = empty) -> TIME tier

Source code in xlron/environments/env_funcs.py
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
def init_active_lightpaths_array_departure(params: RSAGNModelEnvParams):
    """Initialise per-lightpath departure times, aligned row-wise with the registry.

    Lifecycle: inserted NEGATIVE (-(current+holding)) as a pending marker by
    implement_action_rsa_gn_model; complete_step_rsa_gn_model flips it positive on success
    or zeroes the row on failure; remove_expired_services_rsa_gn_model expires
    0 < dep <= t rows.

    Args:
        params (RSAGNModelEnvParams): Environment parameters
    Returns:
        jnp.array: (M, 3) departure times (0 = empty) -> TIME tier
    """
    return jnp.full((_max_active_lightpaths(params), 3), 0.0, dtype=dtype_config.TIME_DTYPE)

init_active_path_array(params)

Initialise active path array. Stores details of full path utilised by lightpath on each frequency slot. Args: params (EnvParams): Environment parameters Returns: jnp.array: Active path array

Source code in xlron/environments/env_funcs.py
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
def init_active_path_array(params: EnvParams):
    """Initialise active path array. Stores details of full path utilised by lightpath on each frequency slot.
    Args:
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: Active path array
    """
    return jnp.full(
        (params.num_links, params.link_resources, params.num_links),
        -1,
        dtype=dtype_config.LARGE_INT_DTYPE,
    )

init_channel_centre_bw_array(params)

Initialise channel centre array. Args: params (EnvParams): Environment parameters Returns: jnp.array: Channel centre array

Source code in xlron/environments/env_funcs.py
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
def init_channel_centre_bw_array(params: EnvParams):
    """Initialise channel centre array.
    Args:
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: Channel centre array
    """
    return jnp.full(
        (params.num_links, params.link_resources), 0.0, dtype=dtype_config.LARGE_FLOAT_DTYPE
    )

init_channel_centre_freq_array(params)

Initialise channel centre frequency array. Args: params (EnvParams): Environment parameters Returns: jnp.array: Channel centre frequency array (GHz)

Source code in xlron/environments/env_funcs.py
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
def init_channel_centre_freq_array(params: EnvParams):
    """Initialise channel centre frequency array.
    Args:
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: Channel centre frequency array (GHz)
    """
    return jnp.full(
        (params.num_links, params.link_resources), 0.0, dtype=dtype_config.LARGE_FLOAT_DTYPE
    )

init_channel_power_array(params)

Initialise channel power array.

Parameters:

Name Type Description Default
params EnvParams

Environment parameters

required

Returns: jnp.array: Channel power array

Source code in xlron/environments/env_funcs.py
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
def init_channel_power_array(params: EnvParams):
    """Initialise channel power array.

    Args:
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: Channel power array
    """
    return jnp.full(
        (params.num_links, params.link_resources), 0.0, dtype=dtype_config.LARGE_FLOAT_DTYPE
    )

init_graph_tuple(state, params, adj, exclude_source_dest=False)

Initialise graph tuple for use with Jraph GNNs. Args: state (EnvState): Environment state params (EnvParams): Environment parameters adj (jnp.array): Adjacency matrix of the graph Returns: jraph.GraphsTuple: Graph tuple

Source code in xlron/environments/env_funcs.py
151
152
153
154
155
156
157
158
159
160
161
162
163
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
@partial(jax.jit, static_argnums=(3,))
def init_graph_tuple(
    state: RSAEnvState,
    params: RSAEnvParams,
    adj: Array,
    exclude_source_dest: bool = False,
) -> jraph.GraphsTuple:
    """Initialise graph tuple for use with Jraph GNNs.
    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
        adj (jnp.array): Adjacency matrix of the graph
    Returns:
        jraph.GraphsTuple: Graph tuple
    """
    senders = params.edges.T[0].astype(dtype_config.LARGE_INT_DTYPE)
    receivers = params.edges.T[1].astype(dtype_config.LARGE_INT_DTYPE)

    # Get source and dest from request array
    # VONE has 2D request_array (2, max_edges*2+1), use first row for node info
    request_array = state.request_array
    if request_array.ndim == 2:
        request_array = request_array[0]
    source_dest, datarate = read_rsa_request(request_array)
    # Global feature is normalised data rate of current request
    globals = jnp.array(
        [datarate / jnp.max(params.values_bw)], dtype=dtype_config.LARGE_FLOAT_DTYPE
    )

    if exclude_source_dest:
        source_dest_features = jnp.zeros(
            (params.num_nodes, 2), dtype=dtype_config.LARGE_FLOAT_DTYPE
        )
    else:
        source, dest = source_dest[0], source_dest[2]
        # One-hot encode source and destination (2 additional features)
        source_dest_features = jnp.zeros(
            (params.num_nodes, 2), dtype=dtype_config.LARGE_FLOAT_DTYPE
        )
        source_dest_features = source_dest_features.at[
            source.astype(dtype_config.INDEX_DTYPE), 0
        ].set(1)
        source_dest_features = source_dest_features.at[
            dest.astype(dtype_config.INDEX_DTYPE), 1
        ].set(-1)

    spectral_features = get_spectral_features(adj, num_features=params.num_spectral_features)

    # For dynamic traffic, edge_features are normalised remaining holding time instead of link_slot_array
    holding_time_edge_features = state.link_slot_departure_array / state.mean_service_holding_time

    if params.__class__.__name__ in ["RSAGNModelEnvParams", "RMSAGNModelEnvParams"]:
        # Normalize by max parameters (converted to linear units)
        gn_state = cast(GNModelEnvState, state)
        gn_params = cast(GNModelEnvParams, params)
        max_power = isrs_gn_model.from_dbm(gn_params.max_power)
        normalized_power = jnp.round(gn_state.channel_power_array / max_power, 3)
        max_snr = isrs_gn_model.from_db(gn_params.max_snr)
        normalized_snr = jnp.round(gn_state.link_snr_array / max_snr, 3)
        edge_features = jnp.stack([normalized_snr, normalized_power], axis=-1)
        node_features = jnp.concatenate([spectral_features, source_dest_features], axis=-1)
    elif params.__class__.__name__ == "VONEEnvParams":
        edge_features = (
            # Cast occupancy (int8 tier) to float: graph features feed the NN embedders and
            # must match the holding-time branch / init-vs-update carry dtype
            state.link_slot_array.astype(dtype_config.SMALL_FLOAT_DTYPE)
            if params.incremental_loading
            else holding_time_edge_features
        )
        node_features = getattr(
            state,
            "node_capacity_array",
            jnp.zeros(params.num_nodes, dtype=dtype_config.LARGE_FLOAT_DTYPE),
        )
        node_features = node_features.reshape(-1, 1)
        node_features = jnp.concatenate(
            [node_features, spectral_features, source_dest_features], axis=-1
        )
    else:
        edge_features = (
            # Cast occupancy (int8 tier) to float: graph features feed the NN embedders and
            # must match the holding-time branch / init-vs-update carry dtype
            state.link_slot_array.astype(dtype_config.SMALL_FLOAT_DTYPE)
            if params.incremental_loading
            else holding_time_edge_features
        )
        # [n_edges] or [n_edges, ...]
        node_features = jnp.concatenate([spectral_features, source_dest_features], axis=-1)

    if params.disable_node_features:
        # One zero feature per node: keeps the (num_nodes, features) rank expected by
        # jax.vmap(node_embedder) in the GNN, matching the width-1 embedder that
        # init_network builds when DISABLE_NODE_FEATURES is set.
        node_features = jnp.zeros((params.num_nodes, 1), dtype=dtype_config.LARGE_FLOAT_DTYPE)

    # Handle undirected graphs (duplicate edges after normalization).
    # senders/receivers are laid out as [fwd_0..fwd_E-1, bwd_0..bwd_E-1], so features must be
    # block-duplicated to match (jnp.repeat would interleave [f0, f0, f1, f1, ...], attaching
    # link j's features to concatenated edges 2j/2j+1 instead of j and E+j; the GNN readout
    # slices edges[: E] as per-link features).
    if not params.directed_graph:
        senders_ = jnp.concatenate([senders, receivers])
        receivers = jnp.concatenate([receivers, senders])
        senders = senders_
        edge_features = jnp.concatenate([edge_features, edge_features], axis=0)

    # Bulk float tier: GNN input features (normalised remaining holding time / SNR / power, ~[-1,1]
    # or [0,1]). Stored at SMALL_FLOAT to cut memory (graph.edges is the largest E*S array under
    # mixed precision); the GNN/Transformer cast them back up to COMPUTE_DTYPE at the model
    # boundary. update_graph_tuple applies the same cast so the carried graph dtype is stable.
    node_features = node_features.astype(dtype_config.SMALL_FLOAT_DTYPE)
    edge_features = edge_features.astype(dtype_config.SMALL_FLOAT_DTYPE)

    return jraph.GraphsTuple(
        nodes=node_features,
        edges=edge_features,
        senders=senders,
        receivers=receivers,
        n_node=jnp.reshape(params.num_nodes, (1,)).astype(dtype_config.LARGE_INT_DTYPE),
        n_edge=jnp.reshape(len(senders), (1,)).astype(dtype_config.LARGE_INT_DTYPE),
        globals=globals,
    )

Initialise link capacity array. Represents available data rate for lightpath on each link. Default is high value (1e6) for unoccupied slots. Once lightpath established, capacity is determined by corresponding entry in path capacity array.

Source code in xlron/environments/env_funcs.py
3084
3085
3086
3087
3088
def init_link_capacity_array(params):
    """Initialise link capacity array. Represents available data rate for lightpath on each link.
    Default is high value (1e6) for unoccupied slots. Once lightpath established, capacity is determined by
    corresponding entry in path capacity array."""
    return jnp.full((params.num_links, params.link_resources), 1e6)

Initialise link length array. Args: graph (nx.Graph): NetworkX graph Returns:

Source code in xlron/environments/env_funcs.py
393
394
395
396
397
398
399
400
401
402
403
def init_link_length_array(graph: nx.Graph) -> Array:
    """Initialise link length array.
    Args:
        graph (nx.Graph): NetworkX graph
    Returns:

    """
    link_lengths = []
    for edge in sorted(graph.edges):
        link_lengths.append(graph.edges[edge]["distance"])
    return jnp.array(link_lengths, dtype=dtype_config.LARGE_INT_DTYPE)

Initialise link length array for environements that use GN model of physical layer. We assume each link has spans of equal length.

Parameters:

Name Type Description Default
graph Graph

NetworkX graph

required
max_span_length int

Maximum span length in metres

required
max_spans int

Maximum number of spans per link

required

Returns: jnp.array: Link length array (L x max_spans) in metres

Source code in xlron/environments/env_funcs.py
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
def init_link_length_array_gn_model(graph: nx.Graph, max_span_length: int, max_spans: int) -> Array:
    """Initialise link length array for environements that use GN model of physical layer.
    We assume each link has spans of equal length.

    Args:
        graph (nx.Graph): NetworkX graph
        max_span_length (int): Maximum span length in metres
        max_spans (int): Maximum number of spans per link
    Returns:
        jnp.array: Link length array (L x max_spans) in metres
    """
    # Row order must be sorted(graph.edges) of the graph AS GIVEN - the ordering used for
    # path_link_array columns, params.edges and init_link_length_array. (The previous
    # doubled-undirected layout permuted lengths across links on directed topologies,
    # silently corrupting span counts and per-link SNR wherever the two directions'
    # lexicographic positions interleave.)
    link_lengths = [
        # Topology distances are in km; convert to metres for GN model
        graph.edges[edge]["distance"] * 1e3
        for edge in sorted(graph.edges)
    ]
    span_length_array = []
    for length in link_lengths:
        num_spans = math.ceil(length / max_span_length)
        avg_span_length = length / num_spans
        span_lengths = [avg_span_length] * num_spans
        span_lengths.extend([0] * (max_spans - num_spans))
        span_length_array.append(span_lengths)
    # Float: average span lengths are fractional (length / num_spans); the int cast truncated
    # up to 1 m per span
    return jnp.array(span_length_array, dtype=dtype_config.LARGE_FLOAT_DTYPE)

Initialize empty (all zeroes) link-slot array. 0 means slot is free, -1 means occupied. Args: params (EnvParams): Environment parameters Returns: jnp.array: Link slot array (E x S) where E is number of edges and S is number of slots

Source code in xlron/environments/env_funcs.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
@jax.jit
def init_link_slot_array(params: EnvParams):
    """Initialize empty (all zeroes) link-slot array. 0 means slot is free, -1 means occupied.
    Args:
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: Link slot array (E x S) where E is number of edges and S is number of slots"""
    # Spectrum occupancy counter, values {0, 1} (steady) with a transient +2 marking a
    # collision (see check_no_spectrum_reuse) and -1/-2 sentinels (band gaps, VONE tentative
    # marks). Occupancy tier: integer in non-differentiable modes (int32 default; int8 under
    # mixed precision, where this largest per-env array is the dominant memory saving),
    # float32 in differentiable mode.
    # Scan-carry rule: every state.replace(link_slot_array=...) site must cast back to this
    # dtype, because masks/blends promote through wider dtypes.
    return jnp.zeros((params.num_links, params.link_resources), dtype=dtype_config.OCCUPANCY_DTYPE)

Initialize link mask

Source code in xlron/environments/env_funcs.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
@partial(jax.jit, static_argnums=(1, 2))
def init_link_slot_mask(params: EnvParams, include_no_op: bool = False, agg: float = 1.0):
    """Initialize link mask"""
    # Action-validity mask on the MASK tier: bool in non-differentiable modes (born as a
    # comparison; consumers cast to float at the point of use, e.g. logit masking), float32 in
    # differentiable mode. The mask is recomputed from scratch each step, so every site that
    # writes it back into the carried state (select_action in train_utils,
    # mask_slots_rmsa_gn_model, VONE) casts to MASK_DTYPE to keep the scan carry dtype stable.
    return jnp.ones(
        params.k_paths * math.ceil(params.link_resources / agg) + (1 * include_no_op),
        dtype=dtype_config.MASK_DTYPE,
    )

Initialise signal-to-noise ratio (SNR) array. Args: params (EnvParams): Environment parameters Returns: jnp.array: SNR array

Source code in xlron/environments/env_funcs.py
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
def init_link_snr_array(params: EnvParams):
    """Initialise signal-to-noise ratio (SNR) array.
    Args:
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: SNR array
    """
    # The SNR is kept in linear units to allow summation of 1/SNR across links
    return jnp.full(
        (params.num_links, params.link_resources), -1e5, dtype=dtype_config.LARGE_FLOAT_DTYPE
    )

init_mod_format_mask(params)

Initialize link mask

Source code in xlron/environments/env_funcs.py
1221
1222
1223
1224
1225
1226
1227
1228
1229
@jax.jit
def init_mod_format_mask(params: EnvParams):
    """Initialize link mask"""
    # Modulation-format mask: {-1} where invalid, small modulation indices where valid (exact in
    # float16). Bulk float tier; the recompute (mask_slots_bit_rate_mod_format) and select_action
    # cast back to SMALL_FLOAT to keep the carried dtype stable.
    return jnp.full(
        (params.k_paths * params.link_resources,), -1.0, dtype=dtype_config.SMALL_FLOAT_DTYPE
    )

init_modulation_format_index_array(params)

Initialise modulation format index array. Args: params (EnvParams): Environment parameters Returns: jnp.array: Modulation format index array

Source code in xlron/environments/env_funcs.py
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
def init_modulation_format_index_array(params: EnvParams):
    """Initialise modulation format index array.
    Args:
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: Modulation format index array
    """
    return jnp.full(
        (params.num_links, params.link_resources), -1, dtype=dtype_config.LARGE_INT_DTYPE
    )  # -1 so that highest order is assumed (closest to Gaussian)

init_modulations_array(modulations_filepath=None)

Initialise array of maximum spectral efficiency for modulation format on path.

Parameters:

Name Type Description Default
modulations_filepath str

Path to CSV file containing modulation formats. Defaults to None.

None

Returns: jnp.array: Array of maximum spectral efficiency for modulation format on path. First two columns are maximum path length and spectral efficiency.

Source code in xlron/environments/env_funcs.py
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
def init_modulations_array(modulations_filepath: str | None = None) -> Array:
    """Initialise array of maximum spectral efficiency for modulation format on path.

    Args:
        modulations_filepath (str, optional): Path to CSV file containing modulation formats. Defaults to None.
    Returns:
        jnp.array: Array of maximum spectral efficiency for modulation format on path.
        First two columns are maximum path length and spectral efficiency.
    """
    f = (
        pathlib.Path(modulations_filepath)
        if modulations_filepath
        else (
            pathlib.Path(__file__).parents[1].absolute()
            / "data"
            / "modulations"
            / "modulations.csv"
        )
    )
    modulations = np.genfromtxt(f, delimiter=",")
    # Drop empty first row (headers) and column (name)
    modulations = modulations[1:, 1:]
    return jnp.array(modulations, dtype=dtype_config.LARGE_FLOAT_DTYPE)

init_path_capacity_array(link_length_array, path_link_array, min_request=1, scale_factor=1.0, alpha=0.0002, NF=4.5, B=10000000000000.0, R_s=100000000000.0, beta_2=-2.17e-26, gamma=0.0012, L_s=100000.0, lambda0=1.55e-06)

Calculated from Nevin paper: https://api.repository.cam.ac.uk/server/api/core/bitstreams/b80e7a9c-a86b-4b30-a6d6-05017c60b0c8/content

Parameters:

Name Type Description Default
link_length_array Array

Array of link lengths

required
path_link_array Array

Array of links on paths

required
min_request int

Minimum data rate request size. Defaults to 100 GBps.

1
scale_factor float

Scale factor for link capacity. Defaults to 1.0.

1.0
alpha float

Fibre attenuation coefficient. Defaults to 0.2e-3 /m

0.0002
NF float

Amplifier noise figure. Defaults to 4.5 dB.

4.5
B float

Total modulated bandwidth. Defaults to 10e12 Hz.

10000000000000.0
R_s float

Symbol rate. Defaults to 100e9 Baud.

100000000000.0
beta_2 float

Dispersion parameter. Defaults to -21.7e-27 s^2/m.

-2.17e-26
gamma float

Nonlinear coefficient. Defaults to 1.2e-3 /W/m.

0.0012
L_s float

Span length. Defaults to 100e3 m.

100000.0
lambda0 float

Wavelength. Defaults to 1550e-9 m.

1.55e-06

Returns:

Name Type Description
Array Array

Array of link capacities in Gbps

Source code in xlron/environments/env_funcs.py
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
def init_path_capacity_array(
    link_length_array: Array,
    path_link_array: Array,
    min_request=1,  # Minimum data rate request size
    scale_factor=1.0,  # Scale factor for link capacity
    alpha=0.2e-3,  # Fibre attenuation coefficient
    NF=4.5,  # Amplifier noise figure
    B=10e12,  # Total modulated bandwidth
    R_s=100e9,  # Symbol rate
    beta_2=-21.7e-27,  # Dispersion parameter
    gamma=1.2e-3,  # Nonlinear coefficient
    L_s=100e3,  # span length
    lambda0=1550e-9,  # Wavelength
) -> Array:
    """Calculated from Nevin paper:
    https://api.repository.cam.ac.uk/server/api/core/bitstreams/b80e7a9c-a86b-4b30-a6d6-05017c60b0c8/content

    Args:
        link_length_array (Array): Array of link lengths
        path_link_array (Array): Array of links on paths
        min_request (int, optional): Minimum data rate request size. Defaults to 100 GBps.
        scale_factor (float, optional): Scale factor for link capacity. Defaults to 1.0.
        alpha (float, optional): Fibre attenuation coefficient. Defaults to 0.2e-3 /m
        NF (float, optional): Amplifier noise figure. Defaults to 4.5 dB.
        B (float, optional): Total modulated bandwidth. Defaults to 10e12 Hz.
        R_s (float, optional): Symbol rate. Defaults to 100e9 Baud.
        beta_2 (float, optional): Dispersion parameter. Defaults to -21.7e-27 s^2/m.
        gamma (float, optional): Nonlinear coefficient. Defaults to 1.2e-3 /W/m.
        L_s (float, optional): Span length. Defaults to 100e3 m.
        lambda0 (float, optional): Wavelength. Defaults to 1550e-9 m.

    Returns:
        Array: Array of link capacities in Gbps
    """
    path_length_array = jnp.dot(path_link_array, link_length_array)
    path_capacity_array = calculate_path_capacity(
        path_length_array,
        min_request=min_request,
        scale_factor=scale_factor,
        alpha=alpha,
        NF=NF,
        B=B,
        R_s=R_s,
        beta_2=beta_2,
        gamma=gamma,
        L_s=L_s,
        lambda0=lambda0,
    )
    return path_capacity_array.astype(dtype_config.LARGE_FLOAT_DTYPE)

init_path_index_array(params)

Initialise path index array. Represents index of lightpath occupying each slot.

Source code in xlron/environments/env_funcs.py
3091
3092
3093
def init_path_index_array(params):
    """Initialise path index array. Represents index of lightpath occupying each slot."""
    return jnp.full((params.num_links, params.link_resources), -1)

init_path_length_array(path_link_array, graph)

Initialise path length array.

Parameters:

Name Type Description Default
path_link_array Array

Path-link array

required
graph Graph

NetworkX graph

required

Returns: Array: Path length array

Source code in xlron/environments/env_funcs.py
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
def init_path_length_array(path_link_array: Array, graph: nx.Graph) -> Array:
    """Initialise path length array.

    Args:
        path_link_array (Array): Path-link array
        graph (nx.Graph): NetworkX graph
    Returns:
        Array: Path length array
    """
    link_length_array = init_link_length_array(graph)
    # Use numpy for this one-time setup dot product — avoids JAX overhead
    # and works with a compact dtype for the large binary path_link_array.
    pla = np.asarray(path_link_array, dtype=np.int8)
    lla = np.asarray(link_length_array, dtype=np.float64)
    path_lengths = pla.astype(np.float64) @ lla
    return jnp.array(path_lengths)

Optimized init_path_link_array.

Key optimizations over the original: 1. O(1) edge lookup via dictionary instead of O(E) linear scan per hop 2. Parallel path computation across node pairs via multiprocessing 3. Pre-allocated numpy array instead of list-of-lists append 4. Vectorized link_usage construction with numpy advanced indexing 5. Optional disk caching of computed arrays (cache_dir parameter)

Each path is defined by a link utilisation array (one row in the path-link array). 1 indicates link corresponding to index is used, 0 indicates not used.

Parameters:

Name Type Description Default
graph Graph

NetworkX graph

required
k int

Number of paths per node pair

required
disjoint bool

Whether to use edge-disjoint paths

False
path_sort_criteria str

Sort paths by criterion

''
directed bool

Whether graph is directed

False
modulations_array None | Array

Array of maximum spectral efficiency for modulation format on path

None
rwa_lr bool

Whether the environment is RWA with lightpath reuse

False
scale_factor float

Scale factor for capacity calculation

1.0
path_snr bool

If GN model is used, include extra row of zeroes for unutilised paths

False
n_workers int

Number of parallel workers for path computation (1 = sequential)

1
topology_name str | None

Topology name for cache filename (required if cache_dir is set)

None
cache_dir str | Path | None

Directory for caching computed arrays. None disables caching.

None

Returns:

Type Description
Array

Path-link array (N(N-1)*k x E) where N is number of nodes,

Array

E is number of edges, k is number of shortest paths

Source code in xlron/environments/env_funcs.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
def init_path_link_array(
    graph: nx.Graph,
    k: int,
    disjoint: bool = False,
    path_sort_criteria: str = "",
    directed: bool = False,
    modulations_array: None | Array = None,
    rwa_lr: bool = False,
    scale_factor: float = 1.0,
    path_snr: bool = False,
    n_workers: int = 1,
    topology_name: str | None = None,
    cache_dir: str | pathlib.Path | None = None,
    maximum_path_length_km: float | None = None,
) -> Array:
    """Optimized init_path_link_array.

    Key optimizations over the original:
    1. O(1) edge lookup via dictionary instead of O(E) linear scan per hop
    2. Parallel path computation across node pairs via multiprocessing
    3. Pre-allocated numpy array instead of list-of-lists append
    4. Vectorized link_usage construction with numpy advanced indexing
    5. Optional disk caching of computed arrays (cache_dir parameter)

    Each path is defined by a link utilisation array (one row in the path-link array).
    1 indicates link corresponding to index is used, 0 indicates not used.

    Args:
        graph: NetworkX graph
        k: Number of paths per node pair
        disjoint: Whether to use edge-disjoint paths
        path_sort_criteria: Sort paths by criterion
        directed: Whether graph is directed
        modulations_array: Array of maximum spectral efficiency for modulation format on path
        rwa_lr: Whether the environment is RWA with lightpath reuse
        scale_factor: Scale factor for capacity calculation
        path_snr: If GN model is used, include extra row of zeroes for unutilised paths
        n_workers: Number of parallel workers for path computation (1 = sequential)
        topology_name: Topology name for cache filename (required if cache_dir is set)
        cache_dir: Directory for caching computed arrays. None disables caching.

    Returns:
        Path-link array (N(N-1)*k x E) where N is number of nodes,
        E is number of edges, k is number of shortest paths
    """
    # --- Disk cache lookup ---
    cache_path = None
    if cache_dir is not None:
        cache_dir = pathlib.Path(cache_dir)
        cache_dir.mkdir(parents=True, exist_ok=True)
        params_hash = _ksp_cache_key(
            graph,
            k,
            disjoint,
            path_sort_criteria,
            directed,
            modulations_array,
            rwa_lr,
            scale_factor,
            path_snr,
            maximum_path_length_km=maximum_path_length_km,
        )
        name = topology_name or "unknown"
        cache_path = cache_dir / f"{name}_k{k}_{path_sort_criteria}_{params_hash}.npz"
        if cache_path.exists():
            print(f"  Loading cached KSP array from {cache_path.name}")
            data = np.load(cache_path)
            arr = np.array(data["arr"], dtype=np.int8)
            if maximum_path_length_km is not None:
                # Cache already contains filtered+trimmed array; read effective_k from shape
                num_pairs = (
                    graph.number_of_nodes() * (graph.number_of_nodes() - 1)
                    if graph.is_directed()
                    else (graph.number_of_nodes() * (graph.number_of_nodes() - 1) // 2)
                )
                data_rows = arr.shape[0] - (1 if path_snr else 0)
                effective_k = data_rows // num_pairs
                return arr, effective_k
            return arr
        print(f"  KSP cache miss — computing paths (will save to {cache_path.name})")

    assert path_sort_criteria in [
        "spectral_resources",
        "hops",
        "distance",
        "hops_distance",
        "capacity",
    ], (
        f"path_sort_criteria must be one of 'spectral_resources', 'hops', 'distance', "
        f"'hops_distance', or 'capacity' got '{path_sort_criteria}'"
    )

    # Determine weight parameter for shortest path computation
    weight = (
        None
        if path_sort_criteria in ["spectral_resources", "hops", "hops_distance", "capacity"]
        else "distance"
    )

    # --- Optimization 1: Build O(1) edge lookup once ---
    edge_to_index, edges = _build_edge_index(graph, directed)
    num_edges = len(edges)

    # --- Optimization 2: Compute paths (optionally in parallel) ---
    node_pairs = list(combinations(graph.nodes, 2))
    if directed:
        node_pairs_rev = [(t, s) for s, t in combinations(graph.nodes, 2)]
        node_pairs = node_pairs + node_pairs_rev

    work_items = [(graph, source, target, k, weight, disjoint) for source, target in node_pairs]

    if n_workers > 1 and len(work_items) > 1:
        with ProcessPoolExecutor(max_workers=n_workers) as executor:
            k_path_collections = list(executor.map(_compute_paths_for_pair, work_items))
    else:
        k_path_collections = [_compute_paths_for_pair(item) for item in work_items]

    # --- Precompute modulations lookup (reversed once, as numpy) ---
    # np.asarray avoids a JAX device sync per path in _get_spectral_efficiency below.
    if modulations_array is not None:
        modulations_reversed = np.asarray(modulations_array[::-1])

    def _get_spectral_efficiency(distance: float) -> float:
        if modulations_array is None:
            return 1.0
        for modulation in modulations_reversed:
            if distance <= modulation[0]:
                return float(modulation[1])
        return 1.0  # fallback

    # --- Optimization 3: Pre-allocate output array ---
    num_pairs = len(k_path_collections)
    total_rows = num_pairs * k + (1 if path_snr else 0)
    all_link_usage = np.zeros((total_rows, num_edges), dtype=np.int8)

    # --- Process each node pair's paths ---
    row = 0
    for k_paths in k_path_collections:
        if not k_paths:
            # No paths found — fill k rows with zeros (already zero)
            row += k
            continue

        # Compute per-path metrics
        num_actual_paths = len(k_paths)
        path_distances = [nx.path_weight(graph, path, weight="distance") for path in k_paths]
        path_hops = [len(path) - 1 for path in k_paths]
        path_se = [_get_spectral_efficiency(d) for d in path_distances]

        if rwa_lr:
            path_capacity = [
                float(calculate_path_capacity(d, scale_factor=scale_factor)) + 1e-6
                for d in path_distances
            ]
        else:
            path_capacity = [1.0] * num_actual_paths

        # Pad to k entries for sorting
        num_missing = k - num_actual_paths
        k_paths_padded = k_paths + [None] * num_missing
        path_distances += [1e6] * num_missing
        path_hops += [1e6] * num_missing
        path_se += [0.0] * num_missing
        path_capacity += [0.0] * num_missing

        # Sort by criteria
        indices = list(range(len(k_paths_padded)))
        indices.sort(
            key=lambda i: _sort_key(
                path_sort_criteria,
                path_distances[i],
                path_hops[i],
                path_se[i],
                path_capacity[i],
                rwa_lr,
            )
        )

        # --- Optimization 4: Vectorized link usage with advanced indexing ---
        for rank, idx in enumerate(indices[:k]):
            path = k_paths_padded[idx]
            if path is None:
                # Dummy path — already zero
                pass
            else:
                # Use numpy advanced indexing for the entire path at once
                edge_indices = [
                    edge_to_index[(path[i], path[i + 1])]
                    for i in range(len(path) - 1)
                    if (path[i], path[i + 1]) in edge_to_index
                ]
                if edge_indices:
                    all_link_usage[row + rank, edge_indices] = 1

        row += k

    # path_snr extra row is already zero from pre-allocation

    result = np.array(all_link_usage, dtype=np.int8)
    effective_k = None
    if maximum_path_length_km is not None:
        result, effective_k = _apply_max_path_length_filter(
            result, graph, k, maximum_path_length_km, path_snr
        )

    # --- Save to disk cache (stores filtered result when filter is active) ---
    if cache_path is not None:
        np.savez_compressed(cache_path, arr=result)
        print(f"  Saved KSP cache to {cache_path.name} ({cache_path.stat().st_size / 1e6:.1f} MB)")

    if effective_k is not None:
        return result, effective_k
    return result

init_path_se_array(path_length_array, modulations_array)

Initialise array of maximum spectral efficiency for highest-order modulation format on path.

Parameters:

Name Type Description Default
path_length_array array

Array of path lengths

required
modulations_array array

Array of maximum spectral efficiency for modulation format on path

required

Returns:

Type Description
Array

jnp.array: Array of maximum spectral efficiency for on path

Source code in xlron/environments/env_funcs.py
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
def init_path_se_array(path_length_array: Array, modulations_array: Array) -> Array:
    """Initialise array of maximum spectral efficiency for highest-order modulation format on path.

    Args:
        path_length_array (jnp.array): Array of path lengths
        modulations_array (jnp.array): Array of maximum spectral efficiency for modulation format on path

    Returns:
        jnp.array: Array of maximum spectral efficiency for on path
    """
    # Flip so that max_length is ascending (shortest reach first)
    modulations_array = np.asarray(modulations_array[::-1])
    max_lengths = modulations_array[:, 0]  # ascending
    se_values = modulations_array[:, 1]

    path_lengths = np.asarray(path_length_array).ravel()

    # For each path, find the first modulation where path_length <= max_length.
    # searchsorted with side='left' on max_lengths gives the index of the first
    # max_length that is >= path_length (since we want length <= max_length).
    indices = np.searchsorted(max_lengths, path_lengths, side="left")
    # Clamp to valid range (paths longer than all modulations get the last one)
    indices = np.clip(indices, 0, len(se_values) - 1)
    return se_values[indices].astype(np.int8)

init_rsa_request_array()

Initialize request array [source, datarate, dest].

Source code in xlron/environments/env_funcs.py
1199
1200
1201
1202
1203
1204
def init_rsa_request_array():
    """Initialize request array [source, datarate, dest]."""
    # Kept on the LARGE_INT tier (int32): it is only 3 elements (negligible memory) and is rebuilt
    # each step by generate_request, whose dtype is path-dependent (float32 for deterministic
    # requests, int for random) -- pinning it small would risk a scan carry dtype mismatch.
    return jnp.zeros(3, dtype=dtype_config.LARGE_INT_DTYPE)

init_traffic_matrix(key, params)

Initialize traffic matrix. Allows for random traffic matrix or uniform traffic matrix. Source-dest traffic requests are sampled probabilistically from the resulting traffic matrix.

Parameters:

Name Type Description Default
key PRNGKey

PRNG key

required
params EnvParams

Environment parameters

required

Returns:

Type Description
Array

jnp.array: Traffic matrix

Source code in xlron/environments/env_funcs.py
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
@jax.jit
def init_traffic_matrix(key: chex.PRNGKey, params: EnvParams) -> Array:
    """Initialize traffic matrix. Allows for random traffic matrix or uniform traffic matrix.
    Source-dest traffic requests are sampled probabilistically from the resulting traffic matrix.

    Args:
        key (chex.PRNGKey): PRNG key
        params (EnvParams): Environment parameters

    Returns:
        jnp.array: Traffic matrix
    """
    # Construct directly in the precision tier (LARGE_FLOAT): the matrix is consumed
    # at float32 (see final cast), so sampling/normalising in SMALL_FLOAT (float16
    # under mixed precision) would just lose precision before the upcast.
    if params.random_traffic:
        traffic_matrix = jax.random.uniform(
            key, shape=(params.num_nodes, params.num_nodes), dtype=dtype_config.LARGE_FLOAT_DTYPE
        )
    else:
        traffic_matrix = jnp.ones(
            (params.num_nodes, params.num_nodes), dtype=dtype_config.LARGE_FLOAT_DTYPE
        )
    diag_elements = jnp.diag_indices_from(traffic_matrix)
    # Set main diagonal to zero so no requests from node to itself
    traffic_matrix = traffic_matrix.at[diag_elements].set(0)
    traffic_matrix = normalise_traffic_matrix(traffic_matrix)
    return traffic_matrix.astype(jnp.float32)

init_transceiver_amplifier_noise_arrays(link_resources, ref_lambda, slot_size, noise_data_filepath=None, slot_frequencies_ghz=None)

Initialise transceiver, amplifier, and ROADM noise arrays from per-band CSV data.

Parameters:

Name Type Description Default
link_resources int

Number of link resources.

required
ref_lambda float

Reference wavelength.

required
slot_size float

Slot size in GHz.

required
noise_data_filepath str

Path to CSV file. Defaults to None.

None
slot_frequencies_ghz ndarray

Pre-computed absolute slot centre frequencies in GHz. When provided, these are used directly instead of computing from the uniform formula.

None

Returns:

Type Description
Tuple[Array, Array, Array, Array, Array]

Tuple of per-slot arrays: (transceiver_snr, amplifier_noise_figure, roadm_express_loss, roadm_add_drop_loss, roadm_noise_figure)

Source code in xlron/environments/env_funcs.py
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
def init_transceiver_amplifier_noise_arrays(
    link_resources: int,
    ref_lambda: float,
    slot_size: float,
    noise_data_filepath: str | None = None,
    slot_frequencies_ghz: np.ndarray | None = None,
) -> Tuple[Array, Array, Array, Array, Array]:
    """Initialise transceiver, amplifier, and ROADM noise arrays from per-band CSV data.

    Args:
        link_resources (int): Number of link resources.
        ref_lambda (float): Reference wavelength.
        slot_size (float): Slot size in GHz.
        noise_data_filepath (str, optional): Path to CSV file. Defaults to None.
        slot_frequencies_ghz (np.ndarray, optional): Pre-computed absolute slot
            centre frequencies in GHz.  When provided, these are used directly
            instead of computing from the uniform formula.

    Returns:
        Tuple of per-slot arrays: (transceiver_snr, amplifier_noise_figure,
            roadm_express_loss, roadm_add_drop_loss, roadm_noise_figure)
    """
    f = (
        pathlib.Path(noise_data_filepath)
        if noise_data_filepath
        else (
            pathlib.Path(__file__).parents[1].absolute()
            / "data"
            / "gn_model"
            / "transceiver_amplifier_data"
            / "transceiver_amplifier_data.csv"
        )
    )
    noise_data = np.genfromtxt(f, delimiter=",")
    # Drop empty first row (headers) and column (name)
    noise_data = noise_data[1:, 1:]
    # Columns are: wavelength_min_nm,wavelength_max_nm,frequency_min_ghz,frequency_max_ghz,
    #   NF_ASE_dB,SNR_TRX_dB,roadm_express_loss_dB,roadm_add_drop_loss_dB,roadm_NF_dB
    frequency_min_ghz = noise_data[:, 2]
    frequency_max_ghz = noise_data[:, 3]
    jax_comparison = slot_frequencies_ghz is None or isinstance(slot_frequencies_ghz, jax.Array)
    if slot_frequencies_ghz is None:
        # Match the legacy JAX default-dtype rounding, including frequencies
        # exactly on a band boundary, without thousands of device dispatches.
        dtype = np.float64 if jax.config.jax_enable_x64 else np.float32
        slot_centres = (
            np.arange(link_resources, dtype=dtype) - dtype((link_resources - 1) / 2)
        ) * dtype(slot_size)
        slot_frequencies_ghz = dtype(c / ref_lambda / 1e9) + slot_centres

    frequencies = np.asarray(slot_frequencies_ghz)
    if jax_comparison:
        # The old scalar JAX comparison casts CSV bounds to the array dtype.
        # NumPy-provided frequencies instead retain NumPy's promotion rules.
        frequency_min_ghz = frequency_min_ghz.astype(frequencies.dtype)
        frequency_max_ghz = frequency_max_ghz.astype(frequencies.dtype)
    matches = (frequencies[:, None] >= frequency_min_ghz) & (
        frequencies[:, None] <= frequency_max_ghz
    )
    # argmax retains the first CSV row when bands overlap, as the old loop did.
    bands = np.argmax(matches, axis=1)
    values = noise_data[:, [5, 4, 6, 7, 8]][bands]
    values = np.where(np.any(matches, axis=1)[:, None], values, 0.0)
    return tuple(jnp.asarray(values[:, column]) for column in range(5))

XPM rows of links after inserting one channel, for get_snr_link_array rows.

The rows are per channel entry (channel_physics_rows), as get_snr_link_array evaluates them: the inserted channel is the single entry at its first slot.

Parameters:

Name Type Description Default
coefficients

(H, 3, S) link_xpm_coefficients of the links before insertion.

required
rows

(bandwidth, power, centre, ...) (H, S) channel rows after insertion.

required
start

the inserted channel's first slot; power, centre, width its values [W, GHz, GHz].

required
Source code in xlron/environments/env_funcs.py
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
def inserted_link_xpm(coefficients, rows, start, power, centre, width, params) -> Array:
    """XPM rows of links after inserting one channel, for get_snr_link_array rows.

    The rows are per channel entry (channel_physics_rows), as get_snr_link_array
    evaluates them: the inserted channel is the single entry at its first slot.

    Args:
        coefficients: (H, 3, S) link_xpm_coefficients of the links before insertion.
        rows: (bandwidth, power, centre, ...) (H, S) channel rows after insertion.
        start: the inserted channel's first slot; power, centre, width its values
            [W, GHz, GHz].
    """
    bandwidth, link_power, _, _ = channel_physics_rows(*rows[:3])
    inside = jnp.arange(bandwidth.shape[-1]) == start

    def link(c, b, p, f):
        return isrs_gn_model.xpm_after_insertion(
            c,
            p,
            f * 1e9,
            b * 1e9,
            inside,
            power,
            centre * 1e9,
            width * 1e9,
            1,
            **_uniform_xpm_physics(params),
        )

    return jax.vmap(link)(coefficients, bandwidth, link_power, rows[2])

lightpath_representatives(state, params)

One (links, slots) cell per lightpath: its first slot on the first link of its path.

A lightpath is identified by its path index and centre frequency: two lightpaths on one path never share a centre frequency because their slots cannot overlap.

Source code in xlron/environments/env_funcs.py
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
def lightpath_representatives(state: GNModelEnvState, params: GNModelEnvParams) -> Array:
    """One (links, slots) cell per lightpath: its first slot on the first link of its path.

    A lightpath is identified by its path index and centre frequency: two lightpaths on
    one path never share a centre frequency because their slots cannot overlap.
    """
    pid = state.path_index_array
    centre = state.channel_centre_freq_array
    present = state.channel_centre_bw_array != 0
    first_link = params.path_link_indices[jnp.maximum(pid, 0), 0]
    on_first_link = first_link == jnp.arange(params.num_links)[:, None]
    continues = jnp.concatenate(
        (
            jnp.zeros((params.num_links, 1), bool),
            (pid[:, 1:] == pid[:, :-1]) & (centre[:, 1:] == centre[:, :-1]) & present[:, :-1],
        ),
        axis=1,
    )
    return present & (pid >= 0) & on_first_link & ~continues

Whether state.link_snr_array always equals get_snr_link_array(state).

Link SNR depends only on that link's own channels. Under safe_release every change re-solves exactly the links it touches (admissions, releases, and rollbacks restore the snapshot), so consumers may read the cache directly. Immediate departures leave the remaining channels on their links stale.

Source code in xlron/environments/env_funcs.py
4538
4539
4540
4541
4542
4543
4544
4545
4546
def link_snr_cache_is_fresh(params: GNModelEnvParams) -> bool:
    """Whether state.link_snr_array always equals get_snr_link_array(state).

    Link SNR depends only on that link's own channels. Under safe_release every
    change re-solves exactly the links it touches (admissions, releases, and
    rollbacks restore the snapshot), so consumers may read the cache directly.
    Immediate departures leave the remaining channels on their links stale.
    """
    return getattr(params, "departure_policy", "immediate") == "safe_release"

(links, 3, slots) polynomial XPM coefficients of every link (Pallas, uniform spans).

With inserted_link_xpm, a candidate insertion then re-solves its path links' XPM in O(slots) per link instead of a full interferer reduction.

Source code in xlron/environments/env_funcs.py
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
def link_xpm_coefficients(state: GNModelEnvState, params: GNModelEnvParams) -> Array:
    """(links, 3, slots) polynomial XPM coefficients of every link (Pallas, uniform spans).

    With inserted_link_xpm, a candidate insertion then re-solves its path links'
    XPM in O(slots) per link instead of a full interferer reduction.
    """
    from xlron.kernels.gn_xpm import xpm_pallas

    physics = _uniform_xpm_physics(params)
    bandwidth, power, _, _ = channel_physics_rows(
        state.channel_centre_bw_array, state.channel_power_array, state.channel_centre_freq_array
    )

    def link(bandwidth, power, centre):
        return xpm_pallas(power, centre * 1e9, bandwidth * 1e9, polynomial=True, **physics)

    return jax.vmap(link)(bandwidth, power, state.channel_centre_freq_array)

live_lightpath_mask(state, params)

Cells whose lightpath carries traffic and so must meet its SNR threshold.

A channel has one SNR, so only its first signal slot on each link is checked (channel_physics_rows); the GN masks rely on this to skip the SNR broadcast.

Source code in xlron/environments/env_funcs.py
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
def live_lightpath_mask(state: GNModelEnvState, params: GNModelEnvParams) -> Array:
    """Cells whose lightpath carries traffic and so must meet its SNR threshold.

    A channel has one SNR, so only its first signal slot on each link is checked
    (channel_physics_rows); the GN masks rely on this to skip the SNR broadcast.
    """
    _, _, first, _ = channel_physics_rows(
        state.channel_centre_bw_array, state.channel_power_array, state.channel_centre_freq_array
    )
    return first & ~held_lightpath_mask(state, params)

make_graph(topology_name='conus', topology_directory=None)

Create graph from topology definition. Topologies must be defined in JSON format in the topologies directory and named as the topology name with .json extension.

Parameters:

Name Type Description Default
topology_name str

topology name

'conus'
topology_directory str | None

topology directory

None

Returns:

Name Type Description
graph

graph

Source code in xlron/environments/env_funcs.py
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
def make_graph(topology_name: str = "conus", topology_directory: str | None = None):
    """Create graph from topology definition.
    Topologies must be defined in JSON format in the topologies directory and
    named as the topology name with .json extension.

    Args:
        topology_name: topology name
        topology_directory: topology directory

    Returns:
        graph: graph
    """
    topology_path = (
        pathlib.Path(topology_directory)
        if topology_directory
        else (pathlib.Path(__file__).parents[1].absolute() / "data" / "topologies")
    )
    # Create topology
    if topology_name == "4node":
        # 4 node ring
        graph = nx.from_numpy_array(
            np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
        )
        # Add edge weights to graph
        nx.set_edge_attributes(graph, {(0, 1): 4, (1, 2): 3, (2, 3): 2, (3, 0): 1}, "distance")
    elif topology_name == "7node":
        # 7 node ring
        graph = nx.from_numpy_array(
            jnp.array(
                [
                    [0, 1, 0, 0, 0, 0, 1],
                    [1, 0, 1, 0, 0, 0, 0],
                    [0, 1, 0, 1, 0, 0, 0],
                    [0, 0, 1, 0, 1, 0, 0],
                    [0, 0, 0, 1, 0, 1, 0],
                    [0, 0, 0, 0, 1, 0, 1],
                    [1, 0, 0, 0, 0, 1, 0],
                ]
            )
        )
        # Add edge weights to graph
        nx.set_edge_attributes(
            graph,
            {
                (0, 1): 4,
                (1, 2): 3,
                (2, 3): 2,
                (3, 4): 1,
                (4, 5): 2,
                (5, 6): 3,
                (6, 0): 4,
            },
            "distance",
        )
    else:
        topology_file = topology_path / f"{topology_name}.json"
        if not topology_file.is_file():
            available = sorted(p.stem for p in topology_path.glob("*.json")) + ["4node", "7node"]
            suggestions = difflib.get_close_matches(topology_name, available, n=3, cutoff=0.5)
            msg = f"Unknown topology '{topology_name}'."
            if suggestions:
                msg += f" Did you mean: {', '.join(suggestions)}?"
            msg += (
                f" {len(available)} topologies are available in {topology_path} "
                f"(use the filename without the .json extension)."
            )
            raise ValueError(msg)
        with open(topology_file) as f:
            graph = nx.node_link_graph(json.load(f), edges="links")
    # Topology JSONs are mixed-base (TopologyBench-derived files number nodes 1..N, others
    # 0..N-1), but node labels are used directly as row indices into node-feature arrays
    # (spectral features, source/dest one-hots, adjacency/Laplacian) and as GNN
    # senders/receivers. Normalise to 0..N-1 in sorted-id order. The relabelling is monotone,
    # so sorted(graph.edges) column order (spectrum arrays, path_link_array) is unchanged.
    graph = nx.convert_node_labels_to_integers(graph, ordering="sorted")
    if list(graph.nodes) != sorted(graph.nodes):
        # convert_node_labels_to_integers keeps the file's node insertion order; rebuild so
        # iteration order == 0..N-1, which adjacency/Laplacian row order and
        # combinations(graph.nodes, 2) (path table / triangular indexing) rely on.
        ordered = graph.__class__()
        ordered.graph.update(graph.graph)
        ordered.add_nodes_from(sorted(graph.nodes(data=True)))
        ordered.add_edges_from(graph.edges(data=True))
        graph = ordered
    return graph

make_line_graph(graph)

Create the line graph of a NetworkX graph.

The line graph L(G) has: - One node for each edge in the original graph G - An edge between two nodes in L(G) if the corresponding edges in G share a node

This is used for transformer architectures where we treat edges (links) as tokens and need positional encodings based on edge relationships.

Parameters:

Name Type Description Default
graph Graph

NetworkX graph (original topology)

required

Returns:

Name Type Description
line_graph Graph

NetworkX line graph where nodes correspond to edges in the original

Source code in xlron/environments/env_funcs.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def make_line_graph(graph: nx.Graph) -> nx.Graph:
    """Create the line graph of a NetworkX graph.

    The line graph L(G) has:
    - One node for each edge in the original graph G
    - An edge between two nodes in L(G) if the corresponding edges in G share a node

    This is used for transformer architectures where we treat edges (links) as tokens
    and need positional encodings based on edge relationships.

    Args:
        graph: NetworkX graph (original topology)

    Returns:
        line_graph: NetworkX line graph where nodes correspond to edges in the original
    """
    return nx.line_graph(graph)

mask_slots_rmsa_gn_model(state, params, request)

Compute the RMSA-GN action mask (see _mask_slots_rmsa_gn_model).

Under an outer environment vmap, all_slots masks are computed in chunks of gn_mask_env_batch_size environments (0: all of them) without changing policy batching. Each chunk runs in lockstep: its loops, switches and conds are shared, and with the Pallas endpoint screen its candidates go through shared queues (pooled_masks), so kernels cover the whole chunk without padding to the busiest environment. Chunks of 1, and first-fit masks without the endpoint screen, mask the environments one at a time.

Source code in xlron/environments/env_funcs.py
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
@jax.jit
def mask_slots_rmsa_gn_model(
    state: RMSAGNModelEnvState, params: RMSAGNModelEnvParams, request: Array
) -> EnvState:
    """Compute the RMSA-GN action mask (see _mask_slots_rmsa_gn_model).

    Under an outer environment vmap, all_slots masks are computed in chunks of
    gn_mask_env_batch_size environments (0: all of them) without changing policy
    batching. Each chunk runs in lockstep: its loops, switches and conds are
    shared, and with the Pallas endpoint screen its candidates go through shared
    queues (pooled_masks), so kernels cover the whole chunk without padding to
    the busiest environment. Chunks of 1, and first-fit masks without the
    endpoint screen, mask the environments one at a time.
    """

    def one(s, r, p):
        return _mask_slots_rmsa_gn_model(s, p, r)

    if params.gn_mask_mode != "all_slots" or (
        params.differentiable and not params.gn_mask_env_batch_size
    ):
        return one(state, request, params)
    if params.differentiable:
        raise ValueError("GN mask environment chunks require hard dynamics")

    batched_mask = custom_vmap(one)

    # params is an explicit argument, not a closure: its arrays are tracers of the
    # enclosing jit, which a custom_vmap rule cannot capture.
    @batched_mask.def_vmap
    def chunked(axis_size, in_batched, states, requests, params):
        if any(jax.tree.leaves(in_batched[2])):
            raise ValueError("GN mask environment chunks need params shared by all envs")

        def broadcast(x, b):
            return x if b else jnp.broadcast_to(x, (axis_size,) + jnp.shape(x))

        states = jax.tree.map(broadcast, states, in_batched[0])
        requests = broadcast(requests, in_batched[1])
        batch_size = min(params.gn_mask_env_batch_size or axis_size, axis_size)
        # First-fit masks stop at each environment's own first fit. Only pooled
        # (Pallas endpoint-screened) chunks keep that per environment; in plain
        # lockstep every environment would scan as deep as the deepest one.
        if batch_size == 1 or (params.gn_mask_first_fit and not _gn_endpoint_screen(params)):
            # A plain scan: lax.map with batch_size=1 still vmaps a batch of one.
            result = jax.lax.map(lambda pair: one(*pair, params), (states, requests))
            return result, jax.tree.map(lambda _: True, result)

        lockstep = jax.vmap(
            partial(_mask_slots_rmsa_gn_model, params=params, env_axis=GN_MASK_ENV_AXIS),
            axis_name=GN_MASK_ENV_AXIS,
        )
        chunks = -(-axis_size // batch_size)
        padding = chunks * batch_size - axis_size

        def split(x):
            # Pad with copies of the last environment; their results are dropped.
            x = jnp.concatenate([x, jnp.repeat(x[-1:], padding, axis=0)]) if padding else x
            return x.reshape((chunks, batch_size) + x.shape[1:])

        pairs = jax.tree.map(split, (states, requests))
        result = jax.lax.map(lambda pair: lockstep(pair[0], request=pair[1]), pairs)
        result = jax.tree.map(lambda x: x.reshape((-1,) + x.shape[2:])[:axis_size], result)
        return result, jax.tree.map(lambda _: True, result)

    return batched_mask(state, request, params)

mask_slots_rwalr(state, params, request)

For use in RWALightpathReuseEnv. Each lightpath has a maximum capacity defined in path_capacity_array. This is updated when a lightpath is assigned. If remaining path capacity is less than current request, corresponding link-slots are masked out. If link-slot is in use by another lightpath for a different source and destination node (even if not full) it is masked out. Step 1: - Mask out slots that are not valid based on path capacity (check link_capacity_array) Step 2: - Mask out slots that are not valid based on lightpath reuse (check path_index_array)

Parameters:

Name Type Description Default
state RWALightpathReuseEnvState

Environment state

required
params EnvParams

Environment parameters

required
request Array

Request array in format [source_node, data-rate, destination_node]

required

Returns:

Name Type Description
state RWALightpathReuseEnvState

Updated environment state

Source code in xlron/environments/env_funcs.py
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
@jax.jit
def mask_slots_rwalr(
    state: RWALightpathReuseEnvState, params: EnvParams, request: Array
) -> RWALightpathReuseEnvState:
    """For use in RWALightpathReuseEnv.
    Each lightpath has a maximum capacity defined in path_capacity_array. This is updated when a lightpath is assigned.
    If remaining path capacity is less than current request, corresponding link-slots are masked out.
    If link-slot is in use by another lightpath for a different source and destination node (even if not full) it is masked out.
    Step 1:
    - Mask out slots that are not valid based on path capacity (check link_capacity_array)
    Step 2:
    - Mask out slots that are not valid based on lightpath reuse (check path_index_array)

    Args:
        state: Environment state
        params: Environment parameters
        request: Request array in format [source_node, data-rate, destination_node]

    Returns:
        state: Updated environment state
    """
    nodes_sd, requested_datarate = read_rsa_request(request)
    source, dest = nodes_sd
    path_start_index = get_path_indices(
        params,
        source,
        dest,
        params.k_paths,
        params.num_nodes,
        directed=params.directed_graph,
    ).astype(dtype_config.INDEX_DTYPE)
    # Step 1 - capacity mask (computed once, shared across paths)
    capacity_mask = (state.link_capacity_array < requested_datarate).astype(
        dtype_config.LARGE_FLOAT_DTYPE
    )

    # Step 2 - lightpath reuse masks (computed once, indexed per path)
    empty_mask = (state.path_index_array != -1).astype(dtype_config.LARGE_FLOAT_DTYPE)

    def single_path(i):
        capacity_slots = get_path_slots(capacity_mask, params, nodes_sd, i)

        lightpath_index = path_start_index + i
        lightpath_mask = (
            1.0 - (state.path_index_array == lightpath_index).astype(dtype_config.LARGE_FLOAT_DTYPE)
        ) * empty_mask
        lightpath_slots = get_path_slots(lightpath_mask, params, nodes_sd, i)

        # Combine: masked if either mask is active, then invert (1 = valid)
        combined = jnp.maximum(capacity_slots, lightpath_slots)
        return 1.0 - jnp.minimum(combined, 1.0)

    # Values are exactly {0, 1}, so the MASK-tier cast (bool in non-differentiable modes)
    # is lossless; consumers cast back to float at the point of use.
    link_slot_mask = (
        jax.vmap(single_path)(jnp.arange(params.k_paths))
        .reshape(-1)
        .astype(dtype_config.MASK_DTYPE)
    )

    full_link_slot_mask = link_slot_mask

    if params.aggregate_slots > 1:
        link_slot_mask = aggregate_slots(link_slot_mask, params)

    if params.include_no_op:
        link_slot_mask = jnp.concatenate(
            [link_slot_mask, jnp.ones((1,), dtype=dtype_config.MASK_DTYPE)]
        )

    return link_slot_mask, full_link_slot_mask

Static bound on the channels of one link: each takes a signal slot and its guard band.

Source code in xlron/environments/env_funcs.py
4155
4156
4157
def max_channels_per_link(params: RSAGNModelEnvParams) -> int:
    """Static bound on the channels of one link: each takes a signal slot and its guard band."""
    return -(-int(params.link_resources) // (1 + max(int(params.guardband), 0)))

normalise_traffic_matrix(traffic_matrix)

Normalise traffic matrix to sum to 1

Source code in xlron/environments/env_funcs.py
1246
1247
1248
1249
def normalise_traffic_matrix(traffic_matrix):
    """Normalise traffic matrix to sum to 1"""
    traffic_matrix /= jnp.sum(traffic_matrix, promote_integers=False)
    return traffic_matrix

pad_array(array, fill_value)

Pad a ragged multidimensional array to rectangular shape. Used for training on multiple topologies. Source: https://codereview.stackexchange.com/questions/222623/pad-a-ragged-multidimensional-array-to-rectangular-shape

Parameters:

Name Type Description Default
array

array to pad

required
fill_value

value to fill with

required

Returns:

Name Type Description
result

padded array

Source code in xlron/environments/env_funcs.py
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
def pad_array(array, fill_value):
    """
    Pad a ragged multidimensional array to rectangular shape.
    Used for training on multiple topologies.
    Source: https://codereview.stackexchange.com/questions/222623/pad-a-ragged-multidimensional-array-to-rectangular-shape

    Args:
        array: array to pad
        fill_value: value to fill with

    Returns:
        result: padded array
    """

    def get_dimensions(array, level=0):
        yield level, len(array)
        try:
            for row in array:
                yield from get_dimensions(row, level + 1)
        except TypeError:  # not an iterable
            pass

    def get_max_shape(array):
        dimensions = defaultdict(int)
        for level, length in get_dimensions(array):
            dimensions[level] = max(dimensions[level], length)
        return [value for _, value in sorted(dimensions.items())]

    def iterate_nested_array(array, index=()):
        try:
            for idx, row in enumerate(array):
                yield from iterate_nested_array(row, (*index, idx))
        except TypeError:  # final level
            yield (*index, slice(len(array))), array

    dimensions = get_max_shape(array)
    result = np.full(dimensions, fill_value)
    for index, value in iterate_nested_array(array):
        result[index] = value
    return result

process_path_action(state, params, path_action)

Process path action to get path index and initial slot index. Args: state (State): current state params (Params): environment parameters path_action (int): path action Returns: int: path index int: initial slot index

Source code in xlron/environments/env_funcs.py
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
@jax.jit
def process_path_action(
    state: EnvState, params: EnvParams, path_action: Array
) -> tuple[Array, Array]:
    """Process path action to get path index and initial slot index.
    Args:
        state (State): current state
        params (Params): environment parameters
        path_action (int): path action
    Returns:
        int: path index
        int: initial slot index
    """
    # ceil, matching init_link_slot_mask / aggregate_slots / the model action-space size
    # (floor would mis-decode path/slot whenever link_resources % aggregate_slots != 0)
    num_slot_actions = math.ceil(params.link_resources / params.aggregate_slots)
    if not params.differentiable:
        # Actions are integers here; // is exact integer floor division, so the
        # round/floor helpers (which promote through float) are redundant.
        path_action = path_action.astype(dtype_config.LARGE_INT_DTYPE)
        path_index = path_action // num_slot_actions
        initial_aggregated_slot_index = jnp.mod(path_action, num_slot_actions)
    else:
        path_action = differentiable_round_simple(
            path_action, params.temperature, params.differentiable
        )
        path_index = differentiable_floor(
            path_action // num_slot_actions, params.temperature, params.differentiable
        ).astype(dtype_config.LARGE_INT_DTYPE)
        initial_aggregated_slot_index = jnp.mod(path_action, num_slot_actions)
    initial_slot_index = initial_aggregated_slot_index * params.aggregate_slots

    if params.aggregate_slots > 1:
        # Compute flat index into 1D array of shape (k_paths * link_resources,)
        full_mask = state.full_link_slot_mask.reshape((params.k_paths, params.link_resources))
        # Mirror aggregate_slots: pad the trailing partial window with invalid (0) slots
        pad_size = num_slot_actions * params.aggregate_slots - params.link_resources
        if pad_size > 0:
            full_mask = jnp.pad(full_mask, ((0, 0), (0, pad_size)), constant_values=0)
        full_mask = full_mask.reshape((params.k_paths, num_slot_actions, params.aggregate_slots))
        window = jax.lax.dynamic_slice(
            full_mask,
            (path_index, initial_aggregated_slot_index, 0),
            (1, 1, params.aggregate_slots),
        )
        # Use argmax to get index of first 1 in slice of mask
        initial_slot_index = initial_slot_index + differentiable_argmax(
            window, temperature=params.temperature, differentiable=params.differentiable
        ).astype(dtype_config.LARGE_INT_DTYPE)
    return path_index, initial_slot_index

read_rsa_request(request_array)

Read RSA request from request array. Return source-destination nodes and bandwidth request. Args: request_array: request array Returns: Tuple[Array, Array]: source-destination nodes and bandwidth request

Source code in xlron/environments/env_funcs.py
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
def read_rsa_request(request_array: Array) -> Tuple[Array, Array]:
    """Read RSA request from request array. Return source-destination nodes and bandwidth request.
    Args:
        request_array: request array
    Returns:
        Tuple[Array, Array]: source-destination nodes and bandwidth request
    """
    nodes_sd = request_array[jnp.array([0, 2])]
    requested_datarate = request_array[1]
    return nodes_sd, requested_datarate

release_departures_safely(state, params)

Departure processing for departure_policy="safe_release" (issue #67).

Expired lightpaths are held (see held_lightpath_mask). Held lightpaths are then switched off oldest-first, each only if the GN model of the state without it (its path links re-solved; all other links are unchanged) and full end-to-end path SNR leave every live lightpath at or above its modulation threshold (and the existing_snr_margin reserve, capped at its current SNR, as for admissions). Every intermediate optical state is therefore safe, so live lightpaths never fall below threshold because of a departure. A rejected release is retried at later arrivals.

Source code in xlron/environments/env_funcs.py
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
def release_departures_safely(
    state: RMSAGNModelEnvState, params: RMSAGNModelEnvParams
) -> RMSAGNModelEnvState:
    """Departure processing for departure_policy="safe_release" (issue #67).

    Expired lightpaths are held (see held_lightpath_mask). Held lightpaths are then
    switched off oldest-first, each only if the GN model of the state without it
    (its path links re-solved; all other links are unchanged) and full end-to-end
    path SNR leave every live lightpath at or above its modulation threshold
    (and the existing_snr_margin reserve, capped at its current SNR, as for
    admissions). Every intermediate optical state is therefore safe, so live
    lightpaths never fall below threshold because of a departure. A rejected
    release is retried at later arrivals.
    """
    if params.relative_arrival_times:
        # Remaining times count down; held cells continue below zero, oldest lowest.
        # Every footprint cell counts down, guard slots included.
        present = state.path_index_array >= 0
        dep = state.link_slot_departure_array
        state = state.replace(
            link_slot_departure_array=jnp.where(present, dep - state.arrival_time, dep)
        )
    held = (held_lightpath_mask(state, params) & lightpath_representatives(state, params)).reshape(
        -1
    )
    # Order at most MAX_RELEASE_CANDIDATES held lightpaths per arrival, oldest first;
    # any beyond that are attempted at later arrivals.
    cells = first_true_indices(held, MAX_RELEASE_CANDIDATES)
    count = jnp.minimum(jnp.sum(held), MAX_RELEASE_CANDIDATES)
    ages = jnp.where(
        jnp.arange(MAX_RELEASE_CANDIDATES) < count,
        state.link_slot_departure_array.reshape(-1)[cells],
        jnp.inf,
    )
    order = cells[jnp.argsort(ages)]
    if params.existing_snr_margin > 0:
        current_snr = get_lightpath_snr(state, params)  # The cache is fresh (see attempt).
    else:
        current_snr = None

    def attempt(carry):
        k, passes, released_in_pass, rejected_in_pass, s, snr = carry
        link, slot = jnp.divmod(order[k], params.link_resources)
        candidate = _switch_off_lightpath(s, link, slot)
        # Only the departing lightpath's links change. The cache is fresh under
        # safe_release (every step refreshes or restores it, releases update it),
        # so recompute just those links (padding entries are dropped).
        path_links = params.path_link_indices[s.path_index_array[link, slot]]
        candidate = candidate.replace(
            link_snr_array=candidate.link_snr_array.at[path_links].set(
                get_snr_link_array(candidate, params, path_links), mode="drop"
            )
        )
        candidate_snr = get_lightpath_snr(candidate, params)
        required = get_required_snr_se_kurtosis_array(
            candidate.modulation_format_index_array, 2, params
        )
        if snr is not None:
            required = jnp.maximum(
                required, jnp.minimum(required + params.existing_snr_margin, snr)
            )
        still_held = held_lightpath_mask(s, params)[link, slot]
        safe = jnp.all(
            jnp.where(live_lightpath_mask(candidate, params), candidate_snr >= required, True)
        )
        release = still_held & safe
        s = s.replace(
            **{
                name: jnp.where(release, getattr(candidate, name), getattr(s, name))
                for name in (*_LIGHTPATH_ARRAYS, "link_snr_array")
            }
        )
        if snr is not None:
            snr = jnp.where(release, candidate_snr, snr)
        released_in_pass = released_in_pass | release
        rejected_in_pass = rejected_in_pass | (still_held & ~safe)
        # Retry the pass only if it both released (so margins changed) and rejected.
        wrap = (
            (k + 1 >= count)
            & released_in_pass
            & rejected_in_pass
            & (passes + 1 < SAFE_RELEASE_PASSES)
        )
        k = jnp.where(wrap, 0, k + 1)
        passes = passes + wrap
        released_in_pass = released_in_pass & ~wrap
        rejected_in_pass = rejected_in_pass & ~wrap
        return k, passes, released_in_pass, rejected_in_pass, s, snr

    _, _, _, _, state, _ = jax.lax.while_loop(
        lambda carry: carry[0] < count,
        attempt,
        (jnp.int32(0), jnp.int32(0), jnp.array(False), jnp.array(False), state, current_snr),
    )
    return state

remove_expired_services_rwalr(state, params)

Parameters:

Name Type Description Default
state RWALightpathReuseEnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Type Description
RWALightpathReuseEnvState

Updated environment state

Source code in xlron/environments/env_funcs.py
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
@jax.jit
def remove_expired_services_rwalr(
    state: RWALightpathReuseEnvState, params: EnvParams
) -> RWALightpathReuseEnvState:
    """

    Args:
        state: Environment state
        params: Environment parameters

    Returns:
        Updated environment state
    """
    # Set one where link_slot_departure_array is >= zero and <= current time
    current_time = state.current_time if not params.relative_arrival_times else state.arrival_time
    dep = state.link_slot_departure_array
    mask_remove = differentiable_compare(
        dep,
        current_time,
        "<=",
        temperature=params.temperature,
        differentiable=params.differentiable,
    ) * differentiable_compare(
        dep,
        zero,
        ">=",
        temperature=params.temperature,
        differentiable=params.differentiable,
    )
    keep = 1 - mask_remove
    # Cast per carried array so the lax.scan carry dtype is stable (see CLAUDE.md dtype rules)
    keep_dep = keep.astype(dep.dtype)
    updated_link_slot_departure_array = dep * keep_dep  # Set to zero where mask is one
    if params.relative_arrival_times:
        mask_subtract = differentiable_compare(
            updated_link_slot_departure_array,
            zero,
            ">",
            temperature=params.temperature,
            differentiable=params.differentiable,
        ).astype(dep.dtype)
        updated_link_slot_departure_array = (
            updated_link_slot_departure_array
            - jnp.squeeze(current_time).astype(dep.dtype) * mask_subtract
        )
    keep_i = keep.astype(state.path_index_array.dtype)
    mask_remove_i = mask_remove.astype(state.path_index_array.dtype)
    neg_one_i = jnp.array(-1, dtype=state.path_index_array.dtype)
    # Freed slots return to the 1e6 "empty" capacity sentinel (matching
    # init_link_capacity_array); leaving the stale reduced capacity permanently masked
    # them at their old value in mask_slots_rwalr
    cap = state.link_capacity_array
    keep_cap = keep.astype(cap.dtype)
    empty_capacity = jnp.asarray(1e6, dtype=cap.dtype)
    state = state.replace(
        link_slot_array=state.link_slot_array * keep.astype(state.link_slot_array.dtype),
        path_index_array=state.path_index_array * keep_i + neg_one_i * mask_remove_i,
        link_slot_departure_array=updated_link_slot_departure_array,
        link_capacity_array=cap * keep_cap + empty_capacity * mask_remove.astype(cap.dtype),
    )
    return state

required_slots(bitrate, se, channel_width, guardband=1, temperature=1.0, differentiable=True)

Calculate required slots for a given bitrate and spectral efficiency.

Parameters:

Name Type Description Default
bit_rate float

Bit rate in Gbps

required
se float

Spectral efficiency in bps/Hz

required
channel_width float

Channel width in GHz

required
guardband int

Guard band. Defaults to 1.

1
temperature float

Temperature for differentiable approximation. Defaults to 1.0.

1.0
differentiable bool

If False, use non-differentiable operations. Defaults to True.

True

Returns:

Name Type Description
int int

Required slots

Source code in xlron/environments/env_funcs.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
@partial(jax.jit, static_argnums=(2, 3, 4, 5))
def required_slots(
    bitrate: float,
    se: int,
    channel_width: float,
    guardband: int = 1,
    temperature: float = 1.0,
    differentiable: bool = True,
) -> int:
    """Calculate required slots for a given bitrate and spectral efficiency.

    Args:
        bit_rate (float): Bit rate in Gbps
        se (float): Spectral efficiency in bps/Hz
        channel_width (float): Channel width in GHz
        guardband (int, optional): Guard band. Defaults to 1.
        temperature (float, optional): Temperature for differentiable approximation. Defaults to 1.0.
        differentiable (bool, optional): If False, use non-differentiable operations. Defaults to True.

    Returns:
        int: Required slots
    """
    # Apply differentiable ceiling
    base_calculation = bitrate / (se * channel_width) + guardband
    slots = differentiable_ceil(
        base_calculation, temperature=temperature, differentiable=differentiable
    )
    # Differentiable version of equality comparison bitrate == 0
    is_zero = differentiable_compare(
        bitrate, zero, "==", temperature=temperature, differentiable=differentiable
    )  # High temperature for sharper transition
    # Differentiable version of the conditional zeroing (if bitrate is zero, then required slots should be zero)
    result = slots * (one - is_zero)
    return jnp.squeeze(result).astype(dtype_config.SMALL_INT_DTYPE)

set_band_gaps(link_slot_array, params, val)

Set band gaps in link slot array Args: link_slot_array (Array): Link slot array params (RSAGNModelEnvParams): Environment parameters val (int): Value to set Returns: Array: Link slot array with band gaps

Source code in xlron/environments/env_funcs.py
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
@partial(jax.jit, static_argnums=(2,))
def set_band_gaps(link_slot_array: Array, params: RSAGNModelEnvParams, val: int) -> Array:
    """Set band gaps in link slot array
    Args:
        link_slot_array (Array): Link slot array
        params (RSAGNModelEnvParams): Environment parameters
        val (int): Value to set
    Returns:
        Array: Link slot array with band gaps
    """
    # Create array that is size of link_slot array with values of column index
    mask = jnp.arange(params.link_resources)
    mask = jnp.tile(mask, (params.num_links, 1))

    num_gaps = params.gap_widths.shape[0]
    if num_gaps > 0:

        def set_band_gap(i, arr):
            gap_start = params.gap_starts[i]
            gap_end = gap_start + params.gap_widths[i]
            condition = jnp.logical_and(arr >= gap_start, arr < gap_end)
            arr = jnp.where(condition, -one, arr)
            return arr

        mask = jax.lax.fori_loop(0, num_gaps, set_band_gap, mask)
        # Cast the sentinel to the occupancy dtype: a Python float `val` would promote the
        # int8 occupancy array to float32 (weak-type promotion), breaking the carried dtype
        link_slot_array = jnp.where(
            mask == -one, jnp.asarray(val, dtype=link_slot_array.dtype), link_slot_array
        )
    return link_slot_array

signal_slot_count(num_slots, params)

Signal slots of a channel occupying num_slots slots including its guard band.

Source code in xlron/environments/env_funcs.py
4087
4088
4089
def signal_slot_count(num_slots: Array, params: RSAGNModelEnvParams) -> Array:
    """Signal slots of a channel occupying num_slots slots including its guard band."""
    return jnp.maximum(jnp.asarray(num_slots, dtype=dtype_config.INDEX_DTYPE) - params.guardband, 1)

update_active_lightpaths_array(state, path_index, initial_slot_index, num_slots)

Update active lightpaths array with new path index. Find the first index of the array with value -1 and replace with path index. Args: state (RSAGNModelEnvState): Environment state path_index (int): Path index to add to active lightpaths array Returns: jnp.array: Updated active lightpaths array

Source code in xlron/environments/env_funcs.py
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
def update_active_lightpaths_array(
    state: RSAGNModelEnvState, path_index: int, initial_slot_index: int, num_slots: int
) -> Array:
    """Update active lightpaths array with new path index.
    Find the first index of the array with value -1 and replace with path index.
    Args:
        state (RSAGNModelEnvState): Environment state
        path_index (int): Path index to add to active lightpaths array
    Returns:
        jnp.array: Updated active lightpaths array
    """
    first_empty_index = jnp.argmin(
        state.active_lightpaths_array[:, 0]
    )  # Just look at the first column
    return jax.lax.dynamic_update_slice(
        state.active_lightpaths_array,
        jnp.array(
            [[path_index, initial_slot_index, num_slots]], dtype=state.active_lightpaths_array.dtype
        ),
        (first_empty_index, 0),
    )

update_active_lightpaths_array_departure(state, time)

Write the departure time into the registry row chosen by update_active_lightpaths_array. Args: state (RSAGNModelEnvState): Environment state time (float): Departure time (negative = pending marker, see init docstring) Returns: jnp.array: Updated departure array

Source code in xlron/environments/env_funcs.py
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
def update_active_lightpaths_array_departure(state: RSAGNModelEnvState, time: float) -> Array:
    """Write the departure time into the registry row chosen by update_active_lightpaths_array.
    Args:
        state (RSAGNModelEnvState): Environment state
        time (float): Departure time (negative = pending marker, see init docstring)
    Returns:
        jnp.array: Updated departure array
    """
    first_empty_index = jnp.argmin(
        state.active_lightpaths_array[:, 0]
    )  # Just look at the first column
    dep = state.active_lightpaths_array_departure
    # (1, 3) row update: time arrives with shape () or (1,); jnp.stack((t, t, t)) of a (1,)
    # input is (3, 1) and used to smear the write down column 0 of three rows.
    row = jnp.broadcast_to(jnp.reshape(time, (1, 1)), (1, 3)).astype(dep.dtype)
    return jax.lax.dynamic_update_slice(dep, row, (first_empty_index, 0))

update_graph_tuple(state, params)

Update graph tuple for use with Jraph GNNs.

Edge and node features are updated from link_slot_array and node_capacity_array respectively. Global features are updated as request_array.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
state EnvState

Environment state with updated graph tuple

Source code in xlron/environments/env_funcs.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def update_graph_tuple(state: RSAEnvState, params: RSAEnvParams) -> RSAEnvState:
    """Update graph tuple for use with Jraph GNNs.

    Edge and node features are updated from link_slot_array and node_capacity_array respectively.
    Global features are updated as request_array.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        state (EnvState): Environment state with updated graph tuple
    """
    # Get source and dest from request array
    # VONE has 2D request_array (2, max_edges*2+1), use first row for node info
    # (same convention as init_graph_tuple)
    request_array = state.request_array
    if request_array.ndim == 2:
        request_array = request_array[0]
    source_dest, datarate = read_rsa_request(request_array)
    source, dest = source_dest[0], source_dest[2]
    # Current request as global feature
    globals = jnp.array(
        [datarate / jnp.max(params.values_bw)], dtype=dtype_config.LARGE_FLOAT_DTYPE
    )
    # One-hot encode source and destination
    source_dest_features = jnp.zeros((params.num_nodes, 2), dtype=dtype_config.LARGE_FLOAT_DTYPE)
    # Convert indices to int32 for indexing...
    source_idx = source.astype(dtype_config.LARGE_INT_DTYPE)
    dest_idx = dest.astype(dtype_config.LARGE_INT_DTYPE)
    # ...but maintain grads in value with differentiable index updates
    source_dest_features = differentiable_one_hot_index_update(
        source_dest_features, source_idx, 1.0, params.temperature, params.differentiable
    )
    source_dest_features = differentiable_one_hot_index_update(
        source_dest_features, dest_idx, -1.0, params.temperature, params.differentiable
    )
    spectral_features = state.graph.nodes[..., : params.num_spectral_features]
    holding_time_edge_features = state.link_slot_departure_array / state.mean_service_holding_time

    if params.__class__.__name__ in ["RSAGNModelEnvParams", "RMSAGNModelEnvParams"]:
        # Normalize by max parameters (converted to linear units)
        gn_state = cast(GNModelEnvState, state)
        gn_params = cast(GNModelEnvParams, params)
        max_power = isrs_gn_model.from_dbm(gn_params.max_power)
        # Use differentiable rounding
        normalized_power = differentiable_round(
            gn_state.channel_power_array / max_power,
            decimals=3,
            temperature=params.temperature,
            differentiable=params.differentiable,
        )

        max_snr = isrs_gn_model.from_db(gn_params.max_snr)
        # Use differentiable rounding
        normalized_snr = differentiable_round(
            gn_state.link_snr_array / max_snr,
            decimals=3,
            temperature=params.temperature,
            differentiable=params.differentiable,
        )

        edge_features = jnp.stack([normalized_snr, normalized_power], axis=-1)
        node_features = jnp.concatenate([spectral_features, source_dest_features], axis=-1)
    elif params.__class__.__name__ == "VONEEnvParams":
        edge_features = (
            # Cast occupancy (int8 tier) to float: graph features feed the NN embedders and
            # must match the holding-time branch / init-vs-update carry dtype
            state.link_slot_array.astype(dtype_config.SMALL_FLOAT_DTYPE)
            if params.incremental_loading
            else holding_time_edge_features
        )
        node_features = getattr(state, "node_capacity_array", jnp.zeros(params.num_nodes))
        node_features = node_features.reshape(-1, 1)
        # VONE carries [capacity(1) | spectral | source-dest(2)] node features, so the
        # static spectral columns sit at offset 1 (the generic slice above would grab the
        # capacity column and drop the last spectral eigenvector).
        vone_spectral_features = state.graph.nodes[..., 1 : 1 + params.num_spectral_features]
        # Match the env's init_graph_tuple(..., exclude_source_dest=True) convention:
        # VONE's request row 0 holds node-capacity request values, not node indices, so
        # the generic one-hot source_dest_features above would encode capacities as node
        # positions. Keep the two source-dest columns zeroed instead. (VONEEnv currently
        # rebuilds the graph via init_graph_tuple each step; this keeps a direct call
        # consistent with that path.)
        vone_source_dest_features = jnp.zeros_like(source_dest_features)
        node_features = jnp.concatenate(
            [node_features, vone_spectral_features, vone_source_dest_features], axis=-1
        )
    else:
        edge_features = (
            # Cast occupancy (int8 tier) to float: graph features feed the NN embedders and
            # must match the holding-time branch / init-vs-update carry dtype
            state.link_slot_array.astype(dtype_config.SMALL_FLOAT_DTYPE)
            if params.incremental_loading
            else holding_time_edge_features
        )
        node_features = jnp.concatenate([spectral_features, source_dest_features], axis=-1)

    if params.disable_node_features:
        # Match init_graph_tuple: (num_nodes, 1) zeros so the carried graph.nodes shape is
        # stable across the scan and rank-1 rows reach the width-1 node embedder.
        node_features = jnp.zeros((params.num_nodes, 1), dtype=dtype_config.LARGE_FLOAT_DTYPE)

    # Block-duplicate to match the [fwd..., bwd...] senders/receivers layout (see init_graph_tuple)
    edge_features = (
        edge_features
        if params.directed_graph
        else jnp.concatenate([edge_features, edge_features], axis=0)
    )
    # Match init_graph_tuple: store GNN input features at SMALL_FLOAT so the carried graph dtype
    # is stable across the scan (the model boundary casts them back up to COMPUTE_DTYPE).
    node_features = node_features.astype(dtype_config.SMALL_FLOAT_DTYPE)
    edge_features = edge_features.astype(dtype_config.SMALL_FLOAT_DTYPE)
    graph = state.graph._replace(nodes=node_features, edges=edge_features, globals=globals)
    state = state.replace(graph=graph)
    return state

uses_pallas_kernels(params)

True when a GN environment selects the Pallas kernels (--gn_kernel_backend).

Source code in xlron/environments/env_funcs.py
4393
4394
4395
def uses_pallas_kernels(params) -> bool:
    """True when a GN environment selects the Pallas kernels (--gn_kernel_backend)."""
    return getattr(params, "gn_kernel_backend", "jax") == "pallas"

Training Utilities

LossDiagnostics

Bases: NamedTuple

Per-step diagnostics emitted from the PPO loss when ENHANCED_LOGGING is on.

Auto-registered as a JAX pytree, so it stacks field-wise inside scan/vmap. Add a field here and it flows through to the wandb registry below and to the dict built in _update_step.

Source code in xlron/train/train_utils.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
class LossDiagnostics(NamedTuple):
    """Per-step diagnostics emitted from the PPO loss when ENHANCED_LOGGING is on.

    Auto-registered as a JAX pytree, so it stacks field-wise inside scan/vmap.
    Add a field here and it flows through to the wandb registry below and to
    the dict built in `_update_step`.
    """

    valid_frac: Array
    clip_frac: Array
    ratio_mean: Array
    ratio_std: Array
    ratio_min: Array
    ratio_max: Array
    valid_mass_mean: Array
    valid_mass_std: Array
    valid_mass_min: Array
    valid_mass_max: Array
    current_log_valid_mass_mean: Array
    current_valid_mass_below_floor_frac: Array
    n_valid_mean: Array
    n_valid_min: Array
    n_valid_max: Array
    adv_mean_raw: Array
    adv_std_raw: Array
    gate_frac: Array
    log_prob_choice: Array
    entropy_choice: Array
    log_prob_min: Array
    invalid_taken_frac: Array
    taken_valid_min: Array
    recenter_ratio_mean: Array
    recenter_ratio_std: Array
    neg_adv_clip_frac: Array
    frac_pos_adv: Array
    mu_low_frac: Array
    mu_high_frac: Array
    mu_high_w_frac: Array

    @classmethod
    def zeros(cls) -> "LossDiagnostics":
        z = jnp.array(0.0)
        return cls(*([z] * len(cls._fields)))

TrainState

Bases: Module

Train state for Equinox models.

The model is stored but marked as non-pytree so JAX doesn't try to trace it.

Source code in xlron/train/train_utils.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
273
class TrainState(eqx.Module):
    """Train state for Equinox models.

    The model is stored but marked as non-pytree so JAX doesn't try to trace it.
    """

    step: Array
    model_params: eqx.Module
    model_static: eqx.Module = eqx.field(static=True)  # Mark as static/non-pytree
    tx: optax.GradientTransformation = eqx.field(static=True)
    opt_state: optax.OptState
    lr_schedule: Schedule = eqx.field(static=True)
    ent_schedule: Schedule = eqx.field(static=True)
    vml_schedule: Schedule = eqx.field(static=True)
    avg_reward: Array
    reward_stepsize: Array
    reward_stepsize_init: Array
    reward_stepsize_offset: Array
    prio_alpha: Array
    prio_beta0: Array
    prio_beta: Array

    def apply_gradients(self, grads: Any) -> "TrainState":
        """Updates model parameters and opt_state."""
        model = eqx.combine(self.model_params, self.model_static)
        updates, new_opt_state = self.tx.update(grads, self.opt_state, self.model_params)
        new_model = eqx.apply_updates(model, updates)
        new_model_params, new_model_static = eqx.partition(new_model, eqx.is_inexact_array)
        # Can't use eqx.tree_at for static fields, create new instance
        return TrainState(
            step=self.step,
            model_params=new_model_params,
            model_static=new_model_static,
            tx=self.tx,
            opt_state=new_opt_state,
            lr_schedule=self.lr_schedule,
            ent_schedule=self.ent_schedule,
            vml_schedule=self.vml_schedule,
            avg_reward=self.avg_reward,
            reward_stepsize=self.reward_stepsize,
            reward_stepsize_init=self.reward_stepsize_init,
            reward_stepsize_offset=self.reward_stepsize_offset,
            prio_alpha=self.prio_alpha,
            prio_beta0=self.prio_beta0,
            prio_beta=self.prio_beta,
        )

    def update_step_size(self) -> "TrainState":
        """Updates the step size used for reward centering."""
        reward_stepsize_offset = self.reward_stepsize_offset + self.reward_stepsize_init * (
            1 - self.reward_stepsize_offset
        )
        reward_stepsize = self.reward_stepsize_init / reward_stepsize_offset
        return eqx.tree_at(
            lambda state: (state.reward_stepsize, state.reward_stepsize_offset),
            self,
            (reward_stepsize, reward_stepsize_offset),
        )

    @staticmethod
    def create(
        model: eqx.Module | None,
        tx: optax.GradientTransformation,
        lr_schedule: Schedule = lambda x: jnp.array(0.0),
        ent_schedule: Schedule = lambda x: jnp.array(0.0),
        vml_schedule: Schedule = lambda x: jnp.array(0.0),
        prio_alpha: float = 0.0,
        prio_beta0: float = 1.0,
        prio_beta: float = 1.0,
        reward_stepsize_init: float = 0.001,
        initial_avg_reward: float = 0.0,
    ) -> "TrainState":
        """Creates a new instance with step=0 and initialized opt_state."""
        opt_state = tx.init(eqx.filter(model, eqx.is_inexact_array))
        model_params, model_static = eqx.partition(model, eqx.is_inexact_array)
        return TrainState(
            step=jnp.array(0),
            model_params=model_params,
            model_static=model_static,
            tx=tx,
            opt_state=opt_state,
            lr_schedule=lr_schedule,
            ent_schedule=ent_schedule,
            vml_schedule=vml_schedule,
            avg_reward=jnp.array(initial_avg_reward, dtype=dtype_config.REWARD_DTYPE),
            reward_stepsize=jnp.array(reward_stepsize_init, dtype=dtype_config.REWARD_DTYPE),
            reward_stepsize_init=jnp.array(reward_stepsize_init, dtype=dtype_config.REWARD_DTYPE),
            reward_stepsize_offset=jnp.array(1.0, dtype=dtype_config.REWARD_DTYPE),
            prio_alpha=jnp.array(prio_alpha, dtype=dtype_config.REWARD_DTYPE),
            prio_beta0=jnp.array(prio_beta0, dtype=dtype_config.REWARD_DTYPE),
            prio_beta=jnp.array(prio_beta, dtype=dtype_config.REWARD_DTYPE),
        )

apply_gradients(grads)

Updates model parameters and opt_state.

Source code in xlron/train/train_utils.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def apply_gradients(self, grads: Any) -> "TrainState":
    """Updates model parameters and opt_state."""
    model = eqx.combine(self.model_params, self.model_static)
    updates, new_opt_state = self.tx.update(grads, self.opt_state, self.model_params)
    new_model = eqx.apply_updates(model, updates)
    new_model_params, new_model_static = eqx.partition(new_model, eqx.is_inexact_array)
    # Can't use eqx.tree_at for static fields, create new instance
    return TrainState(
        step=self.step,
        model_params=new_model_params,
        model_static=new_model_static,
        tx=self.tx,
        opt_state=new_opt_state,
        lr_schedule=self.lr_schedule,
        ent_schedule=self.ent_schedule,
        vml_schedule=self.vml_schedule,
        avg_reward=self.avg_reward,
        reward_stepsize=self.reward_stepsize,
        reward_stepsize_init=self.reward_stepsize_init,
        reward_stepsize_offset=self.reward_stepsize_offset,
        prio_alpha=self.prio_alpha,
        prio_beta0=self.prio_beta0,
        prio_beta=self.prio_beta,
    )

create(model, tx, lr_schedule=lambda x: jnp.array(0.0), ent_schedule=lambda x: jnp.array(0.0), vml_schedule=lambda x: jnp.array(0.0), prio_alpha=0.0, prio_beta0=1.0, prio_beta=1.0, reward_stepsize_init=0.001, initial_avg_reward=0.0) staticmethod

Creates a new instance with step=0 and initialized opt_state.

Source code in xlron/train/train_utils.py
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
273
@staticmethod
def create(
    model: eqx.Module | None,
    tx: optax.GradientTransformation,
    lr_schedule: Schedule = lambda x: jnp.array(0.0),
    ent_schedule: Schedule = lambda x: jnp.array(0.0),
    vml_schedule: Schedule = lambda x: jnp.array(0.0),
    prio_alpha: float = 0.0,
    prio_beta0: float = 1.0,
    prio_beta: float = 1.0,
    reward_stepsize_init: float = 0.001,
    initial_avg_reward: float = 0.0,
) -> "TrainState":
    """Creates a new instance with step=0 and initialized opt_state."""
    opt_state = tx.init(eqx.filter(model, eqx.is_inexact_array))
    model_params, model_static = eqx.partition(model, eqx.is_inexact_array)
    return TrainState(
        step=jnp.array(0),
        model_params=model_params,
        model_static=model_static,
        tx=tx,
        opt_state=opt_state,
        lr_schedule=lr_schedule,
        ent_schedule=ent_schedule,
        vml_schedule=vml_schedule,
        avg_reward=jnp.array(initial_avg_reward, dtype=dtype_config.REWARD_DTYPE),
        reward_stepsize=jnp.array(reward_stepsize_init, dtype=dtype_config.REWARD_DTYPE),
        reward_stepsize_init=jnp.array(reward_stepsize_init, dtype=dtype_config.REWARD_DTYPE),
        reward_stepsize_offset=jnp.array(1.0, dtype=dtype_config.REWARD_DTYPE),
        prio_alpha=jnp.array(prio_alpha, dtype=dtype_config.REWARD_DTYPE),
        prio_beta0=jnp.array(prio_beta0, dtype=dtype_config.REWARD_DTYPE),
        prio_beta=jnp.array(prio_beta, dtype=dtype_config.REWARD_DTYPE),
    )

update_step_size()

Updates the step size used for reward centering.

Source code in xlron/train/train_utils.py
229
230
231
232
233
234
235
236
237
238
239
def update_step_size(self) -> "TrainState":
    """Updates the step size used for reward centering."""
    reward_stepsize_offset = self.reward_stepsize_offset + self.reward_stepsize_init * (
        1 - self.reward_stepsize_offset
    )
    reward_stepsize = self.reward_stepsize_init / reward_stepsize_offset
    return eqx.tree_at(
        lambda state: (state.reward_stepsize, state.reward_stepsize_offset),
        self,
        (reward_stepsize, reward_stepsize_offset),
    )

build_run_summary(run_type, config, metrics_dict, timing=None)

Build a standardized run summary dictionary.

Parameters:

Name Type Description Default
run_type str

One of "rl_training", "heuristic_eval", "model_eval", "cutset_bound", "reconfigurable_routing_bound".

required
config dict

Dict of user-specified flags (from get_user_flags).

required
metrics_dict Dict[str, Dict[str, float]]

{metric_name: {"mean": ..., "std": ..., "iqr_lower": ..., "iqr_upper": ...}}.

required
timing Dict[str, Any] | None

Optional dict with "compilation_time_s", "execution_time_s", "fps".

None

Returns:

Type Description
dict

A dictionary ready for json.dumps serialization.

Source code in xlron/train/train_utils.py
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
def build_run_summary(
    run_type: str,
    config: dict,
    metrics_dict: Dict[str, Dict[str, float]],
    timing: Dict[str, Any] | None = None,
) -> dict:
    """Build a standardized run summary dictionary.

    Args:
        run_type: One of "rl_training", "heuristic_eval", "model_eval",
                  "cutset_bound", "reconfigurable_routing_bound".
        config: Dict of user-specified flags (from get_user_flags).
        metrics_dict: {metric_name: {"mean": ..., "std": ..., "iqr_lower": ..., "iqr_upper": ...}}.
        timing: Optional dict with "compilation_time_s", "execution_time_s", "fps".

    Returns:
        A dictionary ready for json.dumps serialization.
    """
    # Convert all config values to JSON-safe types
    safe_config = {}
    for k, v in config.items():
        try:
            json.dumps(v)
            safe_config[k] = v
        except (TypeError, ValueError):
            safe_config[k] = str(v)

    # Convert all metric values to plain Python floats
    safe_metrics = {}
    for metric_name, stats in metrics_dict.items():
        safe_metrics[metric_name] = {
            stat_name: _to_python(stat_val) for stat_name, stat_val in stats.items()
        }

    summary = {
        "run_type": run_type,
        "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "config": safe_config,
        "metrics": safe_metrics,
    }

    if timing:
        summary["timing"] = {k: _to_python(v) for k, v in timing.items()}

    return summary

cast_model_for_compute(model)

Cast a model's float (inexact) leaves to COMPUTE_DTYPE for the forward pass.

Mixed-precision training: the master weights stay at PARAMS_DTYPE (float32) in the TrainState and optimizer, and are cast to COMPUTE_DTYPE (e.g. bfloat16) only for the forward pass. Because the cast sits inside the differentiated region (it is applied to the model that _loss_fn is differentiated through), gradients flow back through it to the float32 master copy, so the optimizer keeps updating float32 weights. No-op when COMPUTE_DTYPE == PARAMS_DTYPE (the default), which avoids an unnecessary copy.

Source code in xlron/train/train_utils.py
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
def cast_model_for_compute(model: eqx.Module) -> eqx.Module:
    """Cast a model's float (inexact) leaves to COMPUTE_DTYPE for the forward pass.

    Mixed-precision *training*: the master weights stay at PARAMS_DTYPE (float32) in the
    TrainState and optimizer, and are cast to COMPUTE_DTYPE (e.g. bfloat16) only for the forward
    pass. Because the cast sits inside the differentiated region (it is applied to the model that
    `_loss_fn` is differentiated through), gradients flow back through it to the float32 master
    copy, so the optimizer keeps updating float32 weights. No-op when COMPUTE_DTYPE ==
    PARAMS_DTYPE (the default), which avoids an unnecessary copy.
    """
    if jnp.dtype(dtype_config.COMPUTE_DTYPE) == jnp.dtype(dtype_config.PARAMS_DTYPE):
        return model
    return jax.tree_util.tree_map(
        lambda x: x.astype(dtype_config.COMPUTE_DTYPE) if eqx.is_inexact_array(x) else x,
        model,
    )

count_parameters(params)

Counts the number of parameters in a parameter tree.

Source code in xlron/train/train_utils.py
281
282
283
def count_parameters(params: ArrayTree) -> int:
    """Counts the number of parameters in a parameter tree."""
    return sum(x.size for x in jax.tree_util.tree_leaves(params))

get_sweep_rewarm_fn(env, env_params, config)

Build a jitted re-equilibration function for load sweeps.

A load sweep reuses the compiled experiment across loads, but the network state (link occupancy, departure times) in the base experiment_input was warmed up at the original --load. Starting every swept load from that state biases per-load steady-state metrics: low loads inherit an over-full network (blocking overestimated), high loads an under-full one (underestimated). The returned function re-runs the ENV_WARMUP_STEPS warmup at the state's (already updated) arrival rate, then zeroes the warmup metric counters so each swept load's metrics exclude the re-equilibration transient. Build it once outside the load loop: arrival_rate is a dynamic state leaf, so the single compilation is reused across all loads (preserving the sweep's compile-once behaviour).

Parameters:

Name Type Description Default
env

Environment (same one the experiment was compiled with)

required
env_params

Environment parameters

required
config

Config Box (reads ENV_WARMUP_STEPS, NUM_ENVS, NUM_LEARNERS, ...)

required

Returns:

Type Description
Callable[[Tuple, PRNGKey], Tuple]

Jitted function (experiment_input, warmup_key) -> experiment_input, where

Callable[[Tuple, PRNGKey], Tuple]

experiment_input is (runner_state, env_state, obsv, rng_step, rng_epoch).

Callable[[Tuple, PRNGKey], Tuple]

With NUM_LEARNERS > 1 the function is vmapped over the leading learner axis

Callable[[Tuple, PRNGKey], Tuple]

and warmup_key must be a batch of NUM_LEARNERS keys.

Source code in xlron/train/train_utils.py
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
def get_sweep_rewarm_fn(env, env_params, config) -> Callable[[Tuple, chex.PRNGKey], Tuple]:
    """Build a jitted re-equilibration function for load sweeps.

    A load sweep reuses the compiled experiment across loads, but the network state
    (link occupancy, departure times) in the base experiment_input was warmed up at
    the original ``--load``. Starting every swept load from that state biases per-load
    steady-state metrics: low loads inherit an over-full network (blocking
    overestimated), high loads an under-full one (underestimated). The returned
    function re-runs the ``ENV_WARMUP_STEPS`` warmup at the state's (already updated)
    arrival rate, then zeroes the warmup metric counters so each swept load's metrics
    exclude the re-equilibration transient. Build it once outside the load loop:
    ``arrival_rate`` is a dynamic state leaf, so the single compilation is reused
    across all loads (preserving the sweep's compile-once behaviour).

    Args:
        env: Environment (same one the experiment was compiled with)
        env_params: Environment parameters
        config: Config Box (reads ENV_WARMUP_STEPS, NUM_ENVS, NUM_LEARNERS, ...)

    Returns:
        Jitted function (experiment_input, warmup_key) -> experiment_input, where
        experiment_input is (runner_state, env_state, obsv, rng_step, rng_epoch).
        With NUM_LEARNERS > 1 the function is vmapped over the leading learner axis
        and warmup_key must be a batch of NUM_LEARNERS keys.
    """

    def rewarm_fn(experiment_input: Tuple, warmup_key: chex.PRNGKey) -> Tuple:
        runner_state, env_state, obsv, rng_step, rng_epoch = experiment_input
        warmup_key = (
            jax.random.split(warmup_key, config.NUM_ENVS) if config.NUM_ENVS > 1 else warmup_key
        )
        warmup_state = (warmup_key, env_state, obsv)
        warmup_fn = get_warmup_fn(warmup_state, env, env_params, runner_state, config)
        warmup_fn = jax.vmap(warmup_fn) if config.NUM_ENVS > 1 else warmup_fn
        env_state, obsv = warmup_fn(warmup_state)
        env_state = reset_warmup_metric_counters(env_state)
        return (runner_state, env_state, obsv, rng_step, rng_epoch)

    if config.NUM_LEARNERS > 1:
        rewarm_fn = jax.vmap(rewarm_fn)
    return jax.jit(rewarm_fn)

get_user_flags(flags)

Extract only explicitly-set (non-default) flags from absl FlagValues.

Parameters:

Name Type Description Default
flags

absl.flags.FlagValues instance.

required

Returns:

Type Description
dict

Dict of {flag_name: value} for flags that were set on the command line.

Source code in xlron/train/train_utils.py
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
def get_user_flags(flags) -> dict:
    """Extract only explicitly-set (non-default) flags from absl FlagValues.

    Args:
        flags: absl.flags.FlagValues instance.

    Returns:
        Dict of {flag_name: value} for flags that were set on the command line.
    """
    # Filter out absl internal flags (v, verbosity, etc.)
    _ABSL_INTERNAL = {
        "v",
        "verbosity",
        "logger_levels",
        "stderrthreshold",
        "showprefixforinfo",
        "run_with_pdb",
        "pdb_post_mortem",
        "run_with_profiling",
        "profile_file",
        "use_cprofile_for_profiling",
        "only_check_args",
        "?",
        "help",
        "helpshort",
        "helpfull",
        "helpxml",
        "flagfile",
        "undefok",
        "logtostderr",
        "alsologtostderr",
        "log_dir",
    }
    result = {}
    for name in flags:
        if flags[name].using_default_value or name in _ABSL_INTERNAL:
            continue
        val = flags[name].value
        # Fix list flags that received a stringified Python list like "['0.35', '0.35']"
        # absl DEFINE_list splits on commas producing fragments like ["['0.35'", " '0.35']"]
        if isinstance(val, list) and val:
            joined = ",".join(str(x) for x in val)
            if "[" in joined or "'" in joined or '"' in joined:
                cleaned = joined.replace("[", "").replace("]", "").replace("'", "").replace('"', "")
                val = [p.strip() for p in cleaned.split(",") if p.strip()]
        result[name] = val
    return result

get_warmup_fn(warmup_state, env, params, train_state, config)

Warmup period to fill the network before training or eval.

The action selection method is controlled by config.warmup_action_type: - None : use the default for the current run mode (RL policy or heuristic) - "heuristic" : always use the heuristic specified by --path_heuristic - "random" : sample uniformly from valid (masked) actions

Source code in xlron/train/train_utils.py
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
def get_warmup_fn(warmup_state, env, params, train_state, config) -> Callable[[Tuple], Tuple]:
    """Warmup period to fill the network before training or eval.

    The action selection method is controlled by ``config.warmup_action_type``:
      - None  : use the default for the current run mode (RL policy or heuristic)
      - "heuristic" : always use the heuristic specified by ``--path_heuristic``
      - "random"    : sample uniformly from valid (masked) actions
    """
    warmup_action_type = getattr(config, "warmup_action_type", None)
    if warmup_action_type is not None and warmup_action_type not in ("heuristic", "random"):
        raise ValueError(
            f"warmup_action_type must be None, 'heuristic', or 'random', got '{warmup_action_type}'"
        )
    use_heuristic_warmup = config.EVAL_HEURISTIC or warmup_action_type == "heuristic"
    use_random_warmup = warmup_action_type == "random"
    # select_action_eval dispatches to the heuristics on config.EVAL_HEURISTIC, so when
    # heuristic warmup is requested during RL training we pass it a copy of the config
    # with EVAL_HEURISTIC set. GN-model runs with RL launch power are exempt: their
    # warmup path action is overwritten by the ksp_ff/ksp_lf override below, and
    # select_action_eval rejects EVAL_HEURISTIC combined with launch_power_type='rl'.
    warmup_config = config
    if (
        use_heuristic_warmup
        and not config.EVAL_HEURISTIC
        and not ("gn_model" in config.env_type.lower() and config.launch_power_type == "rl")
    ):
        if config.get("aggregate_slots", 1) > 1:
            raise ValueError(
                "warmup_action_type='heuristic' is not supported with aggregate_slots > 1: "
                "heuristics emit full-resolution actions but the env decodes aggregated ones"
            )
        warmup_config = Box(config)
        warmup_config.EVAL_HEURISTIC = True
    if use_heuristic_warmup and config.get("warmup_path_heuristic"):
        warmup_config = Box(warmup_config)
        warmup_config.path_heuristic = config.warmup_path_heuristic

    def warmup_fn(warmup_state, runtime_train_state=None) -> Tuple[EnvState, Array]:
        rng, state, last_obs = warmup_state

        def warmup_step(i, val) -> Tuple:
            _rng, _state, _params, _train_state, _last_obs = val
            # SELECT ACTION
            _rng, action_key, step_key = jax.random.split(_rng, 3)

            if use_random_warmup:
                # Random valid action: sample uniformly from the action mask
                mask_result = env.action_mask(_state.env_state, _params)
                action_mask = mask_result[0]
                action = jax.random.categorical(action_key, jnp.log(jnp.maximum(action_mask, 1e-8)))
            else:
                # Pass the dedicated action_key, not the loop-carry _rng (which is re-split
                # next iteration and must never also be consumed for sampling).
                select_action_state = (action_key, _state, _last_obs)
                if use_heuristic_warmup:
                    _state, action, log_prob, value = select_action_eval(
                        select_action_state, env, _params, _train_state, warmup_config
                    )
                else:
                    _state, action, log_prob, value = select_action(
                        select_action_state, env, _params, _train_state, config
                    )
            if "gn_model" in config.env_type.lower() and config.launch_power_type == "rl":
                # If the action is launch power, the action is this shape:
                # jnp.concatenate([path_action.reshape((1,)), power_action.reshape((1,))], axis=0)
                # We want to overwrite the launch power with a default launch_power
                path_action = (
                    ksp_lf(_state.env_state, _params)
                    if _params.last_fit is True
                    else ksp_ff(_state.env_state, _params)
                )
                action = jnp.concatenate(
                    [
                        path_action.reshape((1,)),
                        jnp.array(
                            [
                                params.default_launch_power,
                            ]
                        ),
                    ],
                    axis=0,
                )
            # With fixed/tabular launch power, both MLP and graph policies emit
            # path actions. GN envs supply the configured power in process_action.
            # STEP ENV
            obsv, _state, reward, terminal, truncated, info = env.step(
                step_key, _state, action, params
            )
            # Keyed on the OUTER config's EVAL_HEURISTIC (not warmup_config's): during RL
            # training with warmup_action_type='heuristic' the returned obs seeds the RL
            # rollout carry, so it must stay a real observation there.
            if config.USE_GNN or config.USE_TRANSFORMER:
                obsv = (_state.env_state,)
            elif config.EVAL_HEURISTIC:
                # Match the placeholder carry from experiment_data_setup: heuristic
                # eval never reads the obs (see heuristic_eval_obs_placeholder)
                obsv = heuristic_eval_obs_placeholder()
            else:
                obsv = tuple([obsv])
            return _rng, _state, _params, _train_state, obsv

        vals = jax.lax.fori_loop(
            0,
            config.ENV_WARMUP_STEPS,
            warmup_step,
            (
                rng,
                state,
                params,
                train_state if runtime_train_state is None else runtime_train_state,
                last_obs,
            ),
        )

        return vals[1], vals[4]

    return warmup_fn

heuristic_eval_obs_placeholder(num_envs=1)

Shape-(1,) placeholder observation for pure-heuristic eval.

Heuristic action selection (select_action_eval with config.EVAL_HEURISTIC) reads only env_state, never the observation, yet the obs rides every scan/fori_loop carry. Building the real flattened observation (request_array + link_slot_array concat, ~4.4k elements on NSFNET 100-FSU) each step is dead work that cannot be eliminated while the obs is threaded through the carry. Substituting this placeholder makes env.step's returned obs unused, so the whole get_obs build is dead-code-eliminated from the compiled step. Not applied for GNN/Transformer policies (their obs is (env_state, params)) nor for EVAL_MODEL or RL training, where the model consumes the observation.

Every site that threads the heuristic-eval obs carry must use this same placeholder (experiment_data_setup, get_warmup_fn's loop body, eval_heuristic's step body) so the carry structure stays consistent across init, warmup, re-warm (load sweeps) and eval.

Source code in xlron/train/train_utils.py
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
def heuristic_eval_obs_placeholder(num_envs: int = 1) -> Tuple[Array, ...]:
    """Shape-(1,) placeholder observation for pure-heuristic eval.

    Heuristic action selection (select_action_eval with config.EVAL_HEURISTIC) reads only
    env_state, never the observation, yet the obs rides every scan/fori_loop carry. Building
    the real flattened observation (request_array + link_slot_array concat, ~4.4k elements on
    NSFNET 100-FSU) each step is dead work that cannot be eliminated while the obs is threaded
    through the carry. Substituting this placeholder makes env.step's returned obs unused, so
    the whole get_obs build is dead-code-eliminated from the compiled step. Not applied for
    GNN/Transformer policies (their obs is (env_state, params)) nor for EVAL_MODEL or RL
    training, where the model consumes the observation.

    Every site that threads the heuristic-eval obs carry must use this same placeholder
    (experiment_data_setup, get_warmup_fn's loop body, eval_heuristic's step body) so the
    carry structure stays consistent across init, warmup, re-warm (load sweeps) and eval.
    """
    shape = (num_envs, 1) if num_envs > 1 else (1,)
    return (jnp.zeros(shape, dtype=jnp.float32),)

load_warmup_cache(path, template)

Restore save_warmup_cache's result into template's structure, shapes and dtypes.

Source code in xlron/train/train_utils.py
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
def load_warmup_cache(path: pathlib.Path, template):
    """Restore save_warmup_cache's result into template's structure, shapes and dtypes."""
    leaves, treedef = jax.tree.flatten(template)
    with np.load(path) as archive:
        restored = []
        for i, leaf in enumerate(leaves):
            value = archive[f"leaf_{i}"]
            if value.shape != jnp.shape(leaf) or value.dtype != jnp.asarray(leaf).dtype:
                raise ValueError(f"{path} does not match this run's warmup state (leaf {i})")
            restored.append(jnp.asarray(value))
        if len(archive.files) != len(leaves):
            raise ValueError(f"{path} does not match this run's warmup state")
    return jax.tree.unflatten(treedef, restored)

log_metrics(config, out, total_run_time, increment_run_time, merge_func, episode_count=0, update_count=0, step_count=0)

Log metrics to wandb and/or save episode end metrics to CSV.

Source code in xlron/train/train_utils.py
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
def log_metrics(
    config: Box,
    out: Dict[str, Dict[str, Array]],
    total_run_time: float,
    increment_run_time: float,
    merge_func: Callable,
    episode_count: int = 0,
    update_count: int = 0,
    step_count: int = 0,
) -> Tuple[Dict, Dict]:
    """Log metrics to wandb and/or save episode end metrics to CSV."""
    standalone_eval = config.get("EVAL_HEURISTIC", False) or config.get("EVAL_MODEL", False)
    prefix = "eval/" if standalone_eval else "train/"
    time_metric = "eval/time_s" if standalone_eval else "performance/time_s"

    with TimeIt("Processing metrics"):
        merged_out, merged_out_loss, processed_data, episode_ends = process_metrics(
            config, out, merge_func
        )

    # Utilisation/fragmentation are state properties computed once per increment
    # from the final link_slot_array (their per-step computation cost ~10-15% of
    # hot-path step time). Inject the end-of-increment values into every stat
    # slot so downstream consumers (summary print, wandb, CSV) see real values.
    try:
        env_state = out["runner_state"][1]
        inner = getattr(env_state, "env_state", env_state)
        lsa = inner.link_slot_array  # ty: ignore[unresolved-attribute]
        if lsa.ndim > 2:  # batched over envs (and possibly learners)
            flat = lsa.reshape((-1,) + lsa.shape[-2:])
            util = float(jnp.mean(jax.vmap(calculate_utilisation)(flat)))
            frag = float(jnp.mean(jax.vmap(calculate_fragmentation)(flat)))
        else:
            util = float(calculate_utilisation(lsa))
            frag = float(calculate_fragmentation(lsa))
        # Template stats entry: eval drops the (constant-zero) per-step
        # utilisation/fragmentation keys from the stacked info entirely
        # (eval_heuristic._pack_info), so the entries may be absent from
        # processed_data and need creating from an always-present metric's shape.
        template = processed_data.get("accepted_services") or next(iter(processed_data.values()))
        injected = [("utilisation", util), ("fragmentation", frag)]
        if "held_lightpaths" in merged_out:
            # Peak number of lightpaths held lit at once (any env, any step) in this
            # increment; block-averaged per-step logging would hide it.
            injected.append(
                ("held_lightpaths_peak", float(np.max(np.asarray(merged_out["held_lightpaths"]))))
            )
        for metric_name, value in injected:
            stats = processed_data.get(metric_name, template)
            if isinstance(stats, dict):
                processed_data[metric_name] = {
                    stat_key: np.full_like(np.asarray(arr, dtype=np.float64), value)
                    for stat_key, arr in stats.items()
                }
        # Keep metric ordering stable (summary-table rows, CSV columns) whether
        # the entries above were overwritten in place or newly created
        reordered = {k: processed_data[k] for k in metrics if k in processed_data}
        reordered.update({k: v for k, v in processed_data.items() if k not in metrics})
        processed_data = reordered
    except (KeyError, IndexError, AttributeError, TypeError, StopIteration):
        # Envs without link_slot_array (or unexpected runner-state layouts) keep
        # whatever process_metrics produced (e.g. VONE's per-step values).
        pass

    all_metrics = list(processed_data.keys())
    if not config.LOG_ALL_INFO:
        all_metrics = [
            "service_blocking_probability",
            "bitrate_blocking_probability",
            "accepted_services",
            "accepted_bitrate",
        ]
        # GN-model diagnostics, logged whenever the environment reports them.
        all_metrics += [
            name
            for name in (
                "spectrum_blocking_probability",
                "snr_blocking_probability",
                "power_blocking_probability",
                "held_lightpaths",
                "held_lightpaths_peak",
            )
            if name in processed_data
        ]

    with TimeIt("Logging metrics"):
        if config.get("EPISODE_DATA_OUTPUT_FILE"):
            print("Saving episode metrics to file")
            # Save episode end metrics to file
            episode_end_df = pd.DataFrame(
                {
                    f"{metric}_{stat}": processed_data[metric][stat]
                    for metric in all_metrics
                    for stat in [
                        "episode_end_mean",
                        "episode_end_std",
                        "episode_end_iqr_upper",
                        "episode_end_iqr_lower",
                    ]
                }
            )
            # Check if data output file exists
            write_headers = not os.path.exists(config.EPISODE_DATA_OUTPUT_FILE)
            episode_end_df.to_csv(
                config.EPISODE_DATA_OUTPUT_FILE, mode="a", header=write_headers, index=False
            )
            # Pickle merged_out for further analysis
            with open(config.EPISODE_DATA_OUTPUT_FILE.replace(".csv", ".pkl"), "wb") as f:
                pickle.dump(merged_out, f)

        if config.WANDB:
            print("Logging metrics to wandb")

            if not config.continuous_operation:
                # Log metrics from every step
                # Define the downsample factor to speed up upload to wandb
                # Then reshape the array and compute the mean
                training_time = (
                    jnp.arange(len(processed_data[all_metrics[0]]["episode_end_mean"]))
                    / len(processed_data[all_metrics[0]]["episode_end_mean"])
                    * increment_run_time
                ) + total_run_time
                # Log episode end metrics
                print(f"Logging episode end metrics for {np.sum(episode_ends)} episodes")
                for i in range(len(processed_data[all_metrics[0]]["episode_end_mean"])):
                    log_dict = {
                        (
                            f"eval/{metric}_{stat.removeprefix('episode_end_')}"
                            if standalone_eval
                            else f"train/{metric}_{stat}"
                        ): processed_data[metric][stat][i]
                        for metric in all_metrics
                        for stat in [
                            "episode_end_mean",
                            "episode_end_std",
                            "episode_end_iqr_upper",
                            "episode_end_iqr_lower",
                        ]
                    }
                    log_dict[time_metric] = training_time[i]
                    log_dict["episode_count"] = i + episode_count
                    wandb.log(log_dict)

            else:
                # Log metrics from every step
                # Define the downsample factor to speed up upload to wandb
                # Then reshape the array and compute the mean
                training_time = (
                    jnp.arange(len(processed_data[all_metrics[0]]["mean"]))
                    / len(processed_data[all_metrics[0]]["mean"])
                    * increment_run_time
                ) + total_run_time

                chop = len(processed_data[all_metrics[0]]["mean"]) % config.DOWNSAMPLE_FACTOR

                def downsample_mean(x: Array) -> Array:
                    x = jnp.asarray(x)
                    return x[chop:].reshape(-1, config.DOWNSAMPLE_FACTOR).mean(axis=1)

                for key in all_metrics:
                    processed_data[key]["mean"] = downsample_mean(processed_data[key]["mean"])
                    processed_data[key]["std"] = downsample_mean(processed_data[key]["std"])
                    processed_data[key]["iqr_upper"] = downsample_mean(
                        processed_data[key]["iqr_upper"]
                    )
                    processed_data[key]["iqr_lower"] = downsample_mean(
                        processed_data[key]["iqr_lower"]
                    )
                training_time = downsample_mean(training_time)

                # Log per step metrics
                print("Logging per step metrics")
                for i in range(len(processed_data[all_metrics[0]]["mean"])):
                    log_dict = {
                        f"{prefix}{metric}_{agg}": processed_data[metric][agg][i]
                        for metric in all_metrics
                        for agg in ["mean", "std", "iqr_upper", "iqr_lower"]
                    }
                    log_dict[time_metric] = training_time[i]
                    log_dict["env_step"] = (i * config.DOWNSAMPLE_FACTOR) + step_count
                    wandb.log(log_dict)

            wandb.log(
                {
                    "performance/increment_time_s": increment_run_time,
                    "performance/environment_transitions_per_s": (
                        config.STEPS_PER_INCREMENT
                        * config.NUM_LEARNERS
                        / max(increment_run_time, 1e-9)
                    ),
                    "env_step": step_count + config.STEPS_PER_INCREMENT // config.NUM_ENVS,
                }
            )

            if config.LOG_LOSS_INFO and merged_out_loss is not None:
                print("Logging loss info")
                for i in range(len(merged_out_loss["loss/total_loss"])):
                    log_dict = {f"{metric}": merged_out_loss[metric][i] for metric in loss_metrics}
                    log_dict.update(
                        {
                            f"{metric}": merged_out_loss[metric][i]
                            for metric in prioritization_metrics
                        }
                    )
                    if config.REWARD_CENTERING:
                        log_dict_rc = {
                            f"{metric}": merged_out_loss[metric][i]
                            for metric in reward_centering_metrics
                        }
                        log_dict = {**log_dict, **log_dict_rc}
                    if config.ENHANCED_LOGGING:
                        log_dict_diag = {
                            f"{metric}": merged_out_loss[metric][i]
                            for metric in diagnostics_metrics
                        }
                        log_dict = {**log_dict, **log_dict_diag}
                    log_dict["update_epoch"] = i + update_count
                    wandb.log(log_dict)

    return merged_out, processed_data

make_ent_schedule(config)

Create an entropy coefficient schedule based on the configuration.

Source code in xlron/train/train_utils.py
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
def make_ent_schedule(config: Box) -> optax.Schedule:
    """Create an entropy coefficient schedule based on the configuration."""

    ENT_COEF = config.ENT_COEF
    ENT_END_FRACTION = config.ENT_END_FRACTION
    NUM_UPDATES = config.NUM_UPDATES * config.NUM_INCREMENTS
    # Evaluated at train_state.step (not optax's per-minibatch count), so the horizon
    # must use the train_state.step unit.
    STEPS_PER_UNIT = steps_per_train_state_unit(config)
    SCHEDULE_MULTIPLIER = config.ENT_SCHEDULE_MULTIPLIER
    end_value = ENT_COEF * ENT_END_FRACTION

    def ent_schedule(count: chex.Numeric) -> chex.Numeric:
        total_steps = NUM_UPDATES * STEPS_PER_UNIT * SCHEDULE_MULTIPLIER
        if config.ENT_SCHEDULE == "cosine":
            schedule = optax.cosine_decay_schedule(
                init_value=ENT_COEF,
                decay_steps=total_steps,
                alpha=end_value,
            )
        elif config.ENT_SCHEDULE == "linear":
            schedule = optax.linear_schedule(
                init_value=ENT_COEF,
                end_value=end_value,
                transition_steps=total_steps,
            )
        elif config.ENT_SCHEDULE == "constant":
            schedule = optax.constant_schedule(ENT_COEF)
        else:
            raise ValueError(f"Invalid entropy schedule {config.ENT_SCHEDULE}")
        return schedule(count)

    return ent_schedule

make_lr_schedule(config)

Create a learning rate schedule based on the configuration.

Source code in xlron/train/train_utils.py
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
def make_lr_schedule(config: Box) -> optax.Schedule:
    """Create a learning rate schedule based on the configuration."""

    LR = config.LR
    LR_END_FRACTION = config.LR_END_FRACTION
    NUM_MINIBATCHES = config.NUM_MINIBATCHES
    NUM_UPDATES = config.NUM_UPDATES * config.NUM_INCREMENTS
    UPDATE_EPOCHS = config.UPDATE_EPOCHS
    SCHEDULE_MULTIPLIER = config.LR_SCHEDULE_MULTIPLIER
    WARMUP_MULTIPLIER = config.WARMUP_MULTIPLIER
    WARMUP_STEPS_FRACTION = config.WARMUP_STEPS_FRACTION
    end_value = LR * LR_END_FRACTION

    def lr_schedule(count: chex.Numeric) -> chex.Numeric:
        total_steps = NUM_UPDATES * UPDATE_EPOCHS * NUM_MINIBATCHES * SCHEDULE_MULTIPLIER
        if config.LR_SCHEDULE == "warmup_cosine":
            schedule = optax.warmup_cosine_decay_schedule(
                init_value=LR,
                peak_value=LR * WARMUP_MULTIPLIER,
                warmup_steps=total_steps * WARMUP_STEPS_FRACTION,
                decay_steps=total_steps,
                end_value=end_value,
            )
        elif config.LR_SCHEDULE == "cosine":
            schedule = optax.cosine_decay_schedule(
                init_value=LR,
                decay_steps=total_steps,
                alpha=end_value,
            )
        elif config.LR_SCHEDULE == "linear":
            schedule = optax.linear_schedule(
                init_value=LR,
                end_value=end_value,
                transition_steps=total_steps,
            )
        elif config.LR_SCHEDULE == "constant":
            schedule = optax.constant_schedule(LR)
        else:
            raise ValueError(f"Invalid LR schedule {config.LR_SCHEDULE}")
        return schedule(count)

    return lr_schedule

make_vf_lr_schedule(config)

Create a learning rate schedule for the value function optimizer.

Source code in xlron/train/train_utils.py
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
def make_vf_lr_schedule(config: Box) -> optax.Schedule:
    """Create a learning rate schedule for the value function optimizer."""
    vf_lr = config.VF_LR if config.VF_LR is not None else config.LR / 3.0
    vf_schedule_type = (
        config.VF_LR_SCHEDULE if config.VF_LR_SCHEDULE is not None else config.LR_SCHEDULE
    )
    vf_end_fraction = (
        config.VF_LR_END_FRACTION
        if config.VF_LR_END_FRACTION is not None
        else config.LR_END_FRACTION
    )
    vf_warmup_mult = (
        config.VF_WARMUP_MULTIPLIER
        if config.VF_WARMUP_MULTIPLIER is not None
        else config.WARMUP_MULTIPLIER
    )
    vf_warmup_frac = (
        config.VF_WARMUP_STEPS_FRACTION
        if config.VF_WARMUP_STEPS_FRACTION is not None
        else config.WARMUP_STEPS_FRACTION
    )
    return _make_schedule(
        vf_lr,
        vf_end_fraction,
        vf_schedule_type,
        vf_warmup_mult,
        vf_warmup_frac,
        config,
        schedule_multiplier=config.VF_SCHEDULE_MULTIPLIER,
    )

make_vml_schedule(config)

Create a valid mass loss coefficient schedule based on the configuration.

Source code in xlron/train/train_utils.py
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
def make_vml_schedule(config: Box) -> optax.Schedule:
    """Create a valid mass loss coefficient schedule based on the configuration."""

    VML_COEF = config.VALID_MASS_LOSS_COEF
    VML_END_FRACTION = config.VML_END_FRACTION
    NUM_UPDATES = config.NUM_UPDATES * config.NUM_INCREMENTS
    # Evaluated at train_state.step (not optax's per-minibatch count), so the horizon
    # must use the train_state.step unit.
    STEPS_PER_UNIT = steps_per_train_state_unit(config)
    SCHEDULE_MULTIPLIER = config.VML_SCHEDULE_MULTIPLIER
    end_value = VML_COEF * VML_END_FRACTION

    def vml_schedule(count: chex.Numeric) -> chex.Numeric:
        total_steps = NUM_UPDATES * STEPS_PER_UNIT * SCHEDULE_MULTIPLIER
        if config.VML_SCHEDULE == "cosine":
            schedule = optax.cosine_decay_schedule(
                init_value=VML_COEF,
                decay_steps=total_steps,
                alpha=end_value,
            )
        elif config.VML_SCHEDULE == "linear":
            schedule = optax.linear_schedule(
                init_value=VML_COEF,
                end_value=end_value,
                transition_steps=total_steps,
            )
        elif config.VML_SCHEDULE == "constant":
            schedule = optax.constant_schedule(VML_COEF)
        else:
            raise ValueError(f"Invalid VML schedule {config.VML_SCHEDULE}")
        return schedule(count)

    return vml_schedule

merge_leading_dims(x, num_dims)

Merge leading dimensions.

Note

This implementation is a generic function for merging leading dimensions extracted from Haiku. For the original implementation, please refer to the following link: (https://github.com/deepmind/dm-haiku/blob/main/haiku/_src/basic.py#L207)

Source code in xlron/train/train_utils.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def merge_leading_dims(x: Array, num_dims: chex.Numeric) -> Array:
    """Merge leading dimensions.

    Note:
        This implementation is a generic function for merging leading dimensions
        extracted from Haiku.
        For the original implementation, please refer to the following link:
        (https://github.com/deepmind/dm-haiku/blob/main/haiku/_src/basic.py#L207)
    """
    # Don't merge if there aren't dimensions to merge.
    if not ndim_at_least(x, num_dims):
        return x

    new_shape = (np.prod(x.shape[:num_dims]),) + x.shape[num_dims:]
    return x.reshape(new_shape)

model_inputs(obs, env_params, config)

Policy call arguments: graph policies read the env params beside the state.

Observations never carry the params (they are pytrees of arrays, which a rollout scan or env vmap would otherwise copy into every transition), so they are appended here at call time.

Source code in xlron/train/train_utils.py
1257
1258
1259
1260
1261
1262
1263
1264
def model_inputs(obs, env_params, config):
    """Policy call arguments: graph policies read the env params beside the state.

    Observations never carry the params (they are pytrees of arrays, which a rollout
    scan or env vmap would otherwise copy into every transition), so they are
    appended here at call time.
    """
    return (*obs, env_params) if config.USE_GNN or config.USE_TRANSFORMER else tuple(obs)

ndim_at_least(x, num_dims)

Check if the number of dimensions of x is at least num_dims.

Source code in xlron/train/train_utils.py
521
522
523
524
525
def ndim_at_least(x: Array, num_dims: chex.Numeric) -> jax.Array:
    """Check if the number of dimensions of `x` is at least `num_dims`."""
    if not (isinstance(x, jax.Array) or isinstance(x, np.ndarray)):
        x = jnp.asarray(x)
    return x.ndim >= num_dims

print_experiment_summary(config, env_params=None)

Print a formatted summary of the experiment configuration.

Source code in xlron/train/train_utils.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
517
518
def print_experiment_summary(config: Box, env_params=None) -> None:
    """Print a formatted summary of the experiment configuration."""
    W = 70
    sep = "=" * W

    # --- Determine execution mode ---
    if config.get("EVAL_HEURISTIC", False):
        mode = f"Heuristic Evaluation ({config.get('path_heuristic', '?')})"
    elif config.get("EVAL_MODEL", False):
        mode = "Model Evaluation"
    elif config.get("ACTION_OPTIMIZATION", False):
        mode = "Action Optimization"
    else:
        mode = "RL Training (PPO)"

    # --- Environment ---
    env_type = config.get("env_type", "?")
    topology = config.get("topology_name", "?")
    if env_params:
        num_nodes = env_params.num_nodes
        num_links = env_params.num_links
    elif config.get("NUM_NODES"):
        num_nodes = config.NUM_NODES
        num_links = config.NUM_LINKS
    else:
        graph = make_graph(topology, topology_directory=config.get("topology_directory", None))
        num_nodes = len(graph.nodes)
        num_links = len(graph.edges)
    k = env_params.k_paths if env_params else config.get("k", "?")
    link_resources = env_params.link_resources if env_params else config.get("link_resources", "?")
    slot_size = env_params.slot_size if env_params else config.get("slot_size", 12.5)
    guardband = env_params.guardband if env_params else config.get("guardband", 1)
    directed = env_params.directed_graph if env_params else config.get("directed_graph", "?")
    path_sort = config.get("path_sort_criteria", "hops")
    total_bw = float(link_resources) * float(slot_size) if link_resources != "?" else "?"

    # --- Traffic ---
    load = env_params.load if env_params else config.get("load", "?")
    holding_time = (
        env_params.mean_service_holding_time
        if env_params
        else config.get("mean_service_holding_time", "?")
    )
    if env_params:
        arrival_rate = env_params.arrival_rate
    elif load != "?" and holding_time != "?":
        arrival_rate = float(load) / float(holding_time)
    else:
        arrival_rate = "?"
    continuous = (
        env_params.continuous_operation if env_params else config.get("continuous_operation", False)
    )
    incremental = (
        env_params.incremental_loading if env_params else config.get("incremental_loading", False)
    )
    max_requests = env_params.max_requests if env_params else config.get("max_requests", "?")
    warmup = config.get("ENV_WARMUP_STEPS", 0)
    reward_type = env_params.reward_type if env_params else config.get("reward_type", "service")
    values_bw = env_params.values_bw if env_params else config.get("values_bw", None)
    truncate_ht = (
        env_params.truncate_holding_time
        if env_params
        else config.get("truncate_holding_time", False)
    )

    # --- Training / Execution ---
    total_timesteps = config.get("TOTAL_TIMESTEPS", "?")
    num_envs = config.get("NUM_ENVS", 1)
    num_learners = config.get("NUM_LEARNERS", 1)
    rollout_length = config.get("ROLLOUT_LENGTH", "?")
    num_updates = config.get("NUM_UPDATES", "?")
    num_minibatches = config.get("NUM_MINIBATCHES", 1)
    update_epochs = config.get("UPDATE_EPOCHS", 1)
    num_increments = config.get("NUM_INCREMENTS", 1)
    steps_per_inc = config.get("STEPS_PER_INCREMENT", "?")
    batch_size = config.get("MINIBATCH_SIZE", "?")

    # --- Model ---
    if config.get("USE_TRANSFORMER", False):
        arch = "Transformer"
        arch_detail = (
            f"{config.get('transformer_num_layers', '?')}L / "
            f"{config.get('transformer_num_heads', '?')}H / "
            f"d={config.get('transformer_embedding_size', '?')}"
        )
    elif config.get("USE_GNN", False):
        arch = "GNN"
        arch_detail = (
            f"{config.get('message_passing_steps', '?')} msg steps / "
            f"edge_emb={config.get('edge_embedding_size', '?')}"
        )
    else:
        arch = "MLP"
        arch_detail = (
            f"{config.get('NUM_LAYERS', '?')} layers x {config.get('NUM_UNITS', '?')} units"
        )

    # --- Print ---
    print(f"\n{sep}")
    print("EXPERIMENT SUMMARY")
    print(sep)

    print(f"  Mode:                     {mode}")
    print(f"  Experiment name:          {config.get('EXPERIMENT_NAME', '-')}")

    print(f"\n  {'--- Environment ---':^{W - 4}}")
    print(f"  Type:                     {env_type}")
    print(f"  Topology:                 {topology} ({'directed' if directed else 'undirected'})")
    print(f"  Nodes / Links:            {num_nodes} / {num_links}")
    print(f"  K-shortest paths:         {k}  (sort: {path_sort})")
    print(
        f"  Slots per link:           {link_resources}  ({slot_size} GHz each, guardband={guardband})"
    )
    if total_bw != "?":
        print(f"  Total spectrum per link:  {total_bw:.0f} GHz")
    consider_mod = env_params.consider_modulation_format if env_params else "?"
    if consider_mod and consider_mod != "?":
        print("  Modulation format:        enabled")
    if config.get("aggregate_slots", 1) > 1:
        print(f"  Slot aggregation:         {config.get('aggregate_slots')}x")

    print(f"\n  {'--- Traffic ---':^{W - 4}}")
    print(f"  Load:                     {load} Erlang")
    print(f"  Arrival rate:             {arrival_rate}")
    print(f"  Mean holding time:        {holding_time}{' (truncated)' if truncate_ht else ''}")
    if values_bw is not None:
        # Support values_bw provided as scalar, array, or comma-separated string.
        if isinstance(values_bw, str):
            parts = [p.strip() for p in values_bw.split(",") if p.strip()]
            bw_list = []
            for p in parts:
                try:
                    fv = float(p)
                    bw_list.append(str(int(fv)) if fv.is_integer() else str(fv))
                except ValueError:
                    bw_list.append(p)
        else:
            flat = np.asarray(values_bw).reshape(-1)
            bw_list = []
            for v in flat:
                try:
                    fv = float(v)
                    bw_list.append(str(int(fv)) if fv.is_integer() else str(fv))
                except (TypeError, ValueError):
                    bw_list.append(str(v))
        bw_str = ", ".join(bw_list)
        print(f"  Bandwidth values (Gbps):  [{bw_str}]")
    print(f"  Reward type:              {reward_type}")
    op_mode = "continuous" if continuous else ("incremental" if incremental else "episodic")
    print(f"  Operation mode:           {op_mode}")
    if not continuous:
        print(f"  Max requests / episode:   {max_requests}")
    if warmup > 0:
        warmup_type = config.get("warmup_action_type", None) or "default"
        if config.get("warmup_path_heuristic"):
            warmup_type += f", {config.warmup_path_heuristic}"
        print(f"  Warmup steps:             {warmup} ({warmup_type})")

    print(f"\n  {'--- Execution ---':^{W - 4}}")
    print(
        f"  Total timesteps:          {total_timesteps:,}"
        if isinstance(total_timesteps, int)
        else f"  Total timesteps:          {total_timesteps}"
    )
    print(f"  Parallel envs:            {num_envs}")
    if num_learners > 1:
        print(f"  Independent learners:     {num_learners}")
        print(f"  Grand total timesteps:    {total_timesteps * num_learners:,}")
    print(
        f"  Increments:               {num_increments}  ({steps_per_inc:,} steps each)"
        if isinstance(steps_per_inc, int)
        else f"  Increments:               {num_increments}"
    )

    if not config.get("EVAL_HEURISTIC", False):
        print(f"  Rollout length:           {rollout_length}")
        batch_total = num_envs * rollout_length if isinstance(rollout_length, int) else "?"
        print(
            f"  Batch size:               {batch_total}  (= {num_envs} envs x {rollout_length} steps)"
        )
        print(f"  Minibatches / epoch:      {num_minibatches}  (minibatch size: {batch_size})")
        print(f"  Update epochs:            {update_epochs}")
        total_updates = num_increments * num_updates * update_epochs * num_minibatches
        print(
            f"  Total gradient steps:     {total_updates:,}"
            if isinstance(total_updates, int)
            else f"  Total gradient steps:     {total_updates}"
        )

    if not (config.get("EVAL_HEURISTIC", False) or config.get("EVAL_MODEL", False)):
        print(f"\n  {'--- Model & Optimiser ---':^{W - 4}}")
        print(f"  Architecture:             {arch}  ({arch_detail})")
        activation = (
            f"{config.get('transformer_ffn_activation', 'gelu')} (FFN)"
            if config.get("USE_TRANSFORMER", False)
            else config.get("ACTIVATION", "?")
        )
        print(f"  Activation:               {activation}")
        print(
            f"  Learning rate:            {config.get('LR', '?')}  (schedule: {config.get('LR_SCHEDULE', '?')})"
        )
        print(f"  Discount (gamma):         {config.get('GAMMA', '?')}")
        gae = config.get("GAE_LAMBDA", None)
        if gae is not None:
            print(f"  GAE lambda:               {gae}")
        else:
            print(
                f"  GAE lambda:               annealed ({config.get('INITIAL_LAMBDA', '?')} -> {config.get('FINAL_LAMBDA', '?')})"
            )
        print(f"  PPO clip:                 {config.get('CLIP_EPS', '?')}")
        print(
            f"  Entropy coef:             {config.get('ENT_COEF', '?')}  (schedule: {config.get('ENT_SCHEDULE', '?')})"
        )
        print(f"  VF coef:                  {config.get('VF_COEF', '?')}")
        print(f"  Max grad norm:            {config.get('MAX_GRAD_NORM', '?')}")
        if config.get("REWARD_CENTERING", False):
            print(
                f"  Reward centering:         enabled (stepsize={config.get('REWARD_STEPSIZE', '?')})"
            )
        if config.get("SEPARATE_VF_OPTIMIZER", False):
            print(f"  Separate VF optimizer:    enabled (VF_LR={config.get('VF_LR', 'auto')})")

    if config.get("EVAL_DURING_TRAINING", False):
        print(
            f"\n  Eval during training:     every {config.get('EVAL_FREQUENCY', '?')} increment(s)"
        )

    if config.get("WANDB", False):
        print(f"  Logging:                  wandb ({config.get('PROJECT', '-')})")
    if config.get("SAVE_MODEL", False):
        print("  Model saving:             enabled")

    print(sep + "\n")

print_metrics(processed_data, config, user_flags=None, timing=None)

Print final metrics as a standardized run summary and optionally write JSONL.

Source code in xlron/train/train_utils.py
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
def print_metrics(
    processed_data: Dict[str, Dict[str, Array]],
    config: Union[Box, Dict[str, Any]],
    user_flags: dict | None = None,
    timing: Dict[str, Any] | None = None,
) -> None:
    """Print final metrics as a standardized run summary and optionally write JSONL."""
    # Determine run type
    if config.get("EVAL_HEURISTIC"):
        run_type = "heuristic_eval"
    elif config.get("EVAL_MODEL"):
        run_type = "model_eval"
    else:
        run_type = "rl_training"

    # Extract final scalar stats from processed_data
    metrics_dict = {}
    for metric in processed_data.keys():
        if config.get("continuous_operation", False):
            metrics_dict[metric] = {
                "mean": float(processed_data[metric]["mean"][-1]),
                "std": float(processed_data[metric]["std"][-1]),
                "iqr_lower": float(processed_data[metric]["iqr_lower"][-1]),
                "iqr_upper": float(processed_data[metric]["iqr_upper"][-1]),
            }
        else:
            metrics_dict[metric] = {
                "mean": float(processed_data[metric]["episode_end_mean"].mean()),
                "std": float(processed_data[metric]["episode_end_std"].mean()),
                "iqr_lower": float(processed_data[metric]["episode_end_iqr_lower"].mean()),
                "iqr_upper": float(processed_data[metric]["episode_end_iqr_upper"].mean()),
            }

    run_config = user_flags if user_flags is not None else {}
    summary = build_run_summary(run_type, run_config, metrics_dict, timing=timing)
    write_run_summary(summary, config.get("DATA_OUTPUT_FILE"), print_to_console=True)

process_metrics(config, out, merge_func)

Calculate statistics from training or evaluation run.

Source code in xlron/train/train_utils.py
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
def process_metrics(config, out, merge_func):
    """Calculate statistics from training or evaluation run."""
    merged_out = {k: jax.tree.map(merge_func, v) for k, v in out["metrics"].items()}
    if config.EVAL_HEURISTIC or config.EVAL_MODEL:
        merged_out_loss = None
    else:
        # Average over minibatches and epochs to get one value per update
        num_learners_or_1 = config.NUM_LEARNERS if config.NUM_LEARNERS > 1 else 1
        merged_out_loss = {
            k: jax.tree.map(
                lambda x: (
                    x.reshape((num_learners_or_1, config.NUM_UPDATES, -1))
                    .mean(axis=-1)
                    .reshape((-1,))
                ),
                v,
            )
            for k, v in out.get("loss_info", {}).items()
        }

    # Calculate blocking probabilities
    merged_out["service_blocking_probability"] = 1 - (
        merged_out["accepted_services"]
        / jnp.where(merged_out["lengths"] == 0, 1, merged_out["lengths"])
    )
    merged_out["bitrate_blocking_probability"] = 1 - (
        merged_out["accepted_bitrate"]
        / jnp.where(merged_out["total_bitrate"] == 0, 1, merged_out["total_bitrate"])
    )

    # Blocking-cause breakdown (GN-model envs only; keys absent for other env types).
    # Causes are mutually exclusive, so these probabilities sum to
    # service_blocking_probability.
    if "blocked_spectrum" in merged_out:
        lengths_safe = jnp.where(merged_out["lengths"] == 0, 1, merged_out["lengths"])
        merged_out["spectrum_blocking_probability"] = merged_out["blocked_spectrum"] / lengths_safe
        merged_out["snr_blocking_probability"] = merged_out["blocked_snr"] / lengths_safe
        merged_out["power_blocking_probability"] = merged_out["blocked_power"] / lengths_safe

    # Calculate episode ends
    merged_out["done"] = jnp.logical_or(merged_out["terminal"], merged_out["truncated"])
    episode_ends = merged_out["done"]

    print(f"Created episode end mask with {np.sum(episode_ends)} episode endings")

    processed_data = {}
    print("Processing output metrics")
    for metric in metrics:
        ends = episode_ends
        try:
            episode_end_mean, episode_end_std, episode_end_iqr_upper, episode_end_iqr_lower = (
                get_episode_end_mean_std_iqr(merged_out[metric], ends, config.NUM_ENVS)
            )
            mean, std, iqr_upper, iqr_lower = get_mean_std_iqr(merged_out, metric)
            processed_data[metric] = {
                "mean": mean,
                "std": std,
                "iqr_upper": iqr_upper,
                "iqr_lower": iqr_lower,
                "episode_end_mean": episode_end_mean,
                "episode_end_std": episode_end_std,
                "episode_end_iqr_upper": episode_end_iqr_upper,
                "episode_end_iqr_lower": episode_end_iqr_lower,
            }
        except KeyError:
            continue
    return merged_out, merged_out_loss, processed_data, episode_ends

reset_warmup_metric_counters(env_state)

Zero the metric counters accumulated during warmup.

With continuous_operation the env is never reset, so the cumulative counters (accepted_services, accepted_bitrate, total_bitrate, and the GN-model blocked_spectrum/blocked_snr/blocked_power counters) and the LogWrapper's lengths/cum_returns would otherwise include the near-zero-blocking network-fill transient, biasing every logged blocking probability (ENV_WARMUP_STEPS is documented as 'steps before collecting stats'). These fields are metrics-only; total_requests, which drives episode truncation, is deliberately kept. jnp.zeros_like preserves per-env shapes and dtypes for the jitted learner.

Source code in xlron/train/train_utils.py
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def reset_warmup_metric_counters(env_state):
    """Zero the metric counters accumulated during warmup.

    With continuous_operation the env is never reset, so the cumulative counters
    (accepted_services, accepted_bitrate, total_bitrate, and the GN-model
    blocked_spectrum/blocked_snr/blocked_power counters) and the LogWrapper's
    lengths/cum_returns would otherwise include the near-zero-blocking network-fill
    transient, biasing every logged blocking probability (ENV_WARMUP_STEPS is
    documented as 'steps before collecting stats'). These fields are metrics-only;
    total_requests, which drives episode truncation, is deliberately kept.
    jnp.zeros_like preserves per-env shapes and dtypes for the jitted learner.
    """
    inner_state = env_state.env_state
    inner_updates = dict(
        accepted_services=jnp.zeros_like(inner_state.accepted_services),
        accepted_bitrate=jnp.zeros_like(inner_state.accepted_bitrate),
        total_bitrate=jnp.zeros_like(inner_state.total_bitrate),
    )
    # GN-model env states also carry cumulative blocking-cause counters; zero them so
    # spectrum/snr/power_blocking_probability exclude the warmup transient and keep
    # summing to service_blocking_probability. hasattr inspects the static pytree
    # structure (not traced values), so this branch is jit-safe.
    if hasattr(inner_state, "blocked_spectrum"):
        inner_updates.update(
            blocked_spectrum=jnp.zeros_like(inner_state.blocked_spectrum),
            blocked_snr=jnp.zeros_like(inner_state.blocked_snr),
            blocked_power=jnp.zeros_like(inner_state.blocked_power),
        )
    return env_state.replace(
        lengths=jnp.zeros_like(env_state.lengths),
        cum_returns=jnp.zeros_like(env_state.cum_returns),
        accepted_services=jnp.zeros_like(env_state.accepted_services),
        accepted_bitrate=jnp.zeros_like(env_state.accepted_bitrate),
        total_bitrate=jnp.zeros_like(env_state.total_bitrate),
        blocked_spectrum=jnp.zeros_like(env_state.blocked_spectrum),
        blocked_snr=jnp.zeros_like(env_state.blocked_snr),
        blocked_power=jnp.zeros_like(env_state.blocked_power),
        env_state=inner_state.replace(**inner_updates),
    )

run_eval_during_training(config, run_eval, eval_input, out, best_eval_metric, step_count, first_save=True)

Run evaluation during training and save model if it improves.

Parameters:

Name Type Description Default
config Box

Training configuration.

required
run_eval Callable

Compiled eval function.

required
eval_input Tuple

Initial eval runner state (train_state, env_state, obsv, rng_step, rng_epoch).

required
out Dict

Output from the current training increment.

required
best_eval_metric float

Best eval metric seen so far.

required
step_count int

Current training env step count (for wandb logging).

required
first_save bool

Whether this is the first save of the training run.

True

Returns:

Type Description
Tuple

Tuple of (updated best_eval_metric, updated first_save).

Source code in xlron/train/train_utils.py
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
def run_eval_during_training(
    config: Box,
    run_eval: Callable,
    eval_input: Tuple,
    out: Dict,
    best_eval_metric: float,
    step_count: int,
    first_save: bool = True,
) -> Tuple:
    """Run evaluation during training and save model if it improves.

    Args:
        config: Training configuration.
        run_eval: Compiled eval function.
        eval_input: Initial eval runner state (train_state, env_state, obsv, rng_step, rng_epoch).
        out: Output from the current training increment.
        best_eval_metric: Best eval metric seen so far.
        step_count: Current training env step count (for wandb logging).
        first_save: Whether this is the first save of the training run.

    Returns:
        Tuple of (updated best_eval_metric, updated first_save).
    """
    # Inject current model params into a copy of the eval runner state.
    # Copy the eval inputs to prevent buffer donation from invalidating the
    # original buffers, which need to be reused on subsequent eval runs.
    current_train_state = out["runner_state"][0]
    eval_runner_state = jax.tree.map(
        jnp.copy,
        (
            current_train_state,
            eval_input[1],  # fresh eval env_state
            eval_input[2],  # fresh eval obsv
            eval_input[3],  # eval rng_step
            eval_input[4],  # eval rng_epoch
        ),
    )
    eval_out = run_eval(eval_runner_state)
    eval_out["metrics"]["returns"].block_until_ready()

    # Compute eval blocking probability, discarding the warmup transient.
    # Metrics shape: (NUM_EPISODES, steps_per_episode, NUM_ENVS) if NUM_ENVS > 1
    #                (NUM_EPISODES, steps_per_episode) if NUM_ENVS == 1
    # With continuous_operation, env_state counters (accepted_services,
    # accepted_bitrate, total_bitrate) are cumulative and never reset.
    # LogWrapper's `lengths` resets per episode so can't be used as a
    # cumulative request count — use the step count directly instead.
    def _flatten(metric):
        """Flatten (NUM_EPISODES, steps_per_episode, ...) -> (total_steps, ...) keeping env dim."""
        x = eval_out["metrics"][metric]
        return x.reshape(-1, *x.shape[2:])  # (total_steps,) or (total_steps, NUM_ENVS)

    accepted_services = _flatten("accepted_services")
    accepted_bitrate = _flatten("accepted_bitrate")
    total_bitrate = _flatten("total_bitrate")
    total_steps = accepted_services.shape[0]

    # Warmup index is per-env steps. Clamp to valid range.
    warmup_idx = int(config.ENV_WARMUP_STEPS)

    # Check ENV_WARMUP_STEPS does not exceed total_steps
    assert warmup_idx < total_steps, (
        f"ENV_WARMUP_STEPS ({config.ENV_WARMUP_STEPS}) must be less than "
        f"the total evaluation steps ({total_steps})."
    )

    # Service BP: each step is one request, so denominator = steps after warmup
    post_warmup_requests = max(total_steps - warmup_idx, 1)
    post_warmup_accepted = accepted_services[-1] - accepted_services[warmup_idx]
    service_bp_per_env = 1 - (post_warmup_accepted / post_warmup_requests)
    service_bp_mean = float(jnp.mean(service_bp_per_env))
    service_bp_std = float(jnp.std(service_bp_per_env))

    # Bitrate BP: denominator is cumulative total_bitrate delta
    post_warmup_total_br = total_bitrate[-1] - total_bitrate[warmup_idx]
    post_warmup_total_br = jnp.where(post_warmup_total_br == 0, 1, post_warmup_total_br)
    post_warmup_accepted_br = accepted_bitrate[-1] - accepted_bitrate[warmup_idx]
    bitrate_bp_per_env = 1 - (post_warmup_accepted_br / post_warmup_total_br)
    bitrate_bp_mean = float(jnp.mean(bitrate_bp_per_env))
    bitrate_bp_std = float(jnp.std(bitrate_bp_per_env))

    if config.reward_type == "bitrate":
        eval_metric_mean = bitrate_bp_mean
        eval_metric_std = bitrate_bp_std
        eval_metric_name = "bitrate_blocking_probability"
    else:
        eval_metric_mean = service_bp_mean
        eval_metric_std = service_bp_std
        eval_metric_name = "service_blocking_probability"

    print(
        f"Eval {eval_metric_name}: {eval_metric_mean:.6f} \u00b1 {eval_metric_std:.6f}"
        f" (best: {best_eval_metric:.6f})"
    )

    if config.WANDB:
        wandb.log(
            {
                "eval/service_blocking_probability_mean": service_bp_mean,
                "eval/service_blocking_probability_std": service_bp_std,
                "eval/bitrate_blocking_probability_mean": bitrate_bp_mean,
                "eval/bitrate_blocking_probability_std": bitrate_bp_std,
                "env_step": step_count,
            }
        )

    if eval_metric_mean <= best_eval_metric:
        best_eval_metric = eval_metric_mean
        print(f"New best eval {eval_metric_name}: {best_eval_metric:.6f}")
        if config.SAVE_MODEL:
            model_params = current_train_state.model_params
            if config.NUM_LEARNERS > 1:
                # vmap over the learner axis stacks every param leaf to [NUM_LEARNERS, ...];
                # save learner 0's weights so the checkpoint matches the unbatched template
                # used by load_model.
                model_params = jax.tree.map(lambda x: x[0], model_params)
            model = eqx.combine(model_params, current_train_state.model_static)
            saved_path = save_model(model, config, first_save=first_save)
            if first_save:
                config.MODEL_PATH = str(saved_path)
                first_save = False

    return best_eval_metric, first_save

save_warmup_cache(path, result)

Save the warmup's (env_state, obs) leaves; written atomically.

Source code in xlron/train/train_utils.py
1203
1204
1205
1206
1207
1208
1209
def save_warmup_cache(path: pathlib.Path, result) -> None:
    """Save the warmup's (env_state, obs) leaves; written atomically."""
    path.parent.mkdir(parents=True, exist_ok=True)
    partial_path = path.with_suffix(f".{os.getpid()}.tmp.npz")
    leaves = jax.tree.leaves(result)
    np.savez(partial_path, **{f"leaf_{i}": np.asarray(x) for i, x in enumerate(leaves)})
    os.replace(partial_path, path)

scale_gradient(g, scale=1)

Scales the gradient of g by scale but keeps the original value unchanged.

Source code in xlron/train/train_utils.py
276
277
278
def scale_gradient(g: Array, scale: float = 1) -> Array:
    """Scales the gradient of `g` by `scale` but keeps the original value unchanged."""
    return g * scale + jax.lax.stop_gradient(g) * (1.0 - scale)

select_action(select_action_state, env, env_params, train_state, config)

Select an action from the policy. If using VONE, the action is a tuple of (source, path, destination). Otherwise, the action is a single lightpath. Args: select_action_state: Tuple of (rng_key, env_state, last_obs) env: Environment env_params: Environment parameters train_state: TrainState config: Configuration Returns: env_state: Environment state action: Action log_prob: Log probability of action value: Value of state

Source code in xlron/train/train_utils.py
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
def select_action(select_action_state, env, env_params, train_state, config):
    """Select an action from the policy.
    If using VONE, the action is a tuple of (source, path, destination).
    Otherwise, the action is a single lightpath.
    Args:
        select_action_state: Tuple of (rng_key, env_state, last_obs)
        env: Environment
        env_params: Environment parameters
        train_state: TrainState
        config: Configuration
    Returns:
        env_state: Environment state
        action: Action
        log_prob: Log probability of action
        value: Value of state
    """
    action_key, env_state, last_obs = select_action_state
    if config.USE_GNN or config.USE_TRANSFORMER:
        last_obs = (env_state.env_state,)
    model = eqx.combine(train_state.model_params, train_state.model_static)
    model = cast_model_for_compute(model)
    # This opt-in head reads the freshly resolved format/width at each candidate.
    # Save the same acting state in PPO so gradient updates see identical features.
    modulation_features = config.get("transformer_modulation_features", False)
    mask_result = env.action_mask(env_state.env_state, env_params)
    if len(mask_result) == 3:
        action_mask, full_action_mask, mod_format_mask = mask_result
    else:
        action_mask, full_action_mask = mask_result
        mod_format_mask = None

    if modulation_features:
        model_state = env_state.env_state.replace(
            link_slot_mask=action_mask,
            full_link_slot_mask=full_action_mask,
            mod_format_mask=mod_format_mask,
        )
        pi, value = model(model_state, env_params)
    else:
        pi, value = model(*model_inputs(last_obs, env_params, config))

    # Always do action masking with VONE
    if config.env_type.lower() == "vone":
        # The single set of logits is sliced into three heads. Layout matches
        # VONEEnv.num_actions: [source nodes | dest nodes | path-slot actions]
        # (a trailing no-op logit, if include_no_op, belongs to no head).
        # select_action operates on a single (unbatched) env state; batching over
        # NUM_ENVS is applied by the outer vmap of _env_step in ppo.py.
        num_nodes = env_params.num_nodes
        source_logits = pi._logits[..., :num_nodes]
        dest_logits = pi._logits[..., num_nodes : 2 * num_nodes]
        key_s, key_p, key_d = jax.random.split(action_key, 3)

        inner_state = env.action_mask_nodes(env_state.env_state, env_params)
        pi_source = distrax.Categorical(
            logits=source_logits + (-1e8 * (1 - inner_state.node_mask_s.astype(jnp.float32)))
        )
        action_s = pi_source.sample(seed=key_s) if not config.deterministic else pi_source.mode()

        # Update destination mask now source has been selected
        inner_state = env.action_mask_dest_node(inner_state, env_params, action_s)
        pi_dest = distrax.Categorical(
            logits=dest_logits + (-1e8 * (1 - inner_state.node_mask_d.astype(jnp.float32)))
        )
        action_d = pi_dest.sample(seed=key_d) if not config.deterministic else pi_dest.mode()

        action = jnp.stack((action_s, jnp.zeros_like(action_s), action_d))
        inner_state = env.action_mask_slots(inner_state, env_params, action)
        path_dim = inner_state.link_slot_mask.shape[-1]
        path_logits = pi._logits[..., 2 * num_nodes : 2 * num_nodes + path_dim]
        pi_path = distrax.Categorical(
            logits=path_logits + (-1e8 * (1 - inner_state.link_slot_mask.astype(jnp.float32)))
        )
        action_p = pi_path.sample(seed=key_p) if not config.deterministic else pi_path.mode()
        action = jnp.stack((action_s, action_p, action_d))

        log_prob_source = pi_source.log_prob(action_s)
        log_prob_path = pi_path.log_prob(action_p)
        log_prob_dest = pi_dest.log_prob(action_d)
        log_prob = log_prob_dest + log_prob_path + log_prob_source
        env_state = env_state.replace(env_state=inner_state)
        # Overwrite the (stale) pre-branch masks with the freshly computed path masks so the
        # final state update below stores them; valid_mass mirrors the RSA path-head semantics.
        action_mask = inner_state.link_slot_mask
        full_action_mask = inner_state.full_link_slot_mask
        probs = jax.nn.softmax(path_logits, axis=-1)
        valid_mass = jnp.sum(probs * action_mask.astype(jnp.float32), axis=-1)

    elif "gn_model" in config.env_type.lower() and config.launch_power_type == "rl":
        # Sampling dispatches to the model's own sample_action* methods (the models know how
        # to convert raw samples to power levels); LaunchPowerActorCriticMLP returns
        # (None, power_dist) so the path logits/mask only exist when the GNN outputs RSA.
        if config.GNN_OUTPUT_RSA and not config.GNN_OUTPUT_LP:
            pi_masked = distrax.Categorical(
                logits=pi[0]._logits + (-1e8 * (1 - action_mask.astype(jnp.float32)))
            )
            path_action, log_prob = model.sample_action_path(  # ty: ignore[unresolved-attribute]
                action_key, pi_masked, log_prob=True, deterministic=config.deterministic
            )
            power_action = jnp.array([env_params.default_launch_power])
        elif config.GNN_OUTPUT_RSA and config.GNN_OUTPUT_LP:
            pi_masked = distrax.Categorical(
                logits=pi[0]._logits + (-1e8 * (1 - action_mask.astype(jnp.float32)))
            )
            path_action, power_action, log_prob = model.sample_action_path_power(  # ty: ignore[unresolved-attribute]
                action_key,
                (pi_masked, pi[1]),
                log_prob=True,
                deterministic=config.deterministic,
            )
        else:
            # Power-only policy: path selected by heuristic (needs launch power set first)
            power_sample_fn = getattr(model, "sample_action_power", model.sample_action)  # ty: ignore[unresolved-attribute]
            power_action, log_prob = power_sample_fn(
                action_key, pi[1], log_prob=True, deterministic=config.deterministic
            )
            inner_state = env_state.env_state.replace(
                launch_power_array=_as_launch_power_array(power_action, env_params)
            )
            env_state = env_state.replace(env_state=inner_state)
            path_action = (
                ksp_lf(env_state.env_state, env_params)
                if env_params.last_fit is True
                else ksp_ff(env_state.env_state, env_params)
            )
        inner_state = env_state.env_state.replace(
            launch_power_array=_as_launch_power_array(power_action, env_params)
        )
        env_state = env_state.replace(env_state=inner_state)
        if config.global_output_size_actor == 0 and (
            config.GNN_OUTPUT_LP or not config.GNN_OUTPUT_RSA
        ):
            # Per-path power head: keep only the sampled path's power/log_prob
            path_index, _ = process_path_action(env_state.env_state, env_params, path_action)
            power_action, log_prob = power_action[path_index], log_prob[path_index]
        action = jnp.concatenate([path_action.reshape((1,)), power_action.reshape((1,))], axis=0)
        if config.GNN_OUTPUT_RSA:
            probs = jax.nn.softmax(pi[0]._logits, axis=-1)
            valid_mass = jnp.sum(probs * action_mask, axis=-1)
        else:
            # No learned path policy: the heuristic path choice is always valid
            valid_mass = jnp.array(1.0, dtype=dtype_config.LARGE_FLOAT_DTYPE)

    else:
        pi_masked = distrax.Categorical(
            logits=pi._logits + (-1e8 * (1 - action_mask.astype(jnp.float32)))
        )
        action = pi_masked.sample(seed=action_key) if not config.deterministic else pi_masked.mode()
        log_prob = pi_masked.log_prob(action)
        probs = jax.nn.softmax(pi._logits, axis=-1)
        valid_mass = jnp.sum(probs * action_mask, axis=-1)

    # Single state update at the end. Store the validity masks at MASK_DTYPE so the carried
    # field dtype is stable across the scan (matches init_link_slot_mask); the transient
    # action_mask used above for logit-masking / valid_mass keeps its full-width dtype.
    # mod_format_mask stays on the SMALL_FLOAT tier (-1 sentinels / modulation indices).
    replace_kwargs = dict(
        link_slot_mask=action_mask.astype(dtype_config.MASK_DTYPE),
        full_link_slot_mask=full_action_mask.astype(dtype_config.MASK_DTYPE),
        valid_mass=valid_mass,
    )
    if mod_format_mask is not None:
        replace_kwargs["mod_format_mask"] = mod_format_mask.astype(dtype_config.SMALL_FLOAT_DTYPE)
    inner_state = env_state.env_state.replace(**replace_kwargs)
    env_state = env_state.replace(env_state=inner_state)

    return env_state, action, log_prob, value

steps_per_train_state_unit(config)

Number of train_state.step increments per update loop.

train_state.step increments once per gradient (minibatch) step when STEP_ON_GRADIENT is set, otherwise once per update loop. Any schedule or anneal evaluated at train_state.step (entropy/VML schedules, GAE-lambda and prio-beta anneals) must scale its horizon by this factor so it completes exactly at the end of training. The LR schedules are exempt: they are driven by optax's internal count, which always ticks once per tx.update (i.e. per minibatch).

Source code in xlron/train/train_utils.py
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
def steps_per_train_state_unit(config: Box) -> int:
    """Number of train_state.step increments per update loop.

    train_state.step increments once per gradient (minibatch) step when STEP_ON_GRADIENT
    is set, otherwise once per update loop. Any schedule or anneal evaluated at
    train_state.step (entropy/VML schedules, GAE-lambda and prio-beta anneals) must scale
    its horizon by this factor so it completes exactly at the end of training. The LR
    schedules are exempt: they are driven by optax's internal count, which always ticks
    once per tx.update (i.e. per minibatch).
    """
    return config.UPDATE_EPOCHS * config.NUM_MINIBATCHES if config.STEP_ON_GRADIENT else 1

unreplicate_batch_dim(x)

Unreplicated just the update batch dimension. (The dimension that is vmapped over when acting and learning)

In stoix's case it is always the second dimension, after the device dimension. We simply take element 0 as the params are identical across this dimension.

Source code in xlron/train/train_utils.py
555
556
557
558
559
560
561
562
def unreplicate_batch_dim(x: ArrayTree) -> ArrayTree:
    """Unreplicated just the update batch dimension.
    (The dimension that is vmapped over when acting and learning)

    In stoix's case it is always the second dimension, after the device dimension.
    We simply take element 0 as the params are identical across this dimension.
    """
    return jax.tree_util.tree_map(lambda x: x[:, 0, ...], x)

unreplicate_n_dims(x, unreplicate_depth=2)

Unreplicates a pytree by removing the first unreplicate_depth axes.

This function takes a pytree and removes some number of axes, associated with parameter duplication for running multiple updates across devices and in parallel with vmap. This is typically one axis for device replication, and one for the update batch size.

Source code in xlron/train/train_utils.py
545
546
547
548
549
550
551
552
def unreplicate_n_dims(x: ArrayTree, unreplicate_depth: int = 2) -> ArrayTree:
    """Unreplicates a pytree by removing the first `unreplicate_depth` axes.

    This function takes a pytree and removes some number of axes, associated with parameter
    duplication for running multiple updates across devices and in parallel with `vmap`.
    This is typically one axis for device replication, and one for the `update batch size`.
    """
    return jax.tree_util.tree_map(lambda x: x[(0,) * unreplicate_depth], x)

warmup_cache_path(config, warmup_state, env_params, runner_state)

File of this warmup's result under --WARMUP_CACHE_DIR, or None if not caching.

The name hashes everything the warmup's result depends on: the environment parameters (static fields included), reset states and warmup keys, the warmup settings, the policy weights when the policy acts, and the xlron source code, so a code change never reuses an older result.

Source code in xlron/train/train_utils.py
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
def warmup_cache_path(config, warmup_state, env_params, runner_state) -> pathlib.Path | None:
    """File of this warmup's result under --WARMUP_CACHE_DIR, or None if not caching.

    The name hashes everything the warmup's result depends on: the environment
    parameters (static fields included), reset states and warmup keys, the warmup
    settings, the policy weights when the policy acts, and the xlron source code,
    so a code change never reuses an older result.
    """
    directory = config.get("WARMUP_CACHE_DIR")
    if not directory or not config.ENV_WARMUP_STEPS:
        return None
    digest = hashlib.sha256()
    for key in (
        "ENV_WARMUP_STEPS",
        "EVAL_HEURISTIC",
        "warmup_action_type",
        "path_heuristic",
        "warmup_path_heuristic",
        "NUM_ENVS",
    ):
        digest.update(f"{key}={config.get(key)!r}".encode())
    # Continuous operation sets max_requests to TOTAL_TIMESTEPS; any value beyond
    # the warmup gives the same warmup, so runs of any length share its result.
    if getattr(env_params, "max_requests", 0) > config.ENV_WARMUP_STEPS:
        env_params = env_params.replace(max_requests=-1)
    _fingerprint(digest, (warmup_state, env_params))
    policy_acts = not (
        config.EVAL_HEURISTIC or config.get("warmup_action_type") in ("heuristic", "random")
    )
    if policy_acts and runner_state is not None:
        _fingerprint(digest, eqx.filter(runner_state.model_params, eqx.is_array))
    source = pathlib.Path(__file__).resolve().parents[1]
    for path in sorted(source.rglob("*.py")):
        if not path.name.endswith("_test.py"):
            digest.update(str(path.relative_to(source)).encode())
            digest.update(path.read_bytes())
    return pathlib.Path(directory) / f"warmup-{digest.hexdigest()[:32]}.npz"

write_run_summary(summary, output_file=None, print_to_console=True)

Print and/or write a run summary.

Parameters:

Name Type Description Default
summary dict

The dict returned by build_run_summary().

required
output_file str | None

If not None, append as one JSON line to this file.

None
print_to_console bool

If True, print a human-readable summary to stdout.

True
Source code in xlron/train/train_utils.py
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
def write_run_summary(
    summary: dict,
    output_file: str | None = None,
    print_to_console: bool = True,
) -> None:
    """Print and/or write a run summary.

    Args:
        summary: The dict returned by build_run_summary().
        output_file: If not None, append as one JSON line to this file.
        print_to_console: If True, print a human-readable summary to stdout.
    """
    if print_to_console:
        print("\n" + "=" * 70)
        print("XLRON Run Summary")
        print("=" * 70)
        print(f"{'Run type:':<22s} {summary['run_type']}")
        print(f"{'Timestamp:':<22s} {summary['timestamp']}")
        if summary.get("timing"):
            t = summary["timing"]
            if t.get("startup_time_s") is not None:
                print(f"{'Total startup:':<22s} {t['startup_time_s']:.2f}s")
            if t.get("compilation_time_s") is not None:
                print(f"{'XLA compile/load:':<22s} {t['compilation_time_s']:.2f}s")
            if t.get("warmup_execution_time_s") is not None:
                print(f"{'Warmup execution:':<22s} {t['warmup_execution_time_s']:.2f}s")
            if t.get("execution_time_s") is not None:
                print(f"{'Execution time:':<22s} {t['execution_time_s']:.2f}s")
            if t.get("fps") is not None:
                print(f"{'FPS:':<22s} {t['fps']:.2f}")
        print("-" * 70)
        print("Config:")
        for k, v in summary["config"].items():
            print(f"  {k:<28s} {v}")
        print("-" * 70)
        print(f"{'Metric':<40s} {'Mean':>12s} {'Std':>12s} {'IQR Lower':>12s} {'IQR Upper':>12s}")
        print("-" * 70)
        for metric_name, stats in summary["metrics"].items():
            mean = stats.get("mean", float("nan"))
            std = stats.get("std", float("nan"))
            iqr_lower = stats.get("iqr_lower", float("nan"))
            iqr_upper = stats.get("iqr_upper", float("nan"))
            print(
                f"{metric_name:<40s} {mean:>12.5f} {std:>12.5f} {iqr_lower:>12.5f} {iqr_upper:>12.5f}"
            )
        print("=" * 70)

    if output_file:
        os.makedirs(os.path.dirname(output_file) or ".", exist_ok=True)
        with open(output_file, "a") as f:
            f.write(json.dumps(summary) + "\n")
        print(f"Run summary appended to {output_file}")

Models

ActorCriticMLP

Bases: Module

Actor-Critic MLP using Equinox.

Source code in xlron/models/mlp.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
273
class ActorCriticMLP(eqx.Module):
    """Actor-Critic MLP using Equinox."""

    actor: MLP
    critic: MLP
    activation_fn: Callable
    temperature: float

    def __init__(
        self,
        action_dim: int,
        input_dim: int,
        activation: str = "tanh",
        num_layers: int = 2,
        num_units: int = 64,
        layer_norm: bool = False,  # Not used for now, can add eqx.nn.LayerNorm later
        temperature: float = 1.0,
        dropout_rate: float = 0.0,
        deterministic: bool = True,
        *,
        key: Array,
    ):
        actor_key, critic_key = jax.random.split(key)
        self.activation_fn = select_activation(activation)
        self.temperature = temperature

        # Build actor layers (logits head init scale 0.01 for a near-uniform initial policy)
        actor_features = [num_units] * num_layers + [action_dim]
        self.actor = MLP(
            actor_features,
            input_dim,
            activation=activation,
            layer_norm=layer_norm,
            dropout_rate=dropout_rate,
            deterministic=deterministic,
            output_scale=0.01,
            key=actor_key,
        )
        critic_features = [num_units] * num_layers + [1]
        self.critic = MLP(
            critic_features,
            input_dim,
            activation=activation,
            layer_norm=layer_norm,
            dropout_rate=dropout_rate,
            deterministic=deterministic,
            output_scale=1.0,
            key=critic_key,
        )

    def __call__(self, x: Array, key: Optional[Array] = None) -> Tuple[distrax.Categorical, Array]:
        # Cast the (possibly low-precision under mixed precision) observation up to the NN compute
        # dtype so weights, activations and the optimizer stay at full precision for stability.
        x = x.astype(dtype_config.COMPUTE_DTYPE)
        # Actor forward pass
        actor_key, critic_key = jax.random.split(key) if key else (None, None)
        logits = self.actor(x, key=actor_key) / self.temperature
        # Cast outputs back to PARAMS_DTYPE (float32) so bf16 stays inside the model and the
        # downstream PPO math / f32 env-state stay float32 (see transformer model for rationale).
        action_dist = distrax.Categorical(logits=logits.astype(dtype_config.PARAMS_DTYPE))
        value = self.critic(x, key=critic_key).astype(dtype_config.PARAMS_DTYPE)
        return action_dist, jnp.squeeze(value, axis=-1)

    def sample_action(
        self,
        seed: chex.PRNGKey,
        dist: distrax.Categorical,
        log_prob: bool = False,
        deterministic: bool = False,
    ) -> Union[Array, Tuple[Array, Array]]:
        """Sample an action from the distribution"""
        action = dist.mode() if deterministic else dist.sample(seed=seed)
        if log_prob:
            return action, dist.log_prob(action)
        return action

sample_action(seed, dist, log_prob=False, deterministic=False)

Sample an action from the distribution

Source code in xlron/models/mlp.py
262
263
264
265
266
267
268
269
270
271
272
273
def sample_action(
    self,
    seed: chex.PRNGKey,
    dist: distrax.Categorical,
    log_prob: bool = False,
    deterministic: bool = False,
) -> Union[Array, Tuple[Array, Array]]:
    """Sample an action from the distribution"""
    action = dist.mode() if deterministic else dist.sample(seed=seed)
    if log_prob:
        return action, dist.log_prob(action)
    return action

LaunchPowerActorCriticMLP

Bases: Module

Actor-Critic MLP for launch power optimization.

Takes an observation of the current request + statistics on each of the K candidate paths. Makes K forward passes, one for each path, and outputs a distribution over power levels for each path.

Source code in xlron/models/mlp.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
class LaunchPowerActorCriticMLP(eqx.Module):
    """Actor-Critic MLP for launch power optimization.

    Takes an observation of the current request + statistics on each of the K candidate paths.
    Makes K forward passes, one for each path, and outputs a distribution over power levels for each path.
    """

    # Actor trunk and discrete head
    actor_layers: tuple
    actor_output: Optional[eqx.nn.Linear]

    # For continuous action space (Beta distribution)
    alpha_out: Optional[eqx.nn.Linear]
    beta_out: Optional[eqx.nn.Linear]

    # Critic trunk and value head
    critic_layers: tuple
    critic_output: eqx.nn.Linear

    # Static configuration
    activation: str = eqx.field(static=True)
    layer_norm: bool = eqx.field(static=True)
    min_power_dbm: float = eqx.field(static=True)
    max_power_dbm: float = eqx.field(static=True)
    step_power_dbm: float = eqx.field(static=True)
    discrete: bool = eqx.field(static=True)
    temperature: float = eqx.field(static=True)
    k_paths: int = eqx.field(static=True)
    num_base_features: int = eqx.field(static=True)
    num_path_features: int = eqx.field(static=True)
    min_concentration: float = eqx.field(static=True)
    max_concentration: float = eqx.field(static=True)
    epsilon: float = eqx.field(static=True)

    def __init__(
        self,
        action_dim: Sequence[int],
        input_dim: int,
        activation: str = "tanh",
        num_layers: int = 2,
        num_units: int = 64,
        layer_norm: bool = False,
        min_power_dbm: float = 0.0,
        max_power_dbm: float = 2.0,
        step_power_dbm: float = 0.1,
        discrete: bool = True,
        temperature: float = 1.0,
        k_paths: int = 5,
        num_base_features: int = 4,
        num_path_features: int = 7,
        min_concentration: float = 0.1,
        max_concentration: float = 20.0,
        epsilon: float = 1e-6,
        *,
        key: Array,
    ):
        super().__init__()
        self.activation = activation
        self.layer_norm = layer_norm
        self.min_power_dbm = min_power_dbm
        self.max_power_dbm = max_power_dbm
        self.step_power_dbm = step_power_dbm
        self.discrete = discrete
        self.temperature = temperature
        self.k_paths = k_paths
        self.num_base_features = num_base_features
        self.num_path_features = num_path_features
        self.min_concentration = min_concentration
        self.max_concentration = max_concentration
        self.epsilon = epsilon

        actor_key, critic_key, output_key = jax.random.split(key, 3)

        # Build actor layers
        actor_keys = jax.random.split(actor_key, num_layers)
        actor_layers_list = []
        # Input is base features + path features
        current_in = num_base_features + num_path_features
        for i in range(num_layers):
            linear = make_linear_with_orthogonal_init(
                current_in, num_units, actor_keys[i], scale=np.sqrt(2)
            )
            actor_layers_list.append(linear)
            if layer_norm:
                actor_layers_list.append(eqx.nn.LayerNorm(num_units))
            current_in = num_units
        self.actor_layers = tuple(actor_layers_list)

        # Actor output
        out_key1, out_key2, out_key3 = jax.random.split(output_key, 3)
        if discrete:
            num_power_levels = int((max_power_dbm - min_power_dbm) / step_power_dbm) + 1
            self.actor_output = make_linear_with_orthogonal_init(
                num_units, num_power_levels, out_key1, scale=0.01
            )
            self.alpha_out = None
            self.beta_out = None
        else:
            self.actor_output = None  # Not used for continuous
            self.alpha_out = make_linear_with_orthogonal_init(num_units, 1, out_key2, scale=0.01)
            self.beta_out = make_linear_with_orthogonal_init(num_units, 1, out_key3, scale=0.01)

        # Build critic layers (take the full observation: base + all K paths' features)
        critic_trunk_key, critic_out_key = jax.random.split(critic_key)
        critic_keys = jax.random.split(critic_trunk_key, num_layers)
        critic_layers_list = []
        current_in = num_base_features + k_paths * num_path_features
        for i in range(num_layers):
            linear = make_linear_with_orthogonal_init(
                current_in, num_units, critic_keys[i], scale=np.sqrt(2)
            )
            critic_layers_list.append(linear)
            if layer_norm:
                critic_layers_list.append(eqx.nn.LayerNorm(num_units))
            current_in = num_units
        self.critic_layers = tuple(critic_layers_list)
        self.critic_output = make_linear_with_orthogonal_init(
            num_units, 1, critic_out_key, scale=1.0
        )

    @property
    def num_power_levels(self):
        """Calculate number of power levels dynamically"""
        return int((self.max_power_dbm - self.min_power_dbm) / self.step_power_dbm) + 1

    @property
    def power_levels(self):
        """Calculate power levels dynamically"""
        return jnp.linspace(
            self.min_power_dbm,
            self.max_power_dbm,
            self.num_power_levels,
            dtype=dtype_config.SMALL_FLOAT_DTYPE,
        )

    def _activate(self, x):
        return select_activation(self.activation)(x)

    def _forward_layers(self, x, layers):
        for layer in layers:
            x = layer(x)
            if isinstance(layer, eqx.nn.Linear):
                x = self._activate(x)
        return x

    def __call__(self, x: Array) -> Tuple[Tuple[None, distrax.Distribution], Array]:
        # Cast the (possibly low-precision under mixed precision) observation up to the NN compute
        # dtype so weights, activations and the optimizer stay at full precision for stability.
        x = x.astype(dtype_config.COMPUTE_DTYPE)

        # Process each path
        def process_path(i):
            base = x[: self.num_base_features]
            path = jax.lax.dynamic_slice(
                x, (self.num_base_features + i * self.num_path_features,), (self.num_path_features,)
            )
            features = jnp.concatenate([base, path])
            actor_hidden = self._forward_layers(features, self.actor_layers)

            if self.discrete:
                return self.actor_output(actor_hidden) / self.temperature
            else:
                alpha = self.min_concentration + jax.nn.softplus(self.alpha_out(actor_hidden)) * (
                    self.max_concentration - self.min_concentration
                )
                beta = self.min_concentration + jax.nn.softplus(self.beta_out(actor_hidden)) * (
                    self.max_concentration - self.min_concentration
                )
                return jnp.concatenate([alpha, beta])

        # Use vmap instead of scan for simpler Equinox pattern
        dist_params = jax.vmap(process_path)(
            jnp.arange(self.k_paths, dtype=dtype_config.INDEX_DTYPE)
        )

        # Critic forward pass
        critic_hidden = self._forward_layers(x, self.critic_layers)
        value = jnp.squeeze(self.critic_output(critic_hidden), axis=-1)

        # Cast outputs back to PARAMS_DTYPE (float32) so bf16 stays inside the model (see
        # ActorCriticMLP for rationale).
        dist_params = dist_params.astype(dtype_config.PARAMS_DTYPE)
        value = value.astype(dtype_config.PARAMS_DTYPE)

        # Create distribution
        if self.discrete:
            dist = distrax.Categorical(logits=dist_params)
        else:
            alpha = dist_params[:, 0]
            beta = dist_params[:, 1]
            dist = distrax.Beta(alpha, beta)

        return (None, dist), value

    def sample_action(self, seed, dist, log_prob=False, deterministic=False):
        """Sample an action and convert to power level"""
        if self.discrete:
            if deterministic:
                raw_action = dist.mode()
            else:
                raw_action = dist.sample(seed=seed)
            # (k_paths,) to match the carried launch_power_array shape
            processed_action = self.power_levels[raw_action].reshape((self.k_paths,))
        else:
            if deterministic:
                mean = dist.alpha / (dist.alpha + dist.beta)
                raw_action = jnp.clip(mean, self.epsilon, 1.0 - self.epsilon)
            else:
                raw_action = jnp.clip(dist.sample(seed=seed), self.epsilon, 1.0 - self.epsilon)
            processed_action = self.min_power_dbm + raw_action * (
                self.max_power_dbm - self.min_power_dbm
            )
        processed_action = from_dbm(processed_action)
        if log_prob:
            return processed_action, dist.log_prob(jnp.squeeze(raw_action))
        return processed_action

    def get_action_probs(self, dist):
        """Get probabilities for discrete case or pdf for continuous case"""
        if self.discrete:
            return dist.probs
        else:
            x = jnp.linspace(0, 1, 100)
            return dist.prob(x)

num_power_levels property

Calculate number of power levels dynamically

power_levels property

Calculate power levels dynamically

get_action_probs(dist)

Get probabilities for discrete case or pdf for continuous case

Source code in xlron/models/mlp.py
493
494
495
496
497
498
499
def get_action_probs(self, dist):
    """Get probabilities for discrete case or pdf for continuous case"""
    if self.discrete:
        return dist.probs
    else:
        x = jnp.linspace(0, 1, 100)
        return dist.prob(x)

sample_action(seed, dist, log_prob=False, deterministic=False)

Sample an action and convert to power level

Source code in xlron/models/mlp.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def sample_action(self, seed, dist, log_prob=False, deterministic=False):
    """Sample an action and convert to power level"""
    if self.discrete:
        if deterministic:
            raw_action = dist.mode()
        else:
            raw_action = dist.sample(seed=seed)
        # (k_paths,) to match the carried launch_power_array shape
        processed_action = self.power_levels[raw_action].reshape((self.k_paths,))
    else:
        if deterministic:
            mean = dist.alpha / (dist.alpha + dist.beta)
            raw_action = jnp.clip(mean, self.epsilon, 1.0 - self.epsilon)
        else:
            raw_action = jnp.clip(dist.sample(seed=seed), self.epsilon, 1.0 - self.epsilon)
        processed_action = self.min_power_dbm + raw_action * (
            self.max_power_dbm - self.min_power_dbm
        )
    processed_action = from_dbm(processed_action)
    if log_prob:
        return processed_action, dist.log_prob(jnp.squeeze(raw_action))
    return processed_action

MLP

Bases: Module

Simple MLP module using Equinox.

Source code in xlron/models/mlp.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
194
195
196
class MLP(eqx.Module):
    """Simple MLP module using Equinox."""

    layers: tuple
    activation_fn: Callable = eqx.field(static=True)
    dropout_rate: float = eqx.field(static=True)
    deterministic: bool = eqx.field(static=True)

    def __init__(
        self,
        features: Sequence[int],
        in_features: int,
        activation: str = "tanh",
        dropout_rate: float = 0.0,
        deterministic: bool = True,
        layer_norm: bool = False,
        output_scale: float = np.sqrt(2),
        *,
        key: Array,
    ):
        self.activation_fn = select_activation(activation)
        self.dropout_rate = dropout_rate
        self.deterministic = deterministic

        layers_list = []
        keys = jax.random.split(key, len(features))
        current_in = in_features

        for i, out_features in enumerate(features):
            # Hidden layers use the standard sqrt(2) orthogonal gain; the output layer
            # uses output_scale (e.g. 0.01 for a policy head, 1.0 for a value head).
            scale = output_scale if i == len(features) - 1 else np.sqrt(2)
            linear = make_linear_with_orthogonal_init(
                current_in, out_features, keys[i], scale=scale
            )
            layers_list.append(linear)
            if layer_norm and i < len(features) - 1:
                layers_list.append(eqx.nn.LayerNorm(out_features))
            current_in = out_features

        self.layers = tuple(layers_list)

    def __call__(self, x: Array, *, key: Optional[Array] = None) -> Array:
        for i, layer in enumerate(self.layers):
            if isinstance(layer, eqx.nn.Linear):
                x = layer(x)
                # Apply activation for all but the last linear layer
                if i < len(self.layers) - 1:
                    x = self.activation_fn(x)
                    if not self.deterministic and self.dropout_rate > 0 and key is not None:
                        key, subkey = jax.random.split(key)
                        x = eqx.nn.Dropout(self.dropout_rate)(x, key=subkey)
            elif isinstance(layer, eqx.nn.LayerNorm):
                x = layer(x)
        return x

bfloat16_safe_orthogonal(scale=1.0)

Returns an orthogonal initializer that is safe for bfloat16.

Source code in xlron/models/mlp.py
104
105
106
107
108
109
110
def bfloat16_safe_orthogonal(scale: float = 1.0) -> Callable:
    """Returns an orthogonal initializer that is safe for bfloat16."""

    def init(key: Array, shape: Sequence[int], dtype: jnp.dtype = jnp.float32) -> Array:
        return orthogonal_init(key, tuple(shape), scale=scale, dtype=dtype)

    return init

constant(value)

Returns a constant initializer.

Source code in xlron/models/mlp.py
113
114
115
116
117
118
119
def constant(value: float) -> Callable:
    """Returns a constant initializer."""

    def init(key: Array, shape: Sequence[int], dtype: jnp.dtype = jnp.float32) -> Array:
        return jnp.full(shape, value, dtype=dtype)

    return init

crelu(x)

Computes the Concatenated ReLU (CReLU) activation function.

Source code in xlron/models/mlp.py
66
67
68
69
def crelu(x: ArrayLike) -> Array:
    """Computes the Concatenated ReLU (CReLU) activation function."""
    x = jnp.concatenate([x, -x], axis=-1)
    return jax.nn.relu(x)

make_linear_with_orthogonal_init(in_features, out_features, key, scale=1.0, dtype=None)

Create a Linear layer with orthogonal initialization.

Source code in xlron/models/mlp.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def make_linear_with_orthogonal_init(
    in_features: int,
    out_features: int,
    key: Array,
    scale: float = 1.0,
    dtype: jnp.dtype = None,
) -> eqx.nn.Linear:
    """Create a Linear layer with orthogonal initialization."""
    if dtype is None:
        dtype = dtype_config.PARAMS_DTYPE

    key1, key2 = jax.random.split(key)
    weight = orthogonal_init(key1, (out_features, in_features), scale=scale, dtype=dtype)
    bias = jnp.zeros(out_features, dtype=dtype)

    linear = eqx.nn.Linear(in_features, out_features, key=key2, dtype=dtype)
    linear = eqx.tree_at(lambda layer: (layer.weight, layer.bias), linear, (weight, bias))
    return linear

orthogonal_init(key, shape, scale=1.0, dtype=jnp.float32)

Orthogonal initializer that is safe for bfloat16 and other dtypes. Based on JAX/Flax orthogonal initializer.

Parameters:

Name Type Description Default
key Array

PRNGKey for initialization

required
shape Tuple[int, ...]

Shape of the weight matrix

required
scale float

Scaling factor for the orthogonal matrix

1.0
dtype dtype

Target dtype (will init in float32 then cast)

float32

Returns:

Type Description
Array

Orthogonally initialized weight matrix

Source code in xlron/models/mlp.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
def orthogonal_init(
    key: Array, shape: Tuple[int, ...], scale: float = 1.0, dtype: jnp.dtype = jnp.float32
) -> Array:
    """
    Orthogonal initializer that is safe for bfloat16 and other dtypes.
    Based on JAX/Flax orthogonal initializer.

    Args:
        key: PRNGKey for initialization
        shape: Shape of the weight matrix
        scale: Scaling factor for the orthogonal matrix
        dtype: Target dtype (will init in float32 then cast)

    Returns:
        Orthogonally initialized weight matrix
    """
    # Always initialize in float32 to avoid dtype issues
    if len(shape) < 2:
        raise ValueError("Orthogonal initialization requires at least 2D shape")

    num_rows, num_cols = shape[-2], shape[-1]
    flat_shape = (max(num_rows, num_cols), min(num_rows, num_cols))

    # Generate random matrix
    a = jax.random.normal(key, flat_shape, dtype=jnp.float32)

    # QR decomposition
    q, r = jnp.linalg.qr(a)
    d = jnp.diag(r)
    q = q * jnp.sign(d)

    # If num_rows < num_cols, we need to transpose
    if num_rows < num_cols:
        q = q.T

    # Take the slice we need
    q = q[:num_rows, :num_cols]

    # Reshape if needed
    if len(shape) > 2:
        q = q.reshape(shape)

    # Scale and cast
    return (scale * q).astype(dtype)

relu2(x)

Squared ReLU, max(x, 0)^2 (So et al. 2021, "Primer").

Source code in xlron/models/mlp.py
72
73
74
def relu2(x: ArrayLike) -> Array:
    """Squared ReLU, max(x, 0)^2 (So et al. 2021, "Primer")."""
    return jnp.square(jax.nn.relu(x))

relu3(x)

Cubed ReLU, max(x, 0)^3.

Source code in xlron/models/mlp.py
77
78
79
80
def relu3(x: ArrayLike) -> Array:
    """Cubed ReLU, max(x, 0)^3."""
    r = jax.nn.relu(x)
    return r * r * r

select_activation(activation)

Selects the activation function based on the provided string.

Source code in xlron/models/mlp.py
 94
 95
 96
 97
 98
 99
100
101
def select_activation(activation: str) -> Callable[[ArrayLike], Array]:
    """Selects the activation function based on the provided string."""
    try:
        return ACTIVATIONS[activation]
    except KeyError:
        raise ValueError(
            f"Unknown activation {activation!r}; expected one of {sorted(ACTIVATIONS)}"
        ) from None

ActorCriticGNN

Bases: Module

Combined Actor-Critic GNN model.

Source code in xlron/models/gnn.py
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
class ActorCriticGNN(eqx.Module):
    """Combined Actor-Critic GNN model."""

    actor: ActorGNN
    critic: CriticGNN

    # Static configuration
    vmap: bool = eqx.field(static=True)
    min_power_dbm: float = eqx.field(static=True)
    max_power_dbm: float = eqx.field(static=True)
    step_power_dbm: float = eqx.field(static=True)
    discrete: bool = eqx.field(static=True)
    epsilon: float = eqx.field(static=True)
    output_path: bool = eqx.field(static=True)
    output_power: bool = eqx.field(static=True)

    def __init__(
        self,
        input_edge_features: int,
        input_node_features: int,
        input_global_features: int,
        activation: str = "tanh",
        num_layers: int = 2,
        num_units: int = 64,
        message_passing_steps: int = 1,
        mlp_layers: int = None,
        mlp_latent: int = None,
        edge_embedding_size: int = 128,
        edge_mlp_layers: int = 3,
        edge_mlp_latent: int = 128,
        edge_output_size_actor: int = 1,
        edge_output_size_critic: int = 1,
        global_embedding_size: int = 8,
        global_mlp_layers: int = 0,
        global_mlp_latent: int = 0,
        global_output_size_actor: int = 0,
        global_output_size_critic: int = 0,
        node_embedding_size: int = 16,
        node_mlp_layers: int = 2,
        node_mlp_latent: int = 128,
        node_output_size_actor: int = 0,
        node_output_size_critic: int = 0,
        attn_mlp_layers: int = 2,
        attn_mlp_latent: int = 128,
        gnn_mlp_layers: int = 1,
        use_attention: bool = True,
        normalise_by_link_length: bool = True,
        gnn_layer_norm: bool = True,
        mlp_layer_norm: bool = False,
        vmap: bool = True,
        temperature: float = 1.0,
        min_power_dbm: float = 0.0,
        max_power_dbm: float = 2.0,
        step_power_dbm: float = 0.1,
        discrete: bool = True,
        min_concentration: float = 0.1,
        max_concentration: float = 20.0,
        epsilon: float = 1e-6,
        output_path: bool = True,
        output_power: bool = True,
        vone_heads: bool = False,
        k_paths: int = 0,
        *,
        key: Array,
    ):
        assert edge_output_size_actor > 0
        assert edge_output_size_critic + global_output_size_critic > 0

        self.vmap = vmap
        self.min_power_dbm = min_power_dbm
        self.max_power_dbm = max_power_dbm
        self.step_power_dbm = step_power_dbm
        self.discrete = discrete
        self.epsilon = epsilon
        self.output_path = output_path
        self.output_power = output_power

        actor_key, critic_key = jax.random.split(key)

        self.actor = ActorGNN(
            input_edge_features=input_edge_features,
            input_node_features=input_node_features,
            input_global_features=input_global_features,
            num_layers=num_layers,
            num_units=num_units,
            message_passing_steps=message_passing_steps,
            mlp_layers=mlp_layers,
            mlp_latent=mlp_latent,
            edge_embedding_size=edge_embedding_size,
            edge_mlp_layers=edge_mlp_layers,
            edge_mlp_latent=edge_mlp_latent,
            edge_output_size=edge_output_size_actor,
            global_embedding_size=global_embedding_size,
            global_mlp_layers=global_mlp_layers,
            global_mlp_latent=global_mlp_latent,
            global_output_size=global_output_size_actor,
            node_embedding_size=node_embedding_size,
            node_mlp_layers=node_mlp_layers,
            node_mlp_latent=node_mlp_latent,
            node_output_size=node_output_size_actor,
            attn_mlp_layers=attn_mlp_layers,
            attn_mlp_latent=attn_mlp_latent,
            use_attention=use_attention,
            normalise_by_link_length=normalise_by_link_length,
            gnn_layer_norm=gnn_layer_norm,
            mlp_layer_norm=mlp_layer_norm,
            temperature=temperature,
            min_power_dbm=min_power_dbm,
            max_power_dbm=max_power_dbm,
            step_power_dbm=step_power_dbm,
            discrete=discrete,
            min_concentration=min_concentration,
            max_concentration=max_concentration,
            epsilon=epsilon,
            vone_heads=vone_heads,
            k_paths=k_paths,
            key=actor_key,
        )

        self.critic = CriticGNN(
            input_edge_features=input_edge_features,
            input_node_features=input_node_features,
            input_global_features=input_global_features,
            activation=activation,
            num_layers=num_layers,
            num_units=num_units,
            message_passing_steps=message_passing_steps,
            mlp_layers=mlp_layers,
            mlp_latent=mlp_latent,
            edge_embedding_size=edge_embedding_size,
            edge_mlp_layers=edge_mlp_layers,
            edge_mlp_latent=edge_mlp_latent,
            edge_output_size=edge_output_size_critic,
            global_embedding_size=global_embedding_size,
            global_mlp_layers=global_mlp_layers,
            global_mlp_latent=global_mlp_latent,
            global_output_size=global_output_size_critic,
            node_embedding_size=node_embedding_size,
            node_mlp_layers=node_mlp_layers,
            node_mlp_latent=node_mlp_latent,
            node_output_size=node_output_size_critic,
            attn_mlp_layers=attn_mlp_layers,
            attn_mlp_latent=attn_mlp_latent,
            use_attention=use_attention,
            normalise_by_link_length=normalise_by_link_length,
            gnn_layer_norm=gnn_layer_norm,
            mlp_layer_norm=mlp_layer_norm,
            key=critic_key,
        )

    @property
    def num_power_levels(self):
        return int((self.max_power_dbm - self.min_power_dbm) / self.step_power_dbm) + 1

    @property
    def power_levels(self):
        return jnp.linspace(
            self.min_power_dbm,
            self.max_power_dbm,
            self.num_power_levels,
            dtype=dtype_config.LARGE_FLOAT_DTYPE,
        )

    def __call__(self, state: EnvState, params: EnvParams):
        if self.vmap:
            actor_fn = jax.vmap(self.actor, in_axes=(0, None))
            critic_fn = jax.vmap(self.critic, in_axes=(0, None))
        else:
            actor_fn = self.actor
            critic_fn = self.critic

        actor_out = actor_fn(state, params)
        critic_out = critic_fn(state, params)
        return actor_out, critic_out

    def sample_action_path(self, seed, dist, log_prob=False, deterministic=False):
        """Sample an action from the distribution."""
        action = (
            dist.mode().astype(dtype_config.INDEX_DTYPE)
            if deterministic
            else dist.sample(seed=seed)
        )
        if log_prob:
            return action, dist.log_prob(action)
        return action

    def sample_action_power(self, seed, dist, log_prob=False, deterministic=False):
        """Sample an action and convert to power level"""
        if self.discrete:
            if deterministic:
                raw_action = dist.mode()
            else:
                raw_action = dist.sample(seed=seed)
            processed_action = self.power_levels[raw_action]
        else:
            if deterministic:
                mean = dist.alpha / (dist.alpha + dist.beta)
                raw_action = jnp.clip(mean, self.epsilon, 1.0 - self.epsilon)
            else:
                raw_action = jnp.clip(dist.sample(seed=seed), self.epsilon, 1.0 - self.epsilon)
            processed_action = self.min_power_dbm + raw_action * (
                self.max_power_dbm - self.min_power_dbm
            )
        processed_action = from_dbm(processed_action)
        if log_prob:
            return processed_action, dist.log_prob(raw_action)
        return processed_action

    def sample_action_path_power(self, seed, dist, log_prob=False, deterministic=False):
        """Sample an action from the distributions."""
        # Independent keys per draw: reusing the same key couples the path and power samples,
        # so the joint would not be the product of marginals that the summed log_prob assumes.
        path_seed, power_seed = jax.random.split(seed)
        path_action = self.sample_action_path(
            path_seed, dist[0], log_prob=log_prob, deterministic=deterministic
        )
        power_action = self.sample_action_power(
            power_seed, dist[1], log_prob=log_prob, deterministic=deterministic
        )
        if log_prob:
            return path_action[0], power_action[0], path_action[1] + power_action[1]
        return path_action, power_action

    def sample_action(self, seed, dist, log_prob=False, deterministic=False):
        """Sample an action from the distributions."""
        if self.output_path and self.output_power:
            return self.sample_action_path_power(
                seed, dist, log_prob=log_prob, deterministic=deterministic
            )
        elif self.output_path:
            return self.sample_action_path(
                seed, dist, log_prob=log_prob, deterministic=deterministic
            )
        elif self.output_power:
            return self.sample_action_power(
                seed, dist, log_prob=log_prob, deterministic=deterministic
            )
        else:
            raise ValueError("No action type specified for sampling.")

sample_action(seed, dist, log_prob=False, deterministic=False)

Sample an action from the distributions.

Source code in xlron/models/gnn.py
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
def sample_action(self, seed, dist, log_prob=False, deterministic=False):
    """Sample an action from the distributions."""
    if self.output_path and self.output_power:
        return self.sample_action_path_power(
            seed, dist, log_prob=log_prob, deterministic=deterministic
        )
    elif self.output_path:
        return self.sample_action_path(
            seed, dist, log_prob=log_prob, deterministic=deterministic
        )
    elif self.output_power:
        return self.sample_action_power(
            seed, dist, log_prob=log_prob, deterministic=deterministic
        )
    else:
        raise ValueError("No action type specified for sampling.")

sample_action_path(seed, dist, log_prob=False, deterministic=False)

Sample an action from the distribution.

Source code in xlron/models/gnn.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
def sample_action_path(self, seed, dist, log_prob=False, deterministic=False):
    """Sample an action from the distribution."""
    action = (
        dist.mode().astype(dtype_config.INDEX_DTYPE)
        if deterministic
        else dist.sample(seed=seed)
    )
    if log_prob:
        return action, dist.log_prob(action)
    return action

sample_action_path_power(seed, dist, log_prob=False, deterministic=False)

Sample an action from the distributions.

Source code in xlron/models/gnn.py
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
def sample_action_path_power(self, seed, dist, log_prob=False, deterministic=False):
    """Sample an action from the distributions."""
    # Independent keys per draw: reusing the same key couples the path and power samples,
    # so the joint would not be the product of marginals that the summed log_prob assumes.
    path_seed, power_seed = jax.random.split(seed)
    path_action = self.sample_action_path(
        path_seed, dist[0], log_prob=log_prob, deterministic=deterministic
    )
    power_action = self.sample_action_power(
        power_seed, dist[1], log_prob=log_prob, deterministic=deterministic
    )
    if log_prob:
        return path_action[0], power_action[0], path_action[1] + power_action[1]
    return path_action, power_action

sample_action_power(seed, dist, log_prob=False, deterministic=False)

Sample an action and convert to power level

Source code in xlron/models/gnn.py
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
def sample_action_power(self, seed, dist, log_prob=False, deterministic=False):
    """Sample an action and convert to power level"""
    if self.discrete:
        if deterministic:
            raw_action = dist.mode()
        else:
            raw_action = dist.sample(seed=seed)
        processed_action = self.power_levels[raw_action]
    else:
        if deterministic:
            mean = dist.alpha / (dist.alpha + dist.beta)
            raw_action = jnp.clip(mean, self.epsilon, 1.0 - self.epsilon)
        else:
            raw_action = jnp.clip(dist.sample(seed=seed), self.epsilon, 1.0 - self.epsilon)
        processed_action = self.min_power_dbm + raw_action * (
            self.max_power_dbm - self.min_power_dbm
        )
    processed_action = from_dbm(processed_action)
    if log_prob:
        return processed_action, dist.log_prob(raw_action)
    return processed_action

ActorGNN

Bases: Module

Actor network using GNN for processing graph state.

Source code in xlron/models/gnn.py
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
class ActorGNN(eqx.Module):
    """Actor network using GNN for processing graph state."""

    graph_net: GraphNet
    power_mlp: Optional[eqx.nn.MLP]
    vone_path_mlp: Optional[eqx.nn.MLP]

    # Static configuration
    activation: str = eqx.field(static=True)
    edge_output_size: int = eqx.field(static=True)
    global_output_size: int = eqx.field(static=True)
    normalise_by_link_length: bool = eqx.field(static=True)
    temperature: float = eqx.field(static=True)
    min_power_dbm: float = eqx.field(static=True)
    max_power_dbm: float = eqx.field(static=True)
    step_power_dbm: float = eqx.field(static=True)
    discrete: bool = eqx.field(static=True)
    min_concentration: float = eqx.field(static=True)
    max_concentration: float = eqx.field(static=True)
    epsilon: float = eqx.field(static=True)

    def __init__(
        self,
        input_edge_features: int,
        input_node_features: int,
        input_global_features: int,
        activation: str = "tanh",
        num_layers: int = 2,
        num_units: int = 64,
        mlp_layers: int = None,
        mlp_latent: int = None,
        edge_embedding_size: int = 128,
        edge_mlp_layers: int = 3,
        edge_mlp_latent: int = 128,
        edge_output_size: int = 0,
        global_embedding_size: int = 8,
        global_mlp_layers: int = 0,
        global_mlp_latent: int = 0,
        global_output_size: int = 0,
        node_embedding_size: int = 16,
        node_mlp_layers: int = 2,
        node_mlp_latent: int = 128,
        node_output_size: int = 0,
        attn_mlp_layers: int = 2,
        attn_mlp_latent: int = 128,
        dropout_rate: float = 0,
        deterministic: bool = False,
        message_passing_steps: int = 1,
        use_attention: bool = True,
        normalise_by_link_length: bool = True,
        gnn_layer_norm: bool = True,
        mlp_layer_norm: bool = False,
        temperature: float = 1.0,
        min_power_dbm: float = 0.0,
        max_power_dbm: float = 2.0,
        step_power_dbm: float = 0.1,
        discrete: bool = True,
        min_concentration: float = 0.1,
        max_concentration: float = 20.0,
        epsilon: float = 1e-6,
        vone_heads: bool = False,
        k_paths: int = 0,
        *,
        key: Array,
    ):
        self.activation = activation
        self.edge_output_size = edge_output_size
        self.global_output_size = global_output_size
        self.normalise_by_link_length = normalise_by_link_length
        self.temperature = temperature
        self.min_power_dbm = min_power_dbm
        self.max_power_dbm = max_power_dbm
        self.step_power_dbm = step_power_dbm
        self.discrete = discrete
        self.min_concentration = min_concentration
        self.max_concentration = max_concentration
        self.epsilon = epsilon

        gnn_key, mlp_key, vone_key = jax.random.split(key, 3)

        self.graph_net = GraphNet(
            input_edge_features=input_edge_features,
            input_node_features=input_node_features,
            input_global_features=input_global_features,
            message_passing_steps=message_passing_steps,
            mlp_layers=mlp_layers,
            mlp_latent=mlp_latent,
            edge_embedding_size=edge_embedding_size,
            edge_mlp_layers=edge_mlp_layers,
            edge_mlp_latent=edge_mlp_latent,
            edge_output_size=edge_output_size,
            global_embedding_size=global_embedding_size,
            global_mlp_layers=global_mlp_layers,
            global_mlp_latent=global_mlp_latent,
            global_output_size=global_output_size,
            node_embedding_size=node_embedding_size,
            node_mlp_layers=node_mlp_layers,
            node_mlp_latent=node_mlp_latent,
            node_output_size=node_output_size,
            attn_mlp_layers=attn_mlp_layers,
            attn_mlp_latent=attn_mlp_latent,
            dropout_rate=dropout_rate,
            use_attention=use_attention,
            gnn_layer_norm=gnn_layer_norm,
            mlp_layer_norm=mlp_layer_norm,
            deterministic=deterministic,
            key=gnn_key,
        )

        # Power MLP
        num_power_levels = int((max_power_dbm - min_power_dbm) / step_power_dbm) + 1
        output_size = num_power_levels if discrete else 2
        edge_feat_size = edge_output_size if edge_output_size > 0 else edge_embedding_size

        self.power_mlp = eqx.nn.MLP(
            in_size=edge_feat_size,
            out_size=output_size,
            width_size=num_units,
            depth=num_layers,
            activation=select_activation(activation),
            key=mlp_key,
        )

        # VONE per-head readout. The path-slot head cannot be indexed by (source, dest)
        # like the RSA readout: VONE samples the physical source/dest nodes downstream
        # from the node heads, so at model-call time no (s, d) pair exists yet (the MLP
        # baseline has the same property). Instead, an MLP over mean-pooled edge features
        # emits the k_paths * edge_output_size path-slot logits; source/dest logits come
        # from the node decoder (node_output_size must be 2: [source col | dest col]).
        if vone_heads:
            assert k_paths > 0, "k_paths must be set for the VONE path-slot head"
            assert node_output_size == 2, (
                "VONE heads need node_output_size == 2 (source/dest logit columns)"
            )
            self.vone_path_mlp = eqx.nn.MLP(
                in_size=edge_feat_size,
                out_size=k_paths * edge_output_size,
                width_size=num_units,
                depth=num_layers,
                activation=select_activation(activation),
                key=vone_key,
            )
        else:
            self.vone_path_mlp = None

    @property
    def num_power_levels(self):
        return int((self.max_power_dbm - self.min_power_dbm) / self.step_power_dbm) + 1

    @property
    def power_levels(self):
        return jnp.linspace(
            self.min_power_dbm,
            self.max_power_dbm,
            self.num_power_levels,
            dtype=dtype_config.SMALL_FLOAT_DTYPE,
        )

    def __call__(
        self, state: EnvState, params: EnvParams
    ) -> distrax.Distribution | Tuple[distrax.Distribution, Optional[distrax.Distribution]]:
        processed_graph = self.graph_net(state.graph)

        # Index edge features
        edge_features = (
            processed_graph.edges
            if params.directed_graph
            else processed_graph.edges[: len(processed_graph.edges) // 2]
        )
        if self.normalise_by_link_length:
            edge_features = edge_features * (
                params.link_length_array / jnp.sum(params.link_length_array, promote_integers=False)
            )

        if params.__class__.__name__ == "VONEEnvParams":
            # VONE per-head readout, laid out to match the slicing in select_action /
            # _loss_fn: [source(num_nodes) | dest(num_nodes) | path-slot(k * ceil(S/agg))
            # | trailing no-op]. VONE's request row 0 holds node-capacity request values,
            # not physical node indices, so the RSA (source, dest)-indexed path readout
            # below is meaningless here; the physical source/dest are sampled downstream
            # from the node heads.
            assert self.vone_path_mlp is not None, (
                "VONE requires ActorGNN built with vone_heads=True (see init_network)"
            )
            node_logits = processed_graph.nodes  # (num_nodes, 2) via node decoder
            source_logits = node_logits[:, 0]
            dest_logits = node_logits[:, 1]
            # Mean-pool edges for scale-stable MLP input (no (s, d) to select a path by)
            path_slot_logits = self.vone_path_mlp(jnp.mean(edge_features, axis=0))
            logits = jnp.concatenate([source_logits, dest_logits, path_slot_logits])
            if params.include_no_op:
                logits = jnp.hstack([logits, jnp.array([-1e4])])
            return distrax.Categorical(logits=logits / self.temperature)

        # Get current request
        nodes_sd, requested_bw = read_rsa_request(state.request_array)

        def get_path_features(i):
            return get_path_slots(edge_features, params, nodes_sd, i, agg_func="sum")

        path_action_logits = jax.vmap(get_path_features)(jnp.arange(params.k_paths)).reshape((-1,))
        if params.include_no_op:
            path_action_logits = jnp.hstack([path_action_logits, jnp.array([-1e4])])
        path_action_logits = jnp.reshape(path_action_logits, (-1,)) / self.temperature
        path_action_dist = distrax.Categorical(logits=path_action_logits)

        power_action_dist = None
        # Only output a launch-power distribution when the RL agent controls launch power.
        # launch_power_type is a static (pytree_node=False) str field on GNModelEnvParams,
        # so this branch is resolved at trace time. With fixed/tabular/scaled launch power,
        # downstream select_action/_loss_fn expect a bare path distribution.
        if (
            params.__class__.__name__ in ("RSAGNModelEnvParams", "RMSAGNModelEnvParams")
            and getattr(params, "launch_power_type", None) == "rl"
        ):
            if self.global_output_size > 0:
                power_logits = processed_graph.globals.reshape((-1,)) / self.temperature  # ty: ignore[unresolved-attribute]
            else:

                def get_power_path_features(i):
                    return get_path_slots(edge_features, params, nodes_sd, i, agg_func="sum")

                path_feature_batch = jax.vmap(get_power_path_features)(jnp.arange(params.k_paths))
                power_logits = jax.vmap(self.power_mlp)(path_feature_batch)

            if self.discrete:
                power_action_dist = distrax.Categorical(logits=power_logits)
            else:
                # The power head outputs 2 components per path: one parameterises alpha, the
                # other beta (mirrors LaunchPowerActorCriticMLP). Splitting them gives a Beta
                # with batch shape (k_paths,) whose mean the agent can actually learn.
                alpha = self.min_concentration + jax.nn.softplus(power_logits[..., 0]) * (
                    self.max_concentration - self.min_concentration
                )
                beta = self.min_concentration + jax.nn.softplus(power_logits[..., 1]) * (
                    self.max_concentration - self.min_concentration
                )
                power_action_dist = distrax.Beta(alpha, beta)

            return (path_action_dist, power_action_dist)

        return path_action_dist

CriticGNN

Bases: Module

Critic network using GNN for processing graph state.

Source code in xlron/models/gnn.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
class CriticGNN(eqx.Module):
    """Critic network using GNN for processing graph state."""

    graph_net: GraphNet
    critic_mlp: eqx.nn.MLP
    critic_output: eqx.nn.Linear

    # Static configuration
    activation: str = eqx.field(static=True)
    global_output_size: int = eqx.field(static=True)
    normalise_by_link_length: bool = eqx.field(static=True)

    def __init__(
        self,
        input_edge_features: int,
        input_node_features: int,
        input_global_features: int,
        activation: str = "tanh",
        num_layers: int = 2,
        num_units: int = 64,
        message_passing_steps: int = 1,
        mlp_layers: int = None,
        mlp_latent: int = None,
        edge_embedding_size: int = 128,
        edge_mlp_layers: int = 3,
        edge_mlp_latent: int = 128,
        edge_output_size: int = 0,
        global_embedding_size: int = 8,
        global_mlp_layers: int = 0,
        global_mlp_latent: int = 0,
        global_output_size: int = 1,  # Must be 1!
        node_embedding_size: int = 16,
        node_mlp_layers: int = 2,
        node_mlp_latent: int = 128,
        node_output_size: int = 0,
        attn_mlp_layers: int = 2,
        attn_mlp_latent: int = 128,
        use_attention: bool = True,
        normalise_by_link_length: bool = True,
        gnn_layer_norm: bool = True,
        mlp_layer_norm: bool = False,
        *,
        key: Array,
    ):
        assert global_output_size == 1
        self.activation = activation
        self.global_output_size = global_output_size
        self.normalise_by_link_length = normalise_by_link_length

        gnn_key, mlp_key, output_key = jax.random.split(key, 3)

        self.graph_net = GraphNet(
            input_edge_features=input_edge_features,
            input_node_features=input_node_features,
            input_global_features=input_global_features,
            message_passing_steps=message_passing_steps,
            mlp_layers=mlp_layers,
            mlp_latent=mlp_latent,
            edge_embedding_size=edge_embedding_size,
            edge_mlp_layers=edge_mlp_layers,
            edge_mlp_latent=edge_mlp_latent,
            edge_output_size=edge_output_size,
            global_embedding_size=global_embedding_size,
            global_mlp_layers=global_mlp_layers,
            global_mlp_latent=global_mlp_latent,
            global_output_size=global_output_size,
            node_embedding_size=node_embedding_size,
            node_mlp_layers=node_mlp_layers,
            node_mlp_latent=node_mlp_latent,
            node_output_size=node_output_size,
            attn_mlp_layers=attn_mlp_layers,
            attn_mlp_latent=attn_mlp_latent,
            use_attention=use_attention,
            gnn_layer_norm=gnn_layer_norm,
            mlp_layer_norm=mlp_layer_norm,
            key=gnn_key,
        )

        # MLP for processing flattened edge features (only used if global_output_size == 0)
        # We use a placeholder size; actual input size depends on runtime graph
        self.critic_mlp = eqx.nn.MLP(
            in_size=edge_output_size if edge_output_size > 0 else edge_embedding_size,
            out_size=num_units,
            width_size=num_units,
            depth=num_layers,
            activation=select_activation(activation),
            key=mlp_key,
        )

        self.critic_output = make_linear_with_orthogonal_init(num_units, 1, output_key, scale=1.0)

    def __call__(self, state: EnvState, params: EnvParams) -> Array:
        # Remove globals so value does not depend on current request
        graph = state.graph._replace(globals=jnp.zeros_like(state.graph.globals))
        state = state.replace(graph=graph)

        processed_graph = self.graph_net(state.graph)

        # Global output is already the scalar value
        # Shape: (1, 1)
        return processed_graph.globals.squeeze()  # ty: ignore[unresolved-attribute]

GraphNet

Bases: Module

A complete Graph Network model defined with Jraph and Equinox.

Source code in xlron/models/gnn.py
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
class GraphNet(eqx.Module):
    """A complete Graph Network model defined with Jraph and Equinox."""

    # Embedding layers
    edge_embedder: eqx.nn.Linear
    node_embedder: eqx.nn.Linear
    global_embedder: eqx.nn.Linear

    # Scan-compatible message passing steps (vmap-stacked)
    steps: MessagePassingStep

    # Decoder layers
    edge_decoder: Optional[eqx.nn.Linear]
    node_decoder: Optional[eqx.nn.Linear]
    global_decoder: Optional[eqx.nn.Linear]

    # Static configuration
    message_passing_steps: int = eqx.field(static=True)
    edge_embedding_size: int = eqx.field(static=True)
    node_embedding_size: int = eqx.field(static=True)
    global_embedding_size: int = eqx.field(static=True)
    edge_output_size: int = eqx.field(static=True)
    node_output_size: int = eqx.field(static=True)
    global_output_size: int = eqx.field(static=True)
    dropout_rate: float = eqx.field(static=True)
    skip_connections: bool = eqx.field(static=True)
    use_edge_model: bool = eqx.field(static=True)
    gnn_layer_norm: bool = eqx.field(static=True)
    deterministic: bool = eqx.field(static=True)
    use_attention: bool = eqx.field(static=True)

    def __init__(
        self,
        input_edge_features: int,
        input_node_features: int,
        input_global_features: int,
        message_passing_steps: int = 1,
        mlp_layers: int = 0,
        mlp_latent: int = 0,
        edge_embedding_size: int = 128,
        edge_mlp_layers: int = 3,
        edge_mlp_latent: int = 128,
        edge_output_size: int = 0,
        global_embedding_size: int = 8,
        global_mlp_layers: int = 0,
        global_mlp_latent: int = 0,
        global_output_size: int = 0,
        node_embedding_size: int = 16,
        node_mlp_layers: int = 2,
        node_mlp_latent: int = 128,
        node_output_size: int = 0,
        attn_mlp_layers: int = 2,
        attn_mlp_latent: int = 128,
        dropout_rate: float = 0,
        skip_connections: bool = True,
        use_edge_model: bool = True,
        gnn_layer_norm: bool = True,
        mlp_layer_norm: bool = False,
        deterministic: bool = True,
        use_attention: bool = True,
        *,
        key: Array,
    ):
        self.message_passing_steps = message_passing_steps
        self.edge_embedding_size = edge_embedding_size
        self.node_embedding_size = node_embedding_size
        self.global_embedding_size = global_embedding_size
        self.edge_output_size = edge_output_size
        self.node_output_size = node_output_size
        self.global_output_size = global_output_size
        self.dropout_rate = dropout_rate
        self.skip_connections = skip_connections
        self.use_edge_model = use_edge_model
        self.gnn_layer_norm = gnn_layer_norm
        self.deterministic = deterministic
        self.use_attention = use_attention

        # Determine MLP dimensions
        if mlp_latent is not None:
            global_mlp_dims = edge_mlp_dims = node_mlp_dims = attn_mlp_dims = [
                mlp_latent
            ] * mlp_layers
        else:
            global_mlp_dims = [global_mlp_latent] * global_mlp_layers
            edge_mlp_dims = [edge_mlp_latent] * edge_mlp_layers
            node_mlp_dims = [node_mlp_latent] * node_mlp_layers
            attn_mlp_dims = [attn_mlp_latent] * attn_mlp_layers

        if skip_connections:
            edge_mlp_dims = edge_mlp_dims + [edge_embedding_size]
            node_mlp_dims = node_mlp_dims + [node_embedding_size]
            global_mlp_dims = global_mlp_dims + [global_embedding_size]

        # Split keys for embedders and decoders
        embed_decode_key, steps_key = jax.random.split(key)
        keys = jax.random.split(embed_decode_key, 6)

        # Create embedders
        self.edge_embedder = eqx.nn.Linear(input_edge_features, edge_embedding_size, key=keys[0])
        self.node_embedder = eqx.nn.Linear(input_node_features, node_embedding_size, key=keys[1])
        self.global_embedder = eqx.nn.Linear(
            input_global_features, global_embedding_size, key=keys[2]
        )

        # Input sizes for MLPs after concatenation
        edge_mlp_input = edge_embedding_size + 2 * node_embedding_size + global_embedding_size
        node_mlp_input = node_embedding_size + 2 * edge_embedding_size + global_embedding_size
        global_mlp_input = node_embedding_size + edge_embedding_size + global_embedding_size
        attn_mlp_input = edge_embedding_size + 2 * node_embedding_size + global_embedding_size

        # Determine which optional components are present (fixed for all steps)
        _has_edge_mlp = use_edge_model and bool(edge_mlp_dims)
        _has_node_mlp = bool(node_mlp_dims)
        _has_global_mlp = global_output_size > 0 and bool(global_mlp_dims)
        _has_attn_mlp = use_attention and bool(attn_mlp_dims)
        _has_layer_norm = gnn_layer_norm
        _has_global_ln = gnn_layer_norm and global_output_size > 0
        attn_depth = max(len(attn_mlp_dims), 1) if _has_attn_mlp else 0

        # Build message passing steps via filter_vmap for scan-compatible stacking
        step_keys = jax.random.split(steps_key, message_passing_steps)

        @eqx.filter_vmap
        def make_step(step_key):
            k1, k2, k3, k4 = jax.random.split(step_key, 4)
            return MessagePassingStep(
                edge_mlp=eqx.nn.MLP(
                    in_size=edge_mlp_input,
                    out_size=edge_mlp_dims[-1],
                    width_size=edge_mlp_dims[0],
                    depth=len(edge_mlp_dims),
                    activation=jax.nn.relu,
                    key=k1,
                )
                if _has_edge_mlp
                else None,
                node_mlp=eqx.nn.MLP(
                    in_size=node_mlp_input,
                    out_size=node_mlp_dims[-1],
                    width_size=node_mlp_dims[0],
                    depth=len(node_mlp_dims),
                    activation=jax.nn.relu,
                    key=k2,
                )
                if _has_node_mlp
                else None,
                global_mlp=eqx.nn.MLP(
                    in_size=global_mlp_input,
                    out_size=global_mlp_dims[-1],
                    width_size=global_mlp_dims[0],
                    depth=len(global_mlp_dims),
                    activation=jax.nn.relu,
                    key=k3,
                )
                if _has_global_mlp
                else None,
                attn_mlp=eqx.nn.MLP(
                    in_size=attn_mlp_input,
                    out_size=1,
                    width_size=attn_mlp_dims[0],
                    depth=attn_depth,
                    activation=jax.nn.relu,
                    key=k4,
                )
                if _has_attn_mlp
                else None,
                node_ln=eqx.nn.LayerNorm(node_embedding_size) if _has_layer_norm else None,
                edge_ln=eqx.nn.LayerNorm(edge_embedding_size) if _has_layer_norm else None,
                global_ln=eqx.nn.LayerNorm(global_embedding_size) if _has_global_ln else None,
            )

        self.steps = make_step(step_keys)

        # Create decoders (keys[3], keys[4], keys[5])
        self.edge_decoder = (
            eqx.nn.Linear(edge_embedding_size, edge_output_size, key=keys[3])
            if edge_output_size > 0
            else None
        )
        self.node_decoder = (
            eqx.nn.Linear(node_embedding_size, node_output_size, key=keys[4])
            if node_output_size > 0
            else None
        )
        self.global_decoder = (
            eqx.nn.Linear(global_embedding_size, global_output_size, key=keys[5])
            if global_output_size > 0
            else None
        )

    def __call__(self, graphs: jraph.GraphsTuple) -> jraph.GraphsTuple:
        # Flatten edges if needed
        if graphs.edges.ndim >= 3:  # ty: ignore[unresolved-attribute]
            edges = graphs.edges.reshape((graphs.edges.shape[0], -1))  # ty: ignore[unresolved-attribute]
            graphs = graphs._replace(edges=edges)

        # Embed. Cast features up to the NN compute dtype first: under mixed precision the graph
        # node/edge/global features may be low precision (float16), but weights/activations stay
        # at COMPUTE_DTYPE for stability.
        nodes = jax.vmap(self.node_embedder)(graphs.nodes.astype(dtype_config.COMPUTE_DTYPE))  # ty: ignore[unresolved-attribute]
        edges = jax.vmap(self.edge_embedder)(graphs.edges.astype(dtype_config.COMPUTE_DTYPE))  # ty: ignore[unresolved-attribute]
        if graphs.globals is not None:
            g = graphs.globals.astype(dtype_config.COMPUTE_DTYPE)  # ty: ignore[unresolved-attribute]
            if g.ndim == 1:
                g = g[:, None]  # (n_graphs,) -> (n_graphs, 1)
            globals_ = jax.vmap(self.global_embedder)(g)
        else:
            globals_ = jnp.zeros((1, self.global_embedding_size), dtype=dtype_config.COMPUTE_DTYPE)

        processed_graphs = graphs._replace(nodes=nodes, edges=edges, globals=globals_)

        # Message passing via scan (traces body once instead of N times)
        dynamic_steps, static_steps = eqx.partition(self.steps, eqx.is_array)

        # Capture static config in closure for the scan body
        _use_attention = self.use_attention
        _skip_connections = self.skip_connections
        _gnn_layer_norm = self.gnn_layer_norm

        def apply_step(carry, dynamic_step):
            graphs = carry
            step = eqx.combine(dynamic_step, static_steps)

            # Build update functions from this step's MLPs
            update_edge_fn = (
                _make_update_edge_fn(step.edge_mlp) if step.edge_mlp is not None else None
            )
            update_node_fn = (
                _make_update_node_fn(step.node_mlp) if step.node_mlp is not None else None
            )
            update_global_fn = (
                _make_update_global_fn(step.global_mlp) if step.global_mlp is not None else None
            )

            if _use_attention and step.attn_mlp is not None:
                _attn_mlp = step.attn_mlp

                def attention_logit_fn(edges, sender_attr, receiver_attr, global_edge_attributes):
                    x = jnp.concatenate(
                        (edges, sender_attr, receiver_attr, global_edge_attributes), axis=1
                    )
                    return jax.vmap(_attn_mlp)(x)

                def attention_reduce_fn(edges, attention):
                    return attention * edges

                graph_net = GraphNetGAT(
                    update_node_fn=update_node_fn,
                    update_edge_fn=update_edge_fn,
                    update_global_fn=update_global_fn,
                    attention_logit_fn=attention_logit_fn,
                    attention_reduce_fn=attention_reduce_fn,
                )
            else:
                graph_net = GraphNetwork(
                    update_node_fn=update_node_fn,
                    update_edge_fn=update_edge_fn,
                    update_global_fn=update_global_fn,
                )

            new_graphs = graph_net(graphs)

            if _skip_connections:
                graphs = add_graphs_tuples(new_graphs, graphs)
            else:
                graphs = new_graphs

            if _gnn_layer_norm and step.node_ln is not None:
                graphs = graphs._replace(
                    nodes=jax.vmap(step.node_ln)(graphs.nodes),
                    edges=jax.vmap(step.edge_ln)(graphs.edges),
                    globals=jax.vmap(step.global_ln)(graphs.globals)
                    if step.global_ln is not None and graphs.globals is not None
                    else graphs.globals,
                )

            return graphs, None

        processed_graphs, _ = jax.lax.scan(apply_step, processed_graphs, dynamic_steps)

        # Decode
        if self.edge_decoder is not None:
            edges = jax.vmap(self.edge_decoder)(processed_graphs.edges)
            processed_graphs = processed_graphs._replace(edges=edges)
        if self.node_decoder is not None:
            nodes = jax.vmap(self.node_decoder)(processed_graphs.nodes)
            processed_graphs = processed_graphs._replace(nodes=nodes)
        if self.global_decoder is not None and processed_graphs.globals is not None:
            globals_ = jax.vmap(self.global_decoder)(processed_graphs.globals)
            processed_graphs = processed_graphs._replace(globals=globals_)

        return processed_graphs

MessagePassingStep

Bases: Module

A single message passing step containing MLPs and optional layer norms.

Source code in xlron/models/gnn.py
421
422
423
424
425
426
427
428
429
430
class MessagePassingStep(eqx.Module):
    """A single message passing step containing MLPs and optional layer norms."""

    edge_mlp: Optional[eqx.nn.MLP]
    node_mlp: Optional[eqx.nn.MLP]
    global_mlp: Optional[eqx.nn.MLP]
    attn_mlp: Optional[eqx.nn.MLP]
    node_ln: Optional[eqx.nn.LayerNorm]
    edge_ln: Optional[eqx.nn.LayerNorm]
    global_ln: Optional[eqx.nn.LayerNorm]

GAT(attention_query_fn, attention_logit_fn, node_update_fn=None)

Returns a method that applies a Graph Attention Network layer.

Graph Attention message passing as described in https://arxiv.org/abs/1710.10903. This model expects node features as a jnp.array, may use edge features for computing attention weights, and ignore global features. It does not support nests.

NOTE: this implementation assumes that the input graph has self edges. To recover the behavior of the referenced paper, please add self edges.

Parameters:

Name Type Description Default
attention_query_fn GATAttentionQueryFn

function that generates attention queries from sender node features.

required
attention_logit_fn GATAttentionLogitFn

function that converts attention queries into logits for softmax attention.

required
node_update_fn Optional[GATNodeUpdateFn]

function that updates the aggregated messages. If None, will apply leaky relu and concatenate (if using multi-head attention).

None

Returns:

Type Description

A function that applies a Graph Attention layer.

Source code in xlron/models/gnn.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def GAT(
    attention_query_fn: GATAttentionQueryFn,
    attention_logit_fn: GATAttentionLogitFn,
    node_update_fn: Optional[GATNodeUpdateFn] = None,
):
    """Returns a method that applies a Graph Attention Network layer.

    Graph Attention message passing as described in
    https://arxiv.org/abs/1710.10903. This model expects node features as a
    jnp.array, may use edge features for computing attention weights, and
    ignore global features. It does not support nests.

    NOTE: this implementation assumes that the input graph has self edges. To
    recover the behavior of the referenced paper, please add self edges.

    Args:
      attention_query_fn: function that generates attention queries
        from sender node features.
      attention_logit_fn: function that converts attention queries into logits for
        softmax attention.
      node_update_fn: function that updates the aggregated messages. If None,
        will apply leaky relu and concatenate (if using multi-head attention).

    Returns:
      A function that applies a Graph Attention layer.
    """
    # pylint: disable=g-long-lambda
    if node_update_fn is None:
        # By default, apply the leaky relu and then concatenate the heads on the
        # feature axis.
        def node_update_fn(x):
            return jnp.reshape(jax.nn.leaky_relu(x), (x.shape[0], -1))

    def _ApplyGAT(graph):
        """Applies a Graph Attention layer."""
        nodes, edges, receivers, senders, _, _, _ = graph
        # Equivalent to the sum of n_node, but statically known.
        try:
            sum_n_node = nodes.shape[0]
        except IndexError:
            raise IndexError("GAT requires node features")  # pylint: disable=raise-missing-from

        # First pass nodes through the node updater.
        nodes = attention_query_fn(nodes)
        # pylint: disable=g-long-lambda
        # We compute the softmax logits using a function that takes the
        # embedded sender and receiver attributes.
        sent_attributes = nodes[senders]
        received_attributes = nodes[receivers]
        softmax_logits = attention_logit_fn(sent_attributes, received_attributes, edges)

        # Compute the softmax weights on the entire tree.
        weights = utils.segment_softmax(
            softmax_logits, segment_ids=receivers, num_segments=sum_n_node
        )
        # Apply weights
        messages = sent_attributes * weights
        # Aggregate messages to nodes.
        nodes = utils.segment_sum(messages, receivers, num_segments=sum_n_node)

        # Apply an update function to the aggregated messages.
        nodes = node_update_fn(nodes)
        return graph._replace(nodes=nodes)

    # pylint: enable=g-long-lambda
    return _ApplyGAT

GraphNetGAT(update_edge_fn, update_node_fn, attention_logit_fn, attention_reduce_fn, update_global_fn=None, aggregate_edges_for_nodes_fn=utils.segment_sum, aggregate_nodes_for_globals_fn=utils.segment_sum, aggregate_edges_for_globals_fn=utils.segment_sum)

Returns a method that applies a GraphNet with attention on edge features.

Parameters:

Name Type Description Default
update_edge_fn GNUpdateEdgeFn

function used to update the edges.

required
update_node_fn GNUpdateNodeFn

function used to update the nodes.

required
attention_logit_fn AttentionLogitFn

function used to calculate the attention weights.

required
attention_reduce_fn AttentionReduceFn

function used to apply attention weights to the edge features.

required
update_global_fn Optional[GNUpdateGlobalFn]

function used to update the globals or None to deactivate globals updates.

None
aggregate_edges_for_nodes_fn AggregateEdgesToNodesFn

function used to aggregate attention-weighted messages to each node.

segment_sum
aggregate_nodes_for_globals_fn AggregateNodesToGlobalsFn

function used to aggregate the nodes for the globals.

segment_sum
aggregate_edges_for_globals_fn AggregateEdgesToGlobalsFn

function used to aggregate attention-weighted edges for the globals.

segment_sum

Returns:

Type Description

A function that applies a GraphNet Graph Attention layer.

Source code in xlron/models/gnn.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
299
300
301
302
303
304
def GraphNetGAT(
    update_edge_fn: GNUpdateEdgeFn,
    update_node_fn: GNUpdateNodeFn,
    attention_logit_fn: AttentionLogitFn,
    attention_reduce_fn: AttentionReduceFn,
    update_global_fn: Optional[GNUpdateGlobalFn] = None,
    aggregate_edges_for_nodes_fn: AggregateEdgesToNodesFn = utils.segment_sum,
    aggregate_nodes_for_globals_fn: AggregateNodesToGlobalsFn = utils.segment_sum,
    aggregate_edges_for_globals_fn: AggregateEdgesToGlobalsFn = utils.segment_sum,
):
    """Returns a method that applies a GraphNet with attention on edge features.

    Args:
      update_edge_fn: function used to update the edges.
      update_node_fn: function used to update the nodes.
      attention_logit_fn: function used to calculate the attention weights.
      attention_reduce_fn: function used to apply attention weights to the edge
        features.
      update_global_fn: function used to update the globals or None to deactivate
        globals updates.
      aggregate_edges_for_nodes_fn: function used to aggregate attention-weighted
        messages to each node.
      aggregate_nodes_for_globals_fn: function used to aggregate the nodes for the
        globals.
      aggregate_edges_for_globals_fn: function used to aggregate
        attention-weighted edges for the globals.

    Returns:
      A function that applies a GraphNet Graph Attention layer.
    """
    if (attention_logit_fn is None) or (attention_reduce_fn is None):
        raise ValueError(
            (
                "`None` value not supported for `attention_logit_fn` or "
                "`attention_reduce_fn` in a Graph Attention network."
            )
        )
    return GraphNetwork(
        update_edge_fn=update_edge_fn,
        update_node_fn=update_node_fn,
        update_global_fn=update_global_fn,
        attention_logit_fn=attention_logit_fn,
        attention_reduce_fn=attention_reduce_fn,
        aggregate_edges_for_nodes_fn=aggregate_edges_for_nodes_fn,
        aggregate_nodes_for_globals_fn=aggregate_nodes_for_globals_fn,
        aggregate_edges_for_globals_fn=aggregate_edges_for_globals_fn,
    )

GraphNetwork(update_edge_fn, update_node_fn, update_global_fn=None, aggregate_edges_for_nodes_fn=utils.segment_sum, aggregate_nodes_for_globals_fn=utils.segment_sum, aggregate_edges_for_globals_fn=utils.segment_sum, attention_logit_fn=None, attention_normalize_fn=utils.segment_softmax, attention_reduce_fn=None)

Returns a method that applies a configured GraphNetwork.

This implementation follows Algorithm 1 in https://arxiv.org/abs/1806.01261

There is one difference. For the nodes update the class aggregates over the sender edges and receiver edges separately. This is a bit more general than the algorithm described in the paper. The original behaviour can be recovered by using only the receiver edge aggregations for the update.

In addition this implementation supports softmax attention over incoming edge features.

Example usage::

gn = GraphNetwork(update_edge_function, update_node_function, **kwargs) # Conduct multiple rounds of message passing with the same parameters: for _ in range(num_message_passing_steps): graph = gn(graph)

Parameters:

Name Type Description Default
update_edge_fn Optional[GNUpdateEdgeFn]

function used to update the edges or None to deactivate edge updates.

required
update_node_fn Optional[GNUpdateNodeFn]

function used to update the nodes or None to deactivate node updates.

required
update_global_fn Optional[GNUpdateGlobalFn]

function used to update the globals or None to deactivate globals updates.

None
aggregate_edges_for_nodes_fn AggregateEdgesToNodesFn

function used to aggregate messages to each node.

segment_sum
aggregate_nodes_for_globals_fn AggregateNodesToGlobalsFn

function used to aggregate the nodes for the globals.

segment_sum
aggregate_edges_for_globals_fn AggregateEdgesToGlobalsFn

function used to aggregate the edges for the globals.

segment_sum
attention_logit_fn Optional[AttentionLogitFn]

function used to calculate the attention weights or None to deactivate attention mechanism.

None
attention_normalize_fn Optional[AttentionNormalizeFn]

function used to normalize raw attention logits or None if attention mechanism is not active.

segment_softmax
attention_reduce_fn Optional[AttentionReduceFn]

function used to apply weights to the edge features or None if attention mechanism is not active.

None

Returns:

Type Description

A method that applies the configured GraphNetwork.

Source code in xlron/models/gnn.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def GraphNetwork(
    update_edge_fn: Optional[GNUpdateEdgeFn],
    update_node_fn: Optional[GNUpdateNodeFn],
    update_global_fn: Optional[GNUpdateGlobalFn] = None,
    # TODO: allow RNN/SSM to be used in the aggregation function
    #  https://github.com/luchris429/popjaxrl/blob/main/algorithms/ppo_gru.py
    aggregate_edges_for_nodes_fn: AggregateEdgesToNodesFn = utils.segment_sum,
    aggregate_nodes_for_globals_fn: AggregateNodesToGlobalsFn = utils.segment_sum,
    aggregate_edges_for_globals_fn: AggregateEdgesToGlobalsFn = utils.segment_sum,
    attention_logit_fn: Optional[AttentionLogitFn] = None,
    attention_normalize_fn: Optional[AttentionNormalizeFn] = utils.segment_softmax,
    attention_reduce_fn: Optional[AttentionReduceFn] = None,
):
    """Returns a method that applies a configured GraphNetwork.

    This implementation follows Algorithm 1 in https://arxiv.org/abs/1806.01261

    There is one difference. For the nodes update the class aggregates over the
    sender edges and receiver edges separately. This is a bit more general
    than the algorithm described in the paper. The original behaviour can be
    recovered by using only the receiver edge aggregations for the update.

    In addition this implementation supports softmax attention over incoming
    edge features.

    Example usage::

      gn = GraphNetwork(update_edge_function,
      update_node_function, **kwargs)
      # Conduct multiple rounds of message passing with the same parameters:
      for _ in range(num_message_passing_steps):
        graph = gn(graph)

    Args:
      update_edge_fn: function used to update the edges or None to deactivate edge
        updates.
      update_node_fn: function used to update the nodes or None to deactivate node
        updates.
      update_global_fn: function used to update the globals or None to deactivate
        globals updates.
      aggregate_edges_for_nodes_fn: function used to aggregate messages to each
        node.
      aggregate_nodes_for_globals_fn: function used to aggregate the nodes for the
        globals.
      aggregate_edges_for_globals_fn: function used to aggregate the edges for the
        globals.
      attention_logit_fn: function used to calculate the attention weights or
        None to deactivate attention mechanism.
      attention_normalize_fn: function used to normalize raw attention logits or
        None if attention mechanism is not active.
      attention_reduce_fn: function used to apply weights to the edge features or
        None if attention mechanism is not active.

    Returns:
      A method that applies the configured GraphNetwork.
    """

    def not_both_supplied(x, y):
        return (x != y) and ((x is None) or (y is None))

    if not_both_supplied(attention_reduce_fn, attention_logit_fn):
        raise ValueError(("attention_logit_fn and attention_reduce_fn must both be supplied."))

    def _ApplyGraphNet(graph):
        """Applies a configured GraphNetwork to a graph.

        This implementation follows Algorithm 1 in https://arxiv.org/abs/1806.01261

        There is one difference. For the nodes update the class aggregates over the
        sender edges and receiver edges separately. This is a bit more general
        the algorithm described in the paper. The original behaviour can be
        recovered by using only the receiver edge aggregations for the update.

        In addition this implementation supports softmax attention over incoming
        edge features.

        Many popular Graph Neural Networks can be implemented as special cases of
        GraphNets, for more information please see the paper.

        Args:
          graph: a `GraphsTuple` containing the graph.

        Returns:
          Updated `GraphsTuple`.
        """
        # pylint: disable=g-long-lambda
        nodes, edges, receivers, senders, globals_, n_node, n_edge = graph
        # Equivalent to jnp.sum(n_node), but jittable
        sum_n_node = tree.tree_leaves(nodes)[0].shape[0]
        sum_n_edge = senders.shape[0]
        if not tree.tree_all(tree.tree_map(lambda n: n.shape[0] == sum_n_node, nodes)):
            raise ValueError("All node arrays in nest must contain the same number of nodes.")

        sent_attributes = tree.tree_map(lambda n: n[senders], nodes)
        received_attributes = tree.tree_map(lambda n: n[receivers], nodes)
        # Here we scatter the global features to the corresponding edges,
        # giving us tensors of shape [num_edges, global_feat].
        global_edge_attributes = tree.tree_map(
            lambda g: jnp.repeat(g, n_edge, axis=0, total_repeat_length=sum_n_edge),
            globals_,
        )

        if update_edge_fn:
            edges = update_edge_fn(
                edges, sent_attributes, received_attributes, global_edge_attributes
            )

        if attention_logit_fn:
            logits = attention_logit_fn(
                edges, sent_attributes, received_attributes, global_edge_attributes
            )
            tree_calculate_weights = functools.partial(
                attention_normalize_fn, segment_ids=receivers, num_segments=sum_n_node
            )
            weights = tree.tree_map(tree_calculate_weights, logits)
            edges = attention_reduce_fn(edges, weights)

        if update_node_fn:
            sent_attributes = tree.tree_map(
                lambda e: aggregate_edges_for_nodes_fn(e, senders, sum_n_node), edges
            )
            received_attributes = tree.tree_map(
                lambda e: aggregate_edges_for_nodes_fn(e, receivers, sum_n_node), edges
            )
            # Here we scatter the global features to the corresponding nodes,
            # giving us tensors of shape [num_nodes, global_feat].
            global_attributes = tree.tree_map(
                lambda g: jnp.repeat(g, n_node, axis=0, total_repeat_length=sum_n_node),
                globals_,
            )
            nodes = update_node_fn(nodes, sent_attributes, received_attributes, global_attributes)

        if update_global_fn:
            n_graph = n_node.shape[0]
            graph_idx = jnp.arange(n_graph)
            # To aggregate nodes and edges from each graph to global features,
            # we first construct tensors that map the node to the corresponding graph.
            # For example, if you have `n_node=[1,2]`, we construct the tensor
            # [0, 1, 1]. We then do the same for edges.
            node_gr_idx = jnp.repeat(graph_idx, n_node, axis=0, total_repeat_length=sum_n_node)
            edge_gr_idx = jnp.repeat(graph_idx, n_edge, axis=0, total_repeat_length=sum_n_edge)
            # We use the aggregation function to pool the nodes/edges per graph.
            node_attributes = tree.tree_map(
                lambda n: aggregate_nodes_for_globals_fn(n, node_gr_idx, n_graph), nodes
            )
            edge_attributes = tree.tree_map(
                lambda e: aggregate_edges_for_globals_fn(e, edge_gr_idx, n_graph), edges
            )
            # These pooled nodes are the inputs to the global update fn.
            globals_ = update_global_fn(node_attributes, edge_attributes, globals_)
        # pylint: enable=g-long-lambda
        return gn_graph.GraphsTuple(
            nodes=nodes,
            edges=edges,
            receivers=receivers,
            senders=senders,
            globals=globals_,
            n_node=n_node,
            n_edge=n_edge,
        )

    return _ApplyGraphNet

add_graphs_tuples(graphs, other_graphs)

Adds the nodes, edges and global features from other_graphs to graphs.

Source code in xlron/models/gnn.py
380
381
382
383
384
385
386
387
388
def add_graphs_tuples(
    graphs: jraph.GraphsTuple, other_graphs: jraph.GraphsTuple
) -> jraph.GraphsTuple:
    """Adds the nodes, edges and global features from other_graphs to graphs."""
    return graphs._replace(
        nodes=graphs.nodes + other_graphs.nodes,
        edges=graphs.edges + other_graphs.edges,
        globals=graphs.globals + other_graphs.globals if graphs.globals is not None else None,
    )

add_self_edges_fn(receivers, senders, total_num_nodes)

Adds self edges. Assumes self edges are not in the graph yet.

Source code in xlron/models/gnn.py
84
85
86
87
88
89
90
91
def add_self_edges_fn(
    receivers: jnp.ndarray, senders: jnp.ndarray, total_num_nodes: int
) -> Tuple[jnp.ndarray, jnp.ndarray]:
    """Adds self edges. Assumes self edges are not in the graph yet."""
    # TODo - check if self-edges required
    receivers = jnp.concatenate((receivers, jnp.arange(total_num_nodes)), axis=0)
    senders = jnp.concatenate((senders, jnp.arange(total_num_nodes)), axis=0)
    return receivers, senders

ActorCriticTransformer

Bases: Module

Source code in xlron/models/transformer.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
class ActorCriticTransformer(eqx.Module):
    actor_critic: eqx.nn.Shared | Tuple[eqx.Module, eqx.Module]
    actor_mlp: eqx.nn.MLP
    critic_mlp: eqx.nn.MLP
    share_layers: bool
    num_slot_actions: int
    num_request_specific_cols: int = eqx.field(static=True)
    embedding_size: int = eqx.field(static=True)
    critic_pooling: str = eqx.field(static=True)
    actor_pooling: str = eqx.field(static=True)
    # Attention pooling for critic (only used when critic_pooling == "attention")
    value_query: Array | None
    # Projection for actor min_mean_max pooling (only used when actor_pooling == "min_mean_max")
    actor_pool_proj: eqx.nn.Linear | None

    def __init__(
        self,
        input_size: int,
        embedding_size: int,
        intermediate_size: int,
        num_slot_actions: int,
        num_layers: int,
        num_heads: int,
        enable_dropout: bool,
        dropout_rate: float,
        attention_dropout_rate: float,
        share_layers: bool,
        num_wire_features: int,
        actor_mlp_width: int,
        critic_mlp_width: int,
        actor_mlp_depth: int,
        critic_mlp_depth: int,
        num_request_specific_cols: int,
        key: chex.PRNGKey,
        critic_pooling: str = "mean",
        actor_pooling: str = "sum",
        ffn_activation: str = "relu2",
    ):
        (
            encoder_key,
            actor_key,
            critic_key,
            vq_key,
            proj_key,
        ) = jax.random.split(key, 5)
        self.share_layers = share_layers
        self.num_request_specific_cols = num_request_specific_cols
        self.embedding_size = embedding_size
        self.critic_pooling = critic_pooling
        self.actor_pooling = actor_pooling
        # Give the critic encoder an independent init key so that with share_layers=False it
        # does not start as an exact copy of the actor. The actor keeps encoder_key so its
        # init is unchanged for a fixed seed.
        critic_enc_key = jax.random.fold_in(encoder_key, 1)
        actor = Encoder(
            input_size=input_size,
            intermediate_size=intermediate_size,
            embedding_size=embedding_size,
            num_layers=num_layers,
            num_heads=num_heads,
            num_wire_features=num_wire_features,
            dropout_rate=dropout_rate,
            attention_dropout_rate=attention_dropout_rate,
            key=encoder_key,
            ffn_activation=ffn_activation,
        )
        critic = Encoder(
            input_size=input_size - num_request_specific_cols,
            intermediate_size=intermediate_size,
            embedding_size=embedding_size,
            num_layers=num_layers,
            num_heads=num_heads,
            num_wire_features=num_wire_features,
            dropout_rate=dropout_rate,
            attention_dropout_rate=attention_dropout_rate,
            key=critic_enc_key,
            ffn_activation=ffn_activation,
        )
        if self.share_layers:
            # When sharing layers, use the same encoder for both actor and critic
            self.actor_critic = (actor, actor)
        else:
            self.actor_critic = (actor, critic)
        self.actor_mlp = eqx.nn.MLP(
            in_size=embedding_size,
            width_size=actor_mlp_width,
            out_size=num_slot_actions,
            depth=actor_mlp_depth,
            key=actor_key,
        )
        self.critic_mlp = eqx.nn.MLP(
            in_size=embedding_size,
            width_size=critic_mlp_width,
            out_size=1,
            depth=critic_mlp_depth,
            key=critic_key,
        )
        self.num_slot_actions = num_slot_actions

        # Attention pooling for critic
        if critic_pooling == "attention":
            self.value_query = jax.random.normal(vq_key, (embedding_size,)) * 0.02
        else:
            self.value_query = None

        # min_mean_max projection for actor: 3 * num_slot_actions -> num_slot_actions
        if actor_pooling == "min_mean_max":
            self.actor_pool_proj = eqx.nn.Linear(
                in_features=3 * num_slot_actions,
                out_features=num_slot_actions,
                key=proj_key,
            )
        else:
            self.actor_pool_proj = None

    def __call__(
        self,
        state: EnvState,
        params: EnvParams,
        *,
        enable_dropout: bool = False,
        key: chex.PRNGKey | None = None,
    ) -> Tuple[distrax.Categorical, Array]:
        """Forward pass through the actor-critic transformer.

        Args:
            state: Environment state
            params: Environment parameters
            enable_dropout: Whether to enable dropout
            key: PRNG key for dropout

        Returns:
            Tuple of (action_distribution, value)
        """
        actor, critic = self.actor_critic
        actor_key, critic_key = jax.random.split(key) if key is not None else (None, None)
        # Cast tokens up to the NN compute dtype: under mixed precision the env-sourced token
        # columns may be low precision, but attention/weights stay at COMPUTE_DTYPE for stability.
        tokens = get_obs_transformer(state, params).astype(dtype_config.COMPUTE_DTYPE)

        action_tokens = actor(
            tokens,
            enable_dropout=enable_dropout,
            key=actor_key,
        )["output"]

        # Strip request-specific columns for critic
        tokens_for_critic = tokens[:, : -self.num_request_specific_cols]
        value_tokens = critic(
            tokens_for_critic,
            enable_dropout=enable_dropout,
            key=critic_key,
        )["output"]

        # ACTOR POOLING
        nodes_sd, requested_bw = read_rsa_request(state.request_array)
        if self.actor_pooling == "min_mean_max":
            action_tokens = jax.vmap(self.actor_mlp)(action_tokens)

            def path_action_min_mean_max(i):
                # Gather per-link features for this path using min, mean, max
                path_min = get_path_slots(action_tokens, params, nodes_sd, i, agg_func="min")
                path_mean = get_path_slots(action_tokens, params, nodes_sd, i, agg_func="mean")
                path_max = get_path_slots(action_tokens, params, nodes_sd, i, agg_func="max")
                concatenated = jnp.concatenate([path_min, path_mean, path_max])
                return self.actor_pool_proj(concatenated)

            path_action_logits = jax.vmap(path_action_min_mean_max)(jnp.arange(params.k_paths))
        else:
            # Default: sum pooling. Pool hidden features over each path's links and
            # project once, rather than projecting every link to slot logits first.
            path_action_logits = pooled_actor_projection(
                self.actor_mlp, action_tokens, get_paths(params, nodes_sd)
            )
        action_logits = path_action_logits.reshape((-1,))

        if params.include_no_op:
            action_logits = jnp.hstack([action_logits, jnp.array([-1e4])])
        # Cast outputs back to PARAMS_DTYPE (float32): under bf16 compute the logits/value are
        # bf16, but the downstream PPO math and the f32 env-state fields (valid_mass etc.) require
        # float32 -- otherwise the lax.scan carry dtype mismatches. Keeps bf16 inside the model.
        action_dist = distrax.Categorical(logits=action_logits.astype(dtype_config.PARAMS_DTYPE))

        # CRITIC POOLING
        if self.critic_pooling == "attention":
            # Single-query attention pooling
            d = self.embedding_size
            # weights: (num_links,) = softmax(value_tokens @ value_query / sqrt(d))
            attn_logits = value_tokens @ self.value_query / jnp.sqrt(d)
            attn_weights = jax.nn.softmax(attn_logits)
            # pooled: (d,) = weighted sum of link embeddings
            pooled = attn_weights[:, None] * value_tokens
            pooled = jnp.sum(pooled, axis=0)
        else:
            # Default: mean pooling
            pooled = jnp.mean(value_tokens, axis=0)

        value = self.critic_mlp(pooled).squeeze().astype(dtype_config.PARAMS_DTYPE)

        return action_dist, value

    def sample_action(
        self,
        seed: chex.PRNGKey,
        dist: distrax.Categorical,
        log_prob: bool = False,
        deterministic: bool = False,
    ) -> Union[Array, Tuple[Array, Array]]:
        """Sample an action from the distribution"""
        action = dist.mode() if deterministic else dist.sample(seed=seed)
        if log_prob:
            return action, dist.log_prob(action)
        return action

__call__(state, params, *, enable_dropout=False, key=None)

Forward pass through the actor-critic transformer.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required
enable_dropout bool

Whether to enable dropout

False
key PRNGKey | None

PRNG key for dropout

None

Returns:

Type Description
Tuple[Categorical, Array]

Tuple of (action_distribution, value)

Source code in xlron/models/transformer.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def __call__(
    self,
    state: EnvState,
    params: EnvParams,
    *,
    enable_dropout: bool = False,
    key: chex.PRNGKey | None = None,
) -> Tuple[distrax.Categorical, Array]:
    """Forward pass through the actor-critic transformer.

    Args:
        state: Environment state
        params: Environment parameters
        enable_dropout: Whether to enable dropout
        key: PRNG key for dropout

    Returns:
        Tuple of (action_distribution, value)
    """
    actor, critic = self.actor_critic
    actor_key, critic_key = jax.random.split(key) if key is not None else (None, None)
    # Cast tokens up to the NN compute dtype: under mixed precision the env-sourced token
    # columns may be low precision, but attention/weights stay at COMPUTE_DTYPE for stability.
    tokens = get_obs_transformer(state, params).astype(dtype_config.COMPUTE_DTYPE)

    action_tokens = actor(
        tokens,
        enable_dropout=enable_dropout,
        key=actor_key,
    )["output"]

    # Strip request-specific columns for critic
    tokens_for_critic = tokens[:, : -self.num_request_specific_cols]
    value_tokens = critic(
        tokens_for_critic,
        enable_dropout=enable_dropout,
        key=critic_key,
    )["output"]

    # ACTOR POOLING
    nodes_sd, requested_bw = read_rsa_request(state.request_array)
    if self.actor_pooling == "min_mean_max":
        action_tokens = jax.vmap(self.actor_mlp)(action_tokens)

        def path_action_min_mean_max(i):
            # Gather per-link features for this path using min, mean, max
            path_min = get_path_slots(action_tokens, params, nodes_sd, i, agg_func="min")
            path_mean = get_path_slots(action_tokens, params, nodes_sd, i, agg_func="mean")
            path_max = get_path_slots(action_tokens, params, nodes_sd, i, agg_func="max")
            concatenated = jnp.concatenate([path_min, path_mean, path_max])
            return self.actor_pool_proj(concatenated)

        path_action_logits = jax.vmap(path_action_min_mean_max)(jnp.arange(params.k_paths))
    else:
        # Default: sum pooling. Pool hidden features over each path's links and
        # project once, rather than projecting every link to slot logits first.
        path_action_logits = pooled_actor_projection(
            self.actor_mlp, action_tokens, get_paths(params, nodes_sd)
        )
    action_logits = path_action_logits.reshape((-1,))

    if params.include_no_op:
        action_logits = jnp.hstack([action_logits, jnp.array([-1e4])])
    # Cast outputs back to PARAMS_DTYPE (float32): under bf16 compute the logits/value are
    # bf16, but the downstream PPO math and the f32 env-state fields (valid_mass etc.) require
    # float32 -- otherwise the lax.scan carry dtype mismatches. Keeps bf16 inside the model.
    action_dist = distrax.Categorical(logits=action_logits.astype(dtype_config.PARAMS_DTYPE))

    # CRITIC POOLING
    if self.critic_pooling == "attention":
        # Single-query attention pooling
        d = self.embedding_size
        # weights: (num_links,) = softmax(value_tokens @ value_query / sqrt(d))
        attn_logits = value_tokens @ self.value_query / jnp.sqrt(d)
        attn_weights = jax.nn.softmax(attn_logits)
        # pooled: (d,) = weighted sum of link embeddings
        pooled = attn_weights[:, None] * value_tokens
        pooled = jnp.sum(pooled, axis=0)
    else:
        # Default: mean pooling
        pooled = jnp.mean(value_tokens, axis=0)

    value = self.critic_mlp(pooled).squeeze().astype(dtype_config.PARAMS_DTYPE)

    return action_dist, value

sample_action(seed, dist, log_prob=False, deterministic=False)

Sample an action from the distribution

Source code in xlron/models/transformer.py
652
653
654
655
656
657
658
659
660
661
662
663
def sample_action(
    self,
    seed: chex.PRNGKey,
    dist: distrax.Categorical,
    log_prob: bool = False,
    deterministic: bool = False,
) -> Union[Array, Tuple[Array, Array]]:
    """Sample an action from the distribution"""
    action = dist.mode() if deterministic else dist.sample(seed=seed)
    if log_prob:
        return action, dist.log_prob(action)
    return action

AttentionBlock

Bases: Module

A single transformer attention block.

Source code in xlron/models/transformer.py
156
157
158
159
160
161
162
163
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
194
195
196
197
198
199
200
201
202
203
204
class AttentionBlock(eqx.Module):
    """A single transformer attention block."""

    attention: MultiheadAttention
    layernorm: eqx.nn.LayerNorm
    dropout: eqx.nn.Dropout
    num_heads: int = eqx.field(static=True)

    def __init__(
        self,
        embedding_size: int,
        num_heads: int,
        dropout_rate: float,
        attention_dropout_rate: float,
        key: chex.PRNGKey,
    ):
        self.num_heads = num_heads
        self.attention = MultiheadAttention(
            num_heads=num_heads,
            query_size=embedding_size,
            dropout_p=attention_dropout_rate,
            key=key,
        )
        self.layernorm = eqx.nn.LayerNorm(shape=embedding_size)
        self.dropout = eqx.nn.Dropout(dropout_rate)

    def __call__(
        self,
        inputs: Array,
        enable_dropout: bool = False,
        attn_mask: Array | None = None,
        process_heads: Callable | None = None,
        key: chex.PRNGKey | None = None,
    ) -> Array:
        attention_key, dropout_key = (None, None) if key is None else jax.random.split(key)

        norm_input = jax.vmap(self.layernorm)(inputs)
        attention_output = self.attention(
            query=norm_input,
            key_=norm_input,
            value=norm_input,
            mask=attn_mask,
            inference=not enable_dropout,
            key=attention_key,
            process_heads=process_heads,
        )
        result = self.dropout(attention_output, inference=not enable_dropout, key=dropout_key)
        result = result + inputs
        return result

FeedForwardBlock

Bases: Module

A single transformer feed forward block.

Source code in xlron/models/transformer.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
class FeedForwardBlock(eqx.Module):
    """A single transformer feed forward block."""

    linear: eqx.nn.Linear
    output: eqx.nn.Linear
    layernorm: eqx.nn.LayerNorm
    dropout: eqx.nn.Dropout
    activation: str = eqx.field(static=True)

    def __init__(
        self,
        embedding_size: int,
        intermediate_size: int,
        dropout_rate: float,
        key: chex.PRNGKey,
        activation: str = "relu2",
    ):
        mlp_key, output_key = jax.random.split(key)
        select_activation(activation)  # fail at construction on an unknown name
        self.activation = activation
        self.linear = eqx.nn.Linear(
            in_features=embedding_size, out_features=intermediate_size, key=mlp_key
        )
        self.output = eqx.nn.Linear(
            in_features=intermediate_size, out_features=embedding_size, key=output_key
        )
        self.layernorm = eqx.nn.LayerNorm(shape=embedding_size)
        self.dropout = eqx.nn.Dropout(dropout_rate)

    def __call__(
        self,
        inputs: Array,
        enable_dropout: bool = True,
        key: chex.PRNGKey | None = None,
    ) -> Array:
        hidden = self.layernorm(inputs)

        # Feed-forward.
        hidden = self.linear(hidden)
        hidden = select_activation(self.activation)(hidden)

        # Project back to input size.
        output = self.output(hidden)
        output = self.dropout(output, inference=not enable_dropout, key=key)

        # Residual
        output += inputs

        return output

TransformerLayer

Bases: Module

A single transformer layer.

Source code in xlron/models/transformer.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class TransformerLayer(eqx.Module):
    """A single transformer layer."""

    attention_block: AttentionBlock
    ff_block: FeedForwardBlock

    def __init__(
        self,
        embedding_size: int,
        intermediate_size: int,
        num_heads: int,
        dropout_rate: float,
        attention_dropout_rate: float,
        key: chex.PRNGKey,
        custom_bias: bool = False,
        ffn_activation: str = "relu2",
    ):
        attention_key, ff_key = jax.random.split(key)

        self.attention_block = AttentionBlock(
            embedding_size=embedding_size,
            num_heads=num_heads,
            dropout_rate=dropout_rate,
            attention_dropout_rate=attention_dropout_rate,
            key=attention_key,
        )
        self.ff_block = FeedForwardBlock(
            embedding_size=embedding_size,
            intermediate_size=intermediate_size,
            dropout_rate=dropout_rate,
            key=ff_key,
            activation=ffn_activation,
        )

    def __call__(
        self,
        inputs: Array,
        *,
        enable_dropout: bool = False,
        attn_mask: Array | None = None,
        key: chex.PRNGKey | None = None,
        process_heads: Callable | None = None,
    ) -> Array:
        attn_key, ff_key = (None, None) if key is None else jax.random.split(key)

        attn_result = self.attention_block(
            inputs,
            enable_dropout=enable_dropout,
            attn_mask=attn_mask,
            key=attn_key,
            process_heads=process_heads,
        )
        # attention_block returns Array when return_attention=False (the default)
        attention_output = attn_result if isinstance(attn_result, Array) else attn_result[0]

        seq_len = inputs.shape[0]
        ff_keys = None if ff_key is None else jax.random.split(ff_key, num=seq_len)
        output = jax.vmap(self.ff_block, in_axes=(0, None, 0))(
            attention_output, enable_dropout, ff_keys
        )
        return output

WIRE

Bases: Module

Wavelet-Induced Rotary Encodings for graphs. https://openreview.net/pdf?id=f7BvsdILYx

Projects m-dimensional node features (e.g., RWSE, spectral coords) to rotation angles for RoPE-style positional encoding.

Source code in xlron/models/transformer.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
class WIRE(eqx.Module):
    """Wavelet-Induced Rotary Encodings for graphs.
    https://openreview.net/pdf?id=f7BvsdILYx

    Projects m-dimensional node features (e.g., RWSE, spectral coords)
    to rotation angles for RoPE-style positional encoding.
    """

    freq_proj: eqx.nn.Linear  # (m,) -> (embedding_size // 2,)
    embedding_size: int = eqx.field(static=True)

    def __init__(
        self,
        num_features: int,
        embedding_size: int,
        key: PRNGKeyArray,
        freq_scale: float = 0.01,
    ):
        """
        Args:
            num_features: Dimension of input position features (m)
            embedding_size: Dimension of queries/keys to rotate (must be even)
            key: PRNG key
            freq_scale: Scale for frequency initialisation
        """
        if embedding_size % 2 != 0:
            raise ValueError("embedding_size must be even")

        self.embedding_size = embedding_size

        # Project position features to angles
        # Output dim is embedding_size // 2 (one angle per 2D rotation block)
        self.freq_proj = eqx.nn.Linear(
            in_features=num_features,
            out_features=embedding_size // 2,
            use_bias=False,
            key=key,
        )

        # Optionally scale down initial frequencies for stability
        scaled_weight = self.freq_proj.weight * freq_scale
        self.freq_proj = eqx.tree_at(lambda layer: layer.weight, self.freq_proj, scaled_weight)

    def get_angles(
        self, positions: Float[Array, "num_nodes num_features"]
    ) -> Float[Array, "num_nodes half_emb"]:
        """Compute rotation angles from position features."""
        return jax.vmap(self.freq_proj)(positions)

    def rotate(
        self,
        x: Float[Array, "num_nodes embedding_size"],
        angles: Float[Array, "num_nodes half_emb"],
    ) -> Float[Array, "num_nodes embedding_size"]:
        """Apply rotary encoding to queries or keys.

        For each 2D block [x_{2i}, x_{2i+1}], rotate by angle theta_i:
            x_{2i}'   = x_{2i} * cos(theta) - x_{2i+1} * sin(theta)
            x_{2i+1}' = x_{2i} * sin(theta) + x_{2i+1} * cos(theta)
        """
        # angles: (num_nodes, embedding_size // 2)
        cos_angles = jnp.cos(angles)
        sin_angles = jnp.sin(angles)

        # Repeat for pairs: [cos_0, cos_0, cos_1, cos_1, ...]
        cos_angles = jnp.repeat(cos_angles, 2, axis=-1)
        sin_angles = jnp.repeat(sin_angles, 2, axis=-1)

        # Rotate pairs: for indices [0,1], [2,3], etc.
        # x_rotated = x * cos + rotate_pairs(x) * sin
        # where rotate_pairs swaps and negates: [x0, x1] -> [-x1, x0]
        x_pairs = x.reshape(x.shape[0], -1, 2)  # (num_nodes, num_pairs, 2)
        x_rotated_pairs = jnp.stack([-x_pairs[..., 1], x_pairs[..., 0]], axis=-1)
        x_rotated = x_rotated_pairs.reshape(x.shape)

        return x * cos_angles + x_rotated * sin_angles

    def __call__(
        self,
        queries: Float[Array, "num_nodes embedding_size"],
        keys: Float[Array, "num_nodes embedding_size"],
        positions: Float[Array, "num_nodes num_features"],
    ) -> tuple[
        Float[Array, "num_nodes embedding_size"],
        Float[Array, "num_nodes embedding_size"],
    ]:
        """Apply WIRE to queries and keys.

        Args:
            queries: Query vectors (num_nodes, embedding_size)
            keys: Key vectors (num_nodes, embedding_size)
            positions: Node position features, e.g., RWSE (num_nodes, num_features)

        Returns:
            Rotated (queries, keys)
        """
        angles = self.get_angles(positions)
        return self.rotate(queries, angles), self.rotate(keys, angles)

__call__(queries, keys, positions)

Apply WIRE to queries and keys.

Parameters:

Name Type Description Default
queries Float[Array, 'num_nodes embedding_size']

Query vectors (num_nodes, embedding_size)

required
keys Float[Array, 'num_nodes embedding_size']

Key vectors (num_nodes, embedding_size)

required
positions Float[Array, 'num_nodes num_features']

Node position features, e.g., RWSE (num_nodes, num_features)

required

Returns:

Type Description
tuple[Float[Array, 'num_nodes embedding_size'], Float[Array, 'num_nodes embedding_size']]

Rotated (queries, keys)

Source code in xlron/models/transformer.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def __call__(
    self,
    queries: Float[Array, "num_nodes embedding_size"],
    keys: Float[Array, "num_nodes embedding_size"],
    positions: Float[Array, "num_nodes num_features"],
) -> tuple[
    Float[Array, "num_nodes embedding_size"],
    Float[Array, "num_nodes embedding_size"],
]:
    """Apply WIRE to queries and keys.

    Args:
        queries: Query vectors (num_nodes, embedding_size)
        keys: Key vectors (num_nodes, embedding_size)
        positions: Node position features, e.g., RWSE (num_nodes, num_features)

    Returns:
        Rotated (queries, keys)
    """
    angles = self.get_angles(positions)
    return self.rotate(queries, angles), self.rotate(keys, angles)

__init__(num_features, embedding_size, key, freq_scale=0.01)

Parameters:

Name Type Description Default
num_features int

Dimension of input position features (m)

required
embedding_size int

Dimension of queries/keys to rotate (must be even)

required
key PRNGKeyArray

PRNG key

required
freq_scale float

Scale for frequency initialisation

0.01
Source code in xlron/models/transformer.py
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
def __init__(
    self,
    num_features: int,
    embedding_size: int,
    key: PRNGKeyArray,
    freq_scale: float = 0.01,
):
    """
    Args:
        num_features: Dimension of input position features (m)
        embedding_size: Dimension of queries/keys to rotate (must be even)
        key: PRNG key
        freq_scale: Scale for frequency initialisation
    """
    if embedding_size % 2 != 0:
        raise ValueError("embedding_size must be even")

    self.embedding_size = embedding_size

    # Project position features to angles
    # Output dim is embedding_size // 2 (one angle per 2D rotation block)
    self.freq_proj = eqx.nn.Linear(
        in_features=num_features,
        out_features=embedding_size // 2,
        use_bias=False,
        key=key,
    )

    # Optionally scale down initial frequencies for stability
    scaled_weight = self.freq_proj.weight * freq_scale
    self.freq_proj = eqx.tree_at(lambda layer: layer.weight, self.freq_proj, scaled_weight)

get_angles(positions)

Compute rotation angles from position features.

Source code in xlron/models/transformer.py
 99
100
101
102
103
def get_angles(
    self, positions: Float[Array, "num_nodes num_features"]
) -> Float[Array, "num_nodes half_emb"]:
    """Compute rotation angles from position features."""
    return jax.vmap(self.freq_proj)(positions)

rotate(x, angles)

Apply rotary encoding to queries or keys.

For each 2D block [x_{2i}, x_{2i+1}], rotate by angle theta_i: x_{2i}' = x_{2i} * cos(theta) - x_{2i+1} * sin(theta) x_{2i+1}' = x_{2i} * sin(theta) + x_{2i+1} * cos(theta)

Source code in xlron/models/transformer.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def rotate(
    self,
    x: Float[Array, "num_nodes embedding_size"],
    angles: Float[Array, "num_nodes half_emb"],
) -> Float[Array, "num_nodes embedding_size"]:
    """Apply rotary encoding to queries or keys.

    For each 2D block [x_{2i}, x_{2i+1}], rotate by angle theta_i:
        x_{2i}'   = x_{2i} * cos(theta) - x_{2i+1} * sin(theta)
        x_{2i+1}' = x_{2i} * sin(theta) + x_{2i+1} * cos(theta)
    """
    # angles: (num_nodes, embedding_size // 2)
    cos_angles = jnp.cos(angles)
    sin_angles = jnp.sin(angles)

    # Repeat for pairs: [cos_0, cos_0, cos_1, cos_1, ...]
    cos_angles = jnp.repeat(cos_angles, 2, axis=-1)
    sin_angles = jnp.repeat(sin_angles, 2, axis=-1)

    # Rotate pairs: for indices [0,1], [2,3], etc.
    # x_rotated = x * cos + rotate_pairs(x) * sin
    # where rotate_pairs swaps and negates: [x0, x1] -> [-x1, x0]
    x_pairs = x.reshape(x.shape[0], -1, 2)  # (num_nodes, num_pairs, 2)
    x_rotated_pairs = jnp.stack([-x_pairs[..., 1], x_pairs[..., 0]], axis=-1)
    x_rotated = x_rotated_pairs.reshape(x.shape)

    return x * cos_angles + x_rotated * sin_angles

pooled_actor_projection(mlp, embeddings, paths)

Commute only the final affine projection with a path's weighted sum.

Hidden nonlinearities remain per link. The bias is multiplied by the sum of path weights, including zero for dummy paths. This keeps ordinary JAX AD. Exact because the actor MLP's final layer has an identity activation (the eqx.nn.MLP default), so sum pooling of logits equals projecting summed features.

Source code in xlron/models/transformer.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def pooled_actor_projection(mlp, embeddings, paths):
    """Commute only the final affine projection with a path's weighted sum.

    Hidden nonlinearities remain per link. The bias is multiplied by the sum
    of path weights, including zero for dummy paths. This keeps ordinary JAX AD.
    Exact because the actor MLP's final layer has an identity activation (the
    eqx.nn.MLP default), so sum pooling of logits equals projecting summed features.
    """
    hidden_mlp = eqx.tree_at(lambda m: m.layers[-1], mlp, eqx.nn.Identity())
    hidden = jax.vmap(hidden_mlp)(embeddings)
    pooled = jnp.sum(paths[:, :, None] * hidden[None, :, :], axis=1)
    final = mlp.layers[-1]
    logits = jax.vmap(lambda x: final.weight @ x)(pooled)
    if final.bias is not None:
        logits = logits + jnp.sum(paths, axis=1)[:, None] * final.bias[None, :]
    return logits

Heuristics

arbr_ff(state, params)

Adaptive Routing with Back-to-back Regeneration (ARBR). Only suitable for RSA/RMSA. Ranks the k candidate paths by an adaptive metric combining the static resource cost of serving the request with the current utilisation of the path's links, then allocates first-fit on the best-ranked path with a free block. Reference: Walkowiak, Klinkowski & Lechowicz, "Dynamic routing in spectrally spatially flexible optical networks with back-to-back regeneration", J. Opt. Commun. Netw. 10(5), 2018.

Adaptation to single-fibre RSA/RMSA without regeneration or transceiver limits: each candidate routing configuration is a single transparent path, so the static cost reduces to SL(p, d) = hops x required slots (incl. guardband), the transceiver terms of the original metric vanish (transceivers unconstrained), and the dynamic cost reduces to the maximum link utilisation (MLU) over the path's links, quantised to decile bins {10, 20, ..., 100} as in the paper. The combined metric is c_adaptive = (1 - alpha) * SL + alpha * MLU, where the tuning parameter alpha is set by --arbr_alpha (0 = static cost only, 1 = dynamic utilisation only; 0.8 is the value recommended in the paper).

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
@jax.jit
def arbr_ff(state: EnvState, params: RSAEnvParams) -> Array:
    """Adaptive Routing with Back-to-back Regeneration (ARBR). Only suitable for RSA/RMSA.
    Ranks the k candidate paths by an adaptive metric combining the static resource
    cost of serving the request with the current utilisation of the path's links,
    then allocates first-fit on the best-ranked path with a free block.
    Reference: Walkowiak, Klinkowski & Lechowicz, "Dynamic routing in spectrally
    spatially flexible optical networks with back-to-back regeneration",
    J. Opt. Commun. Netw. 10(5), 2018.

    Adaptation to single-fibre RSA/RMSA without regeneration or transceiver limits:
    each candidate routing configuration is a single transparent path, so the static
    cost reduces to SL(p, d) = hops x required slots (incl. guardband), the
    transceiver terms of the original metric vanish (transceivers unconstrained),
    and the dynamic cost reduces to the maximum link utilisation (MLU) over the
    path's links, quantised to decile bins {10, 20, ..., 100} as in the paper.
    The combined metric is c_adaptive = (1 - alpha) * SL + alpha * MLU, where the
    tuning parameter alpha is set by --arbr_alpha (0 = static cost only,
    1 = dynamic utilisation only; 0.8 is the value recommended in the paper).

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    mask, candidate_slots = get_action_mask_and_slots(state, params)
    first_slots = _first_fit_from_mask(mask, params)
    nodes_sd, _ = read_rsa_request(state.request_array)
    paths = get_paths(params, nodes_sd)
    # Static cost: slots consumed network-wide = path hops * required slots
    num_slots = jnp.take_along_axis(
        candidate_slots, jnp.minimum(first_slots, params.link_resources - 1)[:, None], axis=1
    ).squeeze(1)
    c_static = jnp.sum(paths, axis=1) * num_slots
    # Dynamic cost: max link utilisation on the path, quantised to deciles
    # (0-10% -> 10, 11-20% -> 20, ..., 91-100% -> 100)
    link_util = jnp.count_nonzero(state.link_slot_array, axis=1) / params.link_resources
    link_util_decile = jnp.clip(jnp.ceil(link_util * 10.0), 1.0, 10.0) * 10.0
    mlu = jnp.max(jnp.where(paths > 0, link_util_decile[None, :], 0.0), axis=1)
    alpha = params.arbr_alpha
    c_adaptive = (1.0 - alpha) * c_static + alpha * mlu
    # Penalise paths with no free block (mirroring kca_ff): first_fit returns
    # params.link_resources for such paths, which maps to slot 0 below, where the
    # mask is guaranteed 0 for such a path.
    slot_indices = first_slots % params.link_resources
    first_slot_valid = jnp.take_along_axis(mask, slot_indices[:, None], axis=1).squeeze(1)
    c_adaptive = jnp.where(first_slot_valid > 0, c_adaptive, jnp.inf)
    # argmin ties break towards the lower path index, i.e. k-shortest-path order
    path_index = jnp.argmin(c_adaptive)
    slot_index = first_slots[path_index] % params.link_resources
    action = path_index * params.link_resources + slot_index
    return action

best_fit(state, params)

Best-Fit Spectrum Allocation. Returns the best fit slot for each path.

Source code in xlron/heuristics/heuristics.py
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
def best_fit(state: EnvState, params: RSAEnvParams) -> Tuple[Array, Array]:
    """Best-Fit Spectrum Allocation. Returns the best fit slot for each path."""
    mask = get_action_mask(state, params)
    link_slot_array = jnp.where(state.link_slot_array < 0, 1.0, state.link_slot_array)
    nodes_sd, requested_bw = read_rsa_request(state.request_array)

    # We need to define a wrapper function in order to vmap with named arguments
    def _find_block_sizes(arr, starts_only=False, reverse=True):
        return jax.vmap(partial(find_block_sizes, differentiable=False), in_axes=(0, None, None))(
            arr, starts_only, reverse
        )

    block_sizes_right = _find_block_sizes(link_slot_array, starts_only=False, reverse=False)
    block_sizes_left = _find_block_sizes(link_slot_array, starts_only=False, reverse=True)
    block_sizes = jnp.maximum((block_sizes_left + block_sizes_right) - 1, 0)
    paths = get_paths(params, nodes_sd)
    se = (
        get_paths_se(params, nodes_sd)
        if params.consider_modulation_format
        else jnp.ones((params.k_paths,))
    )
    num_slots = jax.vmap(required_slots, in_axes=(None, 0, None, None))(
        requested_bw, se, params.slot_size, params.guardband
    )

    # Quantify how well the request fits within a free spectral block
    def get_bf_on_path(path, blocks, req_slots):
        fits = jax.vmap(lambda x: x - req_slots, in_axes=0)(blocks)
        fits = jnp.where(fits >= 0, fits, params.link_resources)
        path_fit = jnp.dot(path, fits) / jnp.sum(path)
        return path_fit

    fits_block = jax.vmap(lambda x, y, z: get_bf_on_path(x, y, z), in_axes=(0, None, 0))(
        paths, block_sizes, num_slots
    )

    # Quantity much of a gap there is between the assigned slots and the next occupied slots on the left
    def get_bf_on_path_left(path, blocks, req_slots):
        fits = jax.vmap(lambda x: x - req_slots, in_axes=0)(blocks)
        fits = jnp.where(fits >= 0, fits, params.link_resources)
        fits_shift = jax.lax.dynamic_slice(fits, (0, 1), (fits.shape[0], fits.shape[1] - 1))
        fits_shift = jnp.concatenate(
            (jnp.full((fits.shape[0], 1), params.link_resources), fits_shift), axis=1
        )
        fits = fits + 1 / jnp.maximum(fits_shift, 1)
        path_fit = jnp.dot(path, fits) / jnp.sum(path)
        return path_fit

    fits_left = jax.vmap(lambda x, y, z: get_bf_on_path_left(x, y, z), in_axes=(0, None, 0))(
        paths, block_sizes_left, num_slots
    )

    # Quantity much of a gap there is between the assigned slots and the next occupied slots on the right
    def get_bf_on_path_right(path, blocks, req_slots):
        fits = jax.vmap(lambda x: x - req_slots, in_axes=0)(blocks)
        fits = jnp.where(fits >= 0, fits, params.link_resources)
        fits_shift = jax.lax.dynamic_slice(fits, (0, 0), (fits.shape[0], fits.shape[1] - 1))
        fits_shift = jnp.concatenate(
            (fits_shift, jnp.full((fits.shape[0], 1), params.link_resources)), axis=1
        )
        fits = fits + 1 / jnp.maximum(fits_shift, 1)
        path_fit = jnp.dot(path, fits) / jnp.sum(path)
        return path_fit

    fits_right = jax.vmap(lambda x, y, z: get_bf_on_path_right(x, y, z), in_axes=(0, None, 0))(
        paths, block_sizes_right, num_slots
    )

    # Sum the contribution to the overall quality of fit, and scale down the left/right contributions
    fits = jnp.sum(
        jnp.stack(
            (fits_block, fits_left / params.link_resources, fits_right / params.link_resources),
            axis=0,
        ),
        axis=0,
    )
    # Mask out occupied lightpaths (in case the quality of fit on some links is good enough to be considered, even if the overall path is invalid)
    fits = jnp.where(mask == 0, jnp.inf, fits)
    best_slots = jnp.argmin(fits, axis=1)
    best_fits = jnp.min(fits, axis=1)
    return best_slots, best_fits

bf_ksp(state, params)

Get the first available slot from the first k-shortest paths Method: Go through action mask and find the first available slot on all paths

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
@jax.jit
def bf_ksp(state: EnvState, params: RSAEnvParams) -> Array:
    """Get the first available slot from the first k-shortest paths
    Method: Go through action mask and find the first available slot on all paths

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    best_slots, fitness = best_fit(state, params)
    # Chosen path is the one with the best fit
    path_index = jnp.argmin(fitness)
    slot_index = best_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

capacity_loss(state, params, num_interfering_routes=1)

Slot-continuity capacity loss (the MSCL metric) of every candidate (path, slot) assignment for the current request.

Capacity A future request needing w contiguous slots fits on path p at starting position i iff slots i..i+w-1 are free on every link of p. Writing run_p[i] for the length of the contiguous free run starting at slot i of p's link-aggregated spectrum (0 if slot i is occupied on any link), the number of feasible placements for size w is N_p(w) = #{i : run_p[i] >= w}, and the slot-continuity capacity of p is the total over all demand sizes:

    C_p = sum_{w=1..W} N_p(w) = sum_i min(run_p[i], W)

W is the largest possible request in slots (from the max datarate, the
lowest spectral efficiency and the slot size, plus guardband); demand
sizes are weighted uniformly, as in the original formulation.

Loss Serving the current request on route r from slot s occupies slots [s, e) on every link of r (e = s + required slots incl. guardband). That reduces C_q for r itself and for every route q sharing >= 1 link with r; spectrum elsewhere is untouched. The MSCL loss of candidate (r, s) is

    loss(r, s) = sum_{q affected} [ C_q before - C_q after ]

and the MSCL heuristics choose the candidate minimising it: a one-step
lookahead that consumes dead-end fragments and spares large aligned voids
on heavily-shared links, rather than packing blindly like first-fit.

Closed form Instead of materialising the updated spectrum for each of the k x S candidates, the per-route loss decomposes exactly into two terms computed from run-length arrays and a single prefix sum:

- inside the block: each free position i in [s, e) drops from
  min(run[i], W) to 0; summed as a difference of the prefix sum of
  min(run, W) at e and s.
- left of the block: positions i in the free run containing s (run start
  a, run end b) are truncated from run length b - i to s - i, losing
  min(b - i, W) - min(s - i, W); summing over d = s - i = 1..D with
  D = s - a and gap g = b - s gives sum_min(D, g) - sum_min(D, 0), where
  sum_min(D, off) = sum_{d=1..D} min(d + off, W) has the closed form
  t*off + t(t+1)/2 + (D-t)*W with t = clip(W - off, 0, D).

Positions at or beyond e keep their runs (a free run starting there
cannot reach back across the newly occupied block), and runs not touching
[s, e) are unaffected. If s is already occupied for a route then a = b = s
and both terms vanish for it, which is exactly right. This closed form is
verified against a brute-force before/after recount in
heuristics_test.py::CapacityLossBruteforceTest.

Interfering route set Two routes interfere when they share at least one link. The routes whose capacity loss is accounted are controlled by num_interfering_routes = n: the first n stored paths of every node pair that share a link with the candidate route, plus the candidate route itself - counted once, since a candidate with k-index below n already is one of its own pair's first n stored routes. n = 1 (the default) is the single-route-per-pair set of the original 2013 formulation. n = k_paths is the all-stored-routes set of the multi-route extension of dos Santos (2021): it also prices in the damage a placement does to a pair's alternative routes (which future traffic will actually be offered to under KSP routing), at n times the cost and memory of the single-route set. The ksp_mscl and mscl_ksp heuristics choose n via the --mscl_interfering_k flag (0 = all k_paths).

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required
num_interfering_routes int

Stored routes per node pair in the interfering set (static at trace time; 1 <= n <= k_paths)

1

References R. C. Almeida Jr., A. F. dos Santos, K. D. R. Assis, H. Waldman & J. F. Martins-Filho, "Slot assignment strategy to reduce loss of capacity of contiguous-slot path requests in flexible grid optical networks", Electronics Letters 49(5), pp. 358-360, 2013. doi:10.1049/el.2012.4247 X. Zhang & C. Qiao, "Wavelength assignment for dynamic traffic in multi-fiber WDM networks", ICCCN 1998 - the relative-capacity-loss RWA metric that MSCL generalises to contiguous-spectrum RSA/RMSA. M. L. dos Santos, "Abordagens para atribuicao de espectro em redes opticas elasticas baseadas em perda de capacidade sob multiplas rotas" (Approaches for spectrum assignment in elastic optical networks based on capacity loss under multiple routes), M.Sc. dissertation, Universidade Federal de Pernambuco, Recife, 2021. https://repositorio.ufpe.br/handle/123456789/45594 - multi-route interfering sets; the MSCL Sequencial and MSCL Combinado heuristics.

Returns:

Name Type Description
Tuple Array

(loss, mask). loss is (k_paths, link_resources) float32 with jnp.inf

Array

at invalid actions; mask is the (k_paths, link_resources) action mask.

Source code in xlron/heuristics/heuristics.py
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
def capacity_loss(
    state: EnvState, params: RSAEnvParams, num_interfering_routes: int = 1
) -> Tuple[Array, Array]:
    """Slot-continuity capacity loss (the MSCL metric) of every candidate
    (path, slot) assignment for the current request.

    Capacity
        A future request needing w contiguous slots fits on path p at starting
        position i iff slots i..i+w-1 are free on every link of p. Writing
        run_p[i] for the length of the contiguous free run starting at slot i of
        p's link-aggregated spectrum (0 if slot i is occupied on any link), the
        number of feasible placements for size w is N_p(w) = #{i : run_p[i] >= w},
        and the slot-continuity capacity of p is the total over all demand sizes:

            C_p = sum_{w=1..W} N_p(w) = sum_i min(run_p[i], W)

        W is the largest possible request in slots (from the max datarate, the
        lowest spectral efficiency and the slot size, plus guardband); demand
        sizes are weighted uniformly, as in the original formulation.

    Loss
        Serving the current request on route r from slot s occupies slots
        [s, e) on every link of r (e = s + required slots incl. guardband). That
        reduces C_q for r itself and for every route q sharing >= 1 link with r;
        spectrum elsewhere is untouched. The MSCL loss of candidate (r, s) is

            loss(r, s) = sum_{q affected} [ C_q before - C_q after ]

        and the MSCL heuristics choose the candidate minimising it: a one-step
        lookahead that consumes dead-end fragments and spares large aligned voids
        on heavily-shared links, rather than packing blindly like first-fit.

    Closed form
        Instead of materialising the updated spectrum for each of the k x S
        candidates, the per-route loss decomposes exactly into two terms computed
        from run-length arrays and a single prefix sum:

        - inside the block: each free position i in [s, e) drops from
          min(run[i], W) to 0; summed as a difference of the prefix sum of
          min(run, W) at e and s.
        - left of the block: positions i in the free run containing s (run start
          a, run end b) are truncated from run length b - i to s - i, losing
          min(b - i, W) - min(s - i, W); summing over d = s - i = 1..D with
          D = s - a and gap g = b - s gives sum_min(D, g) - sum_min(D, 0), where
          sum_min(D, off) = sum_{d=1..D} min(d + off, W) has the closed form
          t*off + t(t+1)/2 + (D-t)*W with t = clip(W - off, 0, D).

        Positions at or beyond e keep their runs (a free run starting there
        cannot reach back across the newly occupied block), and runs not touching
        [s, e) are unaffected. If s is already occupied for a route then a = b = s
        and both terms vanish for it, which is exactly right. This closed form is
        verified against a brute-force before/after recount in
        heuristics_test.py::CapacityLossBruteforceTest.

    Interfering route set
        Two routes interfere when they share at least one link. The routes whose
        capacity loss is accounted are controlled by num_interfering_routes = n:
        the first n stored paths of every node pair that share a link with the
        candidate route, plus the candidate route itself - counted once, since a
        candidate with k-index below n already is one of its own pair's first n
        stored routes. n = 1 (the default) is the single-route-per-pair set of
        the original 2013 formulation. n = k_paths is the all-stored-routes set
        of the multi-route extension of dos Santos (2021): it also prices in the
        damage a placement does to a pair's alternative routes (which future
        traffic will actually be offered to under KSP routing), at n times the
        cost and memory of the single-route set. The ksp_mscl and mscl_ksp
        heuristics choose n via the --mscl_interfering_k flag (0 = all k_paths).

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
        num_interfering_routes (int): Stored routes per node pair in the
            interfering set (static at trace time; 1 <= n <= k_paths)

    References
        R. C. Almeida Jr., A. F. dos Santos, K. D. R. Assis, H. Waldman &
        J. F. Martins-Filho, "Slot assignment strategy to reduce loss of capacity
        of contiguous-slot path requests in flexible grid optical networks",
        Electronics Letters 49(5), pp. 358-360, 2013. doi:10.1049/el.2012.4247
        X. Zhang & C. Qiao, "Wavelength assignment for dynamic traffic in
        multi-fiber WDM networks", ICCCN 1998 - the relative-capacity-loss RWA
        metric that MSCL generalises to contiguous-spectrum RSA/RMSA.
        M. L. dos Santos, "Abordagens para atribuicao de espectro em redes
        opticas elasticas baseadas em perda de capacidade sob multiplas rotas"
        (Approaches for spectrum assignment in elastic optical networks based on
        capacity loss under multiple routes), M.Sc. dissertation, Universidade
        Federal de Pernambuco, Recife, 2021.
        https://repositorio.ufpe.br/handle/123456789/45594 - multi-route
        interfering sets; the MSCL Sequencial and MSCL Combinado heuristics.

    Returns:
        Tuple: (loss, mask). loss is (k_paths, link_resources) float32 with jnp.inf
        at invalid actions; mask is the (k_paths, link_resources) action mask.
    """
    mask, num_slots = get_action_mask_and_slots(state, params)
    nodes_sd, _ = read_rsa_request(state.request_array)
    num_resources = params.link_resources

    # Maximum future demand size (in slots, incl. guardband) to account capacity for,
    # from static params so it can size arrays under jit.
    w_cap = int(np.ceil(params.max_bw / (params.min_se * float(params.slot_size))))
    w_cap = max(w_cap + int(params.guardband), 1)

    # Interfering route set: the first n stored paths of every node pair (rows of
    # the path-link array are pair-major with k consecutive rows per pair);
    # n = 1 selects every pair's shortest path only (the 2013 formulation)
    n_int = int(num_interfering_routes)
    if not 1 <= n_int <= params.k_paths:
        raise ValueError(
            f"num_interfering_routes must be in [1, k_paths={params.k_paths}], got {n_int}"
        )
    # GN appends one zero row for path_index_array == -1. It is not a
    # node-pair route, including when k_paths == 1 makes the shape divisible.
    num_route_rows = params.path_link_array.shape[0] - int(isinstance(params, GNModelEnvParams))
    if n_int == params.k_paths:
        interfering_paths = params.path_link_array[:num_route_rows]
    else:
        pair_major_rows = (
            np.arange(num_route_rows).reshape(-1, params.k_paths)[:, :n_int].reshape(-1)
        )
        interfering_paths = params.path_link_array[pair_major_rows]
    if params.pack_path_bits:
        interfering_paths = jnp.unpackbits(interfering_paths, axis=1)[:, : params.num_links]
    interfering_paths = jnp.asarray(interfering_paths, dtype=jnp.float32)
    cand_paths = jnp.asarray(get_paths(params, nodes_sd), dtype=jnp.float32)

    def prep(paths):
        free = get_path_free_arrays(state.link_slot_array, paths)
        run_len, run_start, run_end = get_run_lengths_and_bounds(free)
        # Capacity contribution of each start position, capped at the max demand size
        capped = jnp.minimum(run_len, w_cap)
        cum_cap = jnp.concatenate(
            (jnp.zeros((capped.shape[0], 1), dtype=jnp.int32), jnp.cumsum(capped, axis=-1)),
            axis=-1,
        )
        return run_start, run_end, cum_cap

    slot_indices = jnp.arange(num_resources, dtype=jnp.int32)
    # Block end (exclusive) of each candidate assignment; clipped for safe gathering
    # (assignments that overrun the spectrum are already invalid in the mask)
    ends = jnp.minimum(slot_indices[None, :] + num_slots, num_resources)

    def sum_min(d, offset):
        # sum_{i=1..d} min(i + offset, w_cap), for the left-of-block truncation term
        t = jnp.clip(w_cap - offset, 0, d)
        return t * offset + t * (t + 1) // 2 + (d - t) * w_cap

    def truncation_loss(run_start, run_end):
        # Capacity lost by positions left of the assignment whose free run is cut at s
        d = slot_indices[None, :] - run_start
        gap = run_end - slot_indices[None, :]
        return sum_min(d, gap) - sum_min(d, 0)

    intf_start, intf_end, intf_cum = prep(interfering_paths)
    cand_start, cand_end, cand_cum = prep(cand_paths)

    # Loss on the interfering routes: truncation left of s plus the capacity of
    # positions inside [s, e) that become occupied. Since the block end
    # e = s + w_r depends on the candidate path only through its width w_r, the sum
    # over interfering routes commutes with the gather at e: everything reduces to
    # matmuls over the route dimension plus one shifted gather of the aggregate,
    # avoiding a (num_pairs * n, k, S) intermediate. Aggregates can reach ~1e7 on
    # 100+-node topologies, so float32 rounding of ~1 capacity unit is possible in
    # near-tied candidates; the ranking is unaffected for practical purposes (the
    # brute-force equality test runs on small topologies where sums stay exact).
    intf_trunc = truncation_loss(intf_start, intf_end)  # (num_pairs * n, S)
    shares = (jnp.dot(cand_paths, interfering_paths.T) > 0).astype(jnp.float32)  # (k, P * n)
    base = jnp.dot(shares, (intf_trunc - intf_cum[:, :num_resources]).astype(jnp.float32))  # (k, S)
    cum_agg = jnp.dot(shares, intf_cum.astype(jnp.float32))  # (k, S + 1)
    loss = base + jnp.take_along_axis(cum_agg, ends, axis=1)

    # Same loss terms on the candidate route itself. A candidate with k-index
    # below n is already in the interfering set (it is one of its own pair's
    # first n stored routes); otherwise add its own loss explicitly
    cand_trunc = truncation_loss(cand_start, cand_end)  # (k, S)
    cand_inside = jnp.take_along_axis(cand_cum, ends, axis=1) - cand_cum[:, :num_resources]
    cand_delta = cand_trunc + cand_inside
    not_in_set = (jnp.arange(params.k_paths) >= n_int).astype(jnp.float32)[:, None]
    loss = loss + cand_delta.astype(jnp.float32) * not_in_set
    loss = jnp.where(mask == 0, jnp.inf, loss)
    return loss, mask

exact_fit(state, params)

Exact-Fit Spectrum Allocation. For each path, find free blocks whose size exactly equals the required slots for the request.

Returns:

Name Type Description
Tuple Array

(first_exact, last_exact, mask). first_exact/last_exact hold the

Array

lowest/highest exactly-fitting block start per path, or link_resources if

Array

no exact fit exists on that path.

Source code in xlron/heuristics/heuristics.py
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
def exact_fit(state: EnvState, params: RSAEnvParams) -> Tuple[Array, Array, Array]:
    """Exact-Fit Spectrum Allocation. For each path, find free blocks whose size
    exactly equals the required slots for the request.

    Returns:
        Tuple: (first_exact, last_exact, mask). first_exact/last_exact hold the
        lowest/highest exactly-fitting block start per path, or link_resources if
        no exact fit exists on that path.
    """
    mask = get_action_mask(state, params)
    nodes_sd, _ = read_rsa_request(state.request_array)
    num_slots = get_request_num_slots(state, params)
    paths = get_paths(params, nodes_sd)
    free = get_path_free_arrays(state.link_slot_array, paths)
    run_len, run_start, _ = get_run_lengths_and_bounds(free)
    slot_indices = jnp.arange(params.link_resources, dtype=jnp.int32)
    is_block_start = free & (run_start == slot_indices[None, :])
    exact = is_block_start & (run_len == num_slots[:, None]) & (mask == 1)
    # First exact-fit block start per path (link_resources if none)
    exact_pad = jnp.concatenate((exact, jnp.full((exact.shape[0], 1), True)), axis=1)
    first_exact = jnp.argmax(exact_pad, axis=1).astype(jnp.int32)
    # Last exact-fit block start per path (link_resources if none)
    last_exact = jnp.where(
        jnp.any(exact, axis=1),
        params.link_resources - jnp.argmax(exact[:, ::-1], axis=1) - 1,
        params.link_resources,
    ).astype(jnp.int32)
    return first_exact, last_exact, mask

ff_ksp(state, params)

Get the first available slot from all paths Method: Go through action mask and find the first available slot on all paths

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
@jax.jit
def ff_ksp(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """Get the first available slot from all paths
    Method: Go through action mask and find the first available slot on all paths

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    first_slots = first_fit(state, params)
    # Chosen path is the one with the lowest index of first available slot
    path_index = jnp.argmin(first_slots)
    slot_index = first_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

first_fit(state, params)

First-Fit Spectrum Allocation. Returns the first fit slot for each path.

When band_slot_order_ff is set (GN model envs with --band_preference), slots are searched in band preference order rather than raw index order.

Source code in xlron/heuristics/heuristics.py
882
883
884
885
886
887
888
889
def first_fit(state: EnvState, params: RSAEnvParams) -> Array:
    """First-Fit Spectrum Allocation. Returns the first fit slot for each path.

    When band_slot_order_ff is set (GN model envs with --band_preference),
    slots are searched in band preference order rather than raw index order.
    """
    mask = get_action_mask(state, params)
    return _first_fit_from_mask(mask, params)

flf_ksp(state, params)

First-Last-Fit across K-Shortest Paths. Small requests take the globally first available slot across all paths (ff_ksp); large requests take the globally last available slot across all paths (lf_ksp). See ksp_flf for the partitioning rationale and references.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
@jax.jit
def flf_ksp(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """First-Last-Fit across K-Shortest Paths.
    Small requests take the globally first available slot across all paths (ff_ksp);
    large requests take the globally last available slot across all paths (lf_ksp).
    See ksp_flf for the partitioning rationale and references.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    is_large = is_large_request(state, params)
    ff_action = ff_ksp(state, params)
    lf_action = lf_ksp(state, params)
    return jnp.where(is_large, lf_action, ff_action)

get_action_mask_and_slots(state, params)

Return feasible starts and the actual footprint of each (path, start).

GN resolves modulation separately for every start. Its nominal reach-based path efficiency does not describe the physically admitted footprint. Compute the mask and widths together so direct heuristic calls also use fresh formats.

Source code in xlron/heuristics/heuristics.py
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
def get_action_mask_and_slots(state: EnvState, params: RSAEnvParams) -> Tuple[Array, Array]:
    """Return feasible starts and the actual footprint of each (path, start).

    GN resolves modulation separately for every start. Its nominal reach-based
    path efficiency does not describe the physically admitted footprint. Compute
    the mask and widths together so direct heuristic calls also use fresh formats.
    """
    if isinstance(params, RMSAGNModelEnvParams):
        updated = _gn_mask_state(state, params)
        formats = updated.mod_format_mask.reshape(params.k_paths, -1).astype(jnp.int32)
        mask = formats >= 0
        efficiencies = params.modulations_array[jnp.maximum(formats, 0), 1]
        _, requested_bw = read_rsa_request(state.request_array)
        slots = required_slots(requested_bw, efficiencies, params.slot_size, params.guardband)
    else:
        mask = get_action_mask(state, params)
        slots = jnp.broadcast_to(get_request_num_slots(state, params)[:, None], mask.shape)
    return mask, slots.astype(jnp.int32)

Get link weights based on occupancy for use in congestion-aware routing heuristics.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array

Link weights

Source code in xlron/heuristics/heuristics.py
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
def get_link_weights(state: EnvState, params: RSAEnvParams):
    """Get link weights based on occupancy for use in congestion-aware routing heuristics.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Link weights
    """
    if isinstance(params, RWALightpathReuseEnvParams):
        rwalr_state = cast(RWALightpathReuseEnvState, state)
        initial_path_capacity = params.initial_path_capacity_array
        initial_path_capacity = jnp.squeeze(
            jax.vmap(lambda x: initial_path_capacity[x])(rwalr_state.path_index_array)
        )
        utilisation = (
            jnp.where(
                initial_path_capacity - rwalr_state.link_capacity_array < 0,
                0,
                initial_path_capacity - rwalr_state.link_capacity_array,
            )
            / initial_path_capacity
        )
        link_occupancy = jnp.sum(utilisation, axis=1)
    else:
        link_occupancy = jnp.count_nonzero(state.link_slot_array, axis=1)
    link_weights = jnp.multiply(
        params.link_length_array.T, (1 / (1 - link_occupancy / (params.link_resources + 1)))
    )[0]
    return link_weights

get_path_free_arrays(link_slot_array, path_links)

Aggregate slot occupancy over the links of each path.

Parameters:

Name Type Description Default
link_slot_array Array

(num_links, num_slots) array; nonzero = occupied

required
path_links Array

(num_paths, num_links) binary path-link incidence

required

Returns:

Name Type Description
Array Array

bool (num_paths, num_slots); True where the slot is free on every link

Source code in xlron/heuristics/heuristics.py
973
974
975
976
977
978
979
980
981
982
983
984
985
def get_path_free_arrays(link_slot_array: Array, path_links: Array) -> Array:
    """Aggregate slot occupancy over the links of each path.

    Args:
        link_slot_array: (num_links, num_slots) array; nonzero = occupied
        path_links: (num_paths, num_links) binary path-link incidence

    Returns:
        Array: bool (num_paths, num_slots); True where the slot is free on every link
    """
    occupied = jnp.where(link_slot_array != 0, 1.0, 0.0)
    path_occ = jnp.dot(path_links.astype(jnp.float32), occupied)
    return path_occ == 0

get_request_num_slots(state, params)

Required slots (incl. guardband) for the current request on each of the k paths.

Source code in xlron/heuristics/heuristics.py
939
940
941
942
943
944
945
946
947
948
949
950
def get_request_num_slots(state: EnvState, params: RSAEnvParams) -> Array:
    """Required slots (incl. guardband) for the current request on each of the k paths."""
    nodes_sd, requested_bw = read_rsa_request(state.request_array)
    se = (
        get_paths_se(params, nodes_sd)
        if params.consider_modulation_format
        else jnp.ones((params.k_paths,))
    )
    num_slots = jax.vmap(required_slots, in_axes=(None, 0, None, None))(
        requested_bw, se, params.slot_size, params.guardband
    )
    return num_slots.astype(jnp.int32)

get_run_lengths_and_bounds(free)

For each slot position, the length of the free run starting there and the [start, end) bounds of the free run containing it.

Parameters:

Name Type Description Default
free Array

bool (..., num_slots)

required

Returns:

Name Type Description
Tuple Array

(run_len, run_start, run_end), each (..., num_slots) int32.

Array

For occupied positions run_len = 0 and run_start = run_end = position.

Source code in xlron/heuristics/heuristics.py
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
def get_run_lengths_and_bounds(free: Array) -> Tuple[Array, Array, Array]:
    """For each slot position, the length of the free run starting there and the
    [start, end) bounds of the free run containing it.

    Args:
        free: bool (..., num_slots)

    Returns:
        Tuple: (run_len, run_start, run_end), each (..., num_slots) int32.
        For occupied positions run_len = 0 and run_start = run_end = position.
    """
    num_slots = free.shape[-1]
    axis = free.ndim - 1  # associative_scan(reverse=True) requires a non-negative axis
    idx = jnp.arange(num_slots, dtype=jnp.int32)
    prev_occ = jax.lax.associative_scan(jnp.maximum, jnp.where(free, -1, idx), axis=axis)
    next_occ = jax.lax.associative_scan(
        jnp.minimum, jnp.where(free, num_slots, idx), axis=axis, reverse=True
    )
    run_start = jnp.where(free, prev_occ + 1, idx)
    run_end = jnp.where(free, next_occ, idx)
    run_len = jnp.where(free, next_occ - idx, 0)
    return run_len, run_start, run_end

is_large_request(state, params)

Classify the current request as large (True) or small (False) by comparing its datarate to the midpoint of the requestable datarate range. Used by the first-last-fit family to segregate request size classes at opposite spectrum ends.

Source code in xlron/heuristics/heuristics.py
930
931
932
933
934
935
936
def is_large_request(state: EnvState, params: RSAEnvParams) -> Array:
    """Classify the current request as large (True) or small (False) by comparing its
    datarate to the midpoint of the requestable datarate range. Used by the
    first-last-fit family to segregate request size classes at opposite spectrum ends."""
    _, requested_bw = read_rsa_request(state.request_array)
    threshold = (jnp.min(params.values_bw) + jnp.max(params.values_bw)) / 2
    return requested_bw > threshold

kca_ff(state, params)

Congestion-aware First Fit. Only suitable for RSA/RMSA. Method:

Source code in xlron/heuristics/heuristics.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
@jax.jit
def kca_ff(state: EnvState, params: RSAEnvParams) -> Array:
    """Congestion-aware First Fit. Only suitable for RSA/RMSA.
    Method:

    """
    mask = get_action_mask(state, params)
    # Get index of first available slots for each path
    first_slots = first_fit(state, params)
    # Get nodes
    nodes_sd, _ = read_rsa_request(state.request_array)
    # Initialise array to hold congestion on each path
    path_congestion_array = jnp.full((mask.shape[0],), 0.0)
    link_weights = get_link_weights(state, params)

    def get_path_congestion(i, val):
        # Get links on path
        path = get_paths(params, nodes_sd)[i]
        # Get congestion
        path_link_congestion = jnp.multiply(link_weights, path)
        path_congestion = jnp.sum(path_link_congestion).reshape((1,))
        return jax.lax.dynamic_update_slice(val, path_congestion, (i,))

    path_congestion_array = jax.lax.fori_loop(
        0, mask.shape[0], get_path_congestion, path_congestion_array
    )
    # Penalise infeasible paths (mirroring kmc_ff/kmf_ff/kme_ff) so congestion only
    # ranks paths that can actually fit the request. first_fit returns
    # params.link_resources for a path with no valid block, which maps to slot 0
    # below, where the mask is guaranteed 0 for such a path.
    slot_indices = first_slots % params.link_resources
    first_slot_valid = jnp.take_along_axis(mask, slot_indices[:, None], axis=1).squeeze(1)
    path_congestion_array = jnp.where(first_slot_valid > 0, path_congestion_array, jnp.inf)
    path_index = jnp.argmin(path_congestion_array)
    slot_index = first_slots[path_index] % params.link_resources
    action = path_index * params.link_resources + slot_index
    return action

kmc_ff(state, params)

K-Minimum Cut. Only suitable for RSA/RMSA. Method: 1. Go through action mask and find the first available slot on all paths. 2. For each path, allocate the first available slot. 3. Sum number of new consecutive zero regions (cuts) created by assignment (on each link) 4. Choose path that creates the fewest cuts.

Source code in xlron/heuristics/heuristics.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
@jax.jit
def kmc_ff(state: EnvState, params: RSAEnvParams) -> Array:
    """K-Minimum Cut. Only suitable for RSA/RMSA.
    Method:
    1. Go through action mask and find the first available slot on all paths.
    2. For each path, allocate the first available slot.
    3. Sum number of new consecutive zero regions (cuts) created by assignment (on each link)
    4. Choose path that creates the fewest cuts.
    """
    mask = get_action_mask(state, params)
    first_slots = first_fit(state, params)
    link_slot_array = jnp.where(state.link_slot_array < 0, 1.0, state.link_slot_array)
    nodes_sd, requested_bw = read_rsa_request(state.request_array)
    block_sizes = jax.vmap(partial(find_block_sizes, differentiable=False), in_axes=(0,))(
        link_slot_array
    )
    block_sizes_mask = jnp.where(
        block_sizes > 0, 1, 0.0
    )  # Binary array showing initial block starts
    block_count = jnp.sum(block_sizes_mask, axis=1)

    def get_cuts_on_path(i, result):
        initial_slot_index = first_slots[i] % params.link_resources
        path = get_paths(params, nodes_sd)[i]
        se = get_paths_se(params, nodes_sd)[i] if params.consider_modulation_format else 1
        num_slots = required_slots(requested_bw, se, params.slot_size, guardband=params.guardband)
        affected_slots_mask = get_affected_slots_mask(initial_slot_index, num_slots, path, params)
        # Make link-slot_array positive
        updated_slots = set_path_links(link_slot_array, affected_slots_mask, 1.0)
        updated_block_sizes = jax.vmap(
            partial(find_block_sizes, differentiable=False), in_axes=(0,)
        )(updated_slots)
        updated_block_sizes_mask = jnp.where(
            updated_block_sizes > 0, 1, 0
        )  # Binary array showing updated block starts
        updated_block_count = jnp.sum(updated_block_sizes_mask, axis=1)
        num_cuts = jax.lax.cond(
            mask[i][initial_slot_index] == 0.0,  # If true, no valid action for path
            lambda x: jnp.full((1,), params.link_resources * params.num_links).astype(
                jnp.float32
            ),  # Return max no. of cuts
            lambda x: jnp.sum(jnp.maximum(updated_block_count - block_count, 0.0)).reshape(
                (1,)
            ),  # Else, return number of cuts
            1.0,
        )
        result = jax.lax.dynamic_update_slice(result, num_cuts, (i,))
        return result

    # Initialise array to hold number of cuts on each path
    path_cuts_array = jnp.full((mask.shape[0],), 0.0)
    path_cuts_array = jax.lax.fori_loop(0, mask.shape[0], get_cuts_on_path, path_cuts_array)
    path_index = jnp.argmin(path_cuts_array)
    slot_index = first_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

kme_ff(state, params)

K-Minimum Entropy. Only suitable for RSA/RMSA. Method: 1. Go through action mask and find the first available slot on all paths. 2. For each path, allocate the first available slot. 3. Sum the change in Shannon fragmentation entropy of the path's links caused by the assignment (Wright, Parker & Lord, JOCN 2015). 4. Choose path whose assignment increases entropy the least.

Source code in xlron/heuristics/heuristics.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
@jax.jit
def kme_ff(state: EnvState, params: RSAEnvParams) -> Array:
    """K-Minimum Entropy. Only suitable for RSA/RMSA.
    Method:
    1. Go through action mask and find the first available slot on all paths.
    2. For each path, allocate the first available slot.
    3. Sum the change in Shannon fragmentation entropy of the path's links
       caused by the assignment (Wright, Parker & Lord, JOCN 2015).
    4. Choose path whose assignment increases entropy the least.
    """
    mask = get_action_mask(state, params)
    first_slots = first_fit(state, params)
    link_slot_array = jnp.where(state.link_slot_array < 0, 1.0, state.link_slot_array)
    nodes_sd, requested_bw = read_rsa_request(state.request_array)
    max_entropy = jnp.sum(jnp.log(params.link_resources)) * params.num_links

    def get_link_entropy(blocks):
        ent = jax.vmap(
            lambda x: jnp.sum(x / params.link_resources * jnp.log(params.link_resources / x)),
            in_axes=0,
        )(blocks)
        return jnp.sum(jnp.where(blocks > 0, ent, 0))

    # Baseline per-link entropy before allocation, so paths are ranked by the
    # entropy change their allocation causes rather than the absolute
    # post-allocation entropy (which conflates the allocation's impact with the
    # path's length and existing fragmentation)
    base_block_sizes = jax.vmap(find_block_sizes, in_axes=(0,))(link_slot_array)
    base_entropy = jax.vmap(get_link_entropy, in_axes=(0,))(base_block_sizes)

    def get_entropy_on_path(i, result):
        initial_slot_index = first_slots[i] % params.link_resources
        path = get_paths(params, nodes_sd)[i]
        se = get_paths_se(params, nodes_sd)[i] if params.consider_modulation_format else 1
        num_slots = required_slots(requested_bw, se, params.slot_size, guardband=params.guardband)
        affected_slots_mask = get_affected_slots_mask(initial_slot_index, num_slots, path, params)
        # Make link-slot_array positive
        updated_slots = set_path_links(link_slot_array, affected_slots_mask, 1.0)
        updated_block_sizes = jax.vmap(
            partial(find_block_sizes, differentiable=False), in_axes=(0,)
        )(updated_slots)
        updated_entropy = jax.vmap(get_link_entropy, in_axes=(0,))(updated_block_sizes)
        new_path_entropy = jnp.sum(jnp.dot(path, updated_entropy - base_entropy)).reshape((1,))
        new_path_entropy = jax.lax.cond(
            mask[i][initial_slot_index] == 0.0,  # If true, no valid action for path
            lambda x: max_entropy.astype(jnp.float32).reshape((1,)),  # Return maximum entropy
            lambda x: new_path_entropy,  # Else, return number of cuts
            1.0,
        )
        result = jax.lax.dynamic_update_slice(result, new_path_entropy, (i,))
        return result

    path_entropy_array = jnp.full((mask.shape[0],), 0.0)
    path_entropy_array = jax.lax.fori_loop(
        0, mask.shape[0], get_entropy_on_path, path_entropy_array
    )
    path_index = jnp.argmin(path_entropy_array)
    slot_index = first_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

kmf_ff(state, params)

K-Minimum Frag-size. Only suitable for RSA/RMSA. Method: 1. Go through action mask and find the first available slot on all paths. 2. For each path, allocate the first available slot. 3. Sum number of new consecutive zero regions (cuts) created by assignment (on each link) 4. Choose path that creates the fewest cuts.

Source code in xlron/heuristics/heuristics.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
567
568
569
570
571
572
573
574
575
@jax.jit
def kmf_ff(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """K-Minimum Frag-size. Only suitable for RSA/RMSA.
    Method:
    1. Go through action mask and find the first available slot on all paths.
    2. For each path, allocate the first available slot.
    3. Sum number of new consecutive zero regions (cuts) created by assignment (on each link)
    4. Choose path that creates the fewest cuts.
    """
    mask = get_action_mask(state, params)
    first_slots = first_fit(state, params)
    link_slot_array = jnp.where(state.link_slot_array < 0, 1.0, state.link_slot_array)
    nodes_sd, requested_bw = read_rsa_request(state.request_array)
    blocks = jax.vmap(partial(find_block_sizes, differentiable=False), in_axes=(0,))(
        link_slot_array
    )

    def get_frags_on_path(i, result):
        initial_slot_index = first_slots[i] % params.link_resources
        path = get_paths(params, nodes_sd)[i]
        se = get_paths_se(params, nodes_sd)[i] if params.consider_modulation_format else 1
        num_slots = required_slots(requested_bw, se, params.slot_size, guardband=params.guardband)
        affected_slots_mask = get_affected_slots_mask(initial_slot_index, num_slots, path, params)
        # Mask on path links
        block_sizes = jax.vmap(lambda x, y: jnp.where(x > 0, y, 0.0), in_axes=(0, 0))(path, blocks)
        updated_slots = set_path_links(state.link_slot_array, affected_slots_mask, -1)
        updated_block_sizes = jax.vmap(
            partial(find_block_sizes, differentiable=False), in_axes=(0,)
        )(updated_slots)
        # Mask on path links
        updated_block_sizes = jax.vmap(lambda x, y: jnp.where(x > 0, y, 0.0), in_axes=(0, 0))(
            path, updated_block_sizes
        )
        difference = updated_block_sizes - block_sizes
        new_frags = jnp.where(difference != 0, block_sizes + difference, 0.0)
        # Slice new frags up to initial slot index (so as to only consider frags to the left)
        new_frags = jnp.where(
            jnp.arange(params.link_resources) < initial_slot_index, new_frags, 0.0
        )
        new_frag_size = jnp.sum(new_frags)
        num_frags = jax.lax.cond(
            mask[i][initial_slot_index] == 0.0,  # If true, no valid action for path
            lambda x: jnp.full(
                (1,), float(params.link_resources * params.num_links)
            ),  # Return max frag size
            lambda x: new_frag_size.reshape((1,)),
            # Else, return number of cuts
            1.0,
        )
        result = jax.lax.dynamic_update_slice(result, num_frags, (i,))
        return result

    # Initialise array to hold number of cuts on each path
    path_frags_array = jnp.full((mask.shape[0],), 0.0)
    path_frags_array = jax.lax.fori_loop(0, mask.shape[0], get_frags_on_path, path_frags_array)
    path_index = jnp.argmin(path_frags_array)
    slot_index = first_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

ksp_bf(state, params)

Get the first available slot from all k-shortest paths Method: Go through action mask and find the first available slot, starting from shortest path

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
@jax.jit
def ksp_bf(state: EnvState, params: RSAEnvParams) -> Array:
    """Get the first available slot from all k-shortest paths
    Method: Go through action mask and find the first available slot, starting from shortest path

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    best_slots, fitness = best_fit(state, params)
    # Chosen path is the first one with an available slot
    path_index = jnp.argmin(jnp.where(fitness < jnp.inf, 0, 1))
    slot_index = best_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

ksp_ef(state, params)

K-Shortest Path, Exact-Fit. Only suitable for RSA/RMSA. On the shortest available path, allocate the first free block whose size exactly matches the required slots; if no exact-fit block exists, fall back to first-fit. Exact-fit consumes blocks whole, avoiding the creation of small unusable fragments. Reference: Chatterjee, Sarma & Oki, "Routing and spectrum allocation in elastic optical networks: A tutorial", IEEE Comms. Surveys & Tutorials 17(3), 2015.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@jax.jit
def ksp_ef(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """K-Shortest Path, Exact-Fit. Only suitable for RSA/RMSA.
    On the shortest available path, allocate the first free block whose size exactly
    matches the required slots; if no exact-fit block exists, fall back to first-fit.
    Exact-fit consumes blocks whole, avoiding the creation of small unusable fragments.
    Reference: Chatterjee, Sarma & Oki, "Routing and spectrum allocation in elastic
    optical networks: A tutorial", IEEE Comms. Surveys & Tutorials 17(3), 2015.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    first_exact, _, _ = exact_fit(state, params)
    first_slots = first_fit(state, params)
    # Chosen path is the first one with an available slot (as in ksp_ff)
    path_index = jnp.argmax(first_slots < params.link_resources)
    slot_index = jnp.where(
        first_exact[path_index] < params.link_resources,
        first_exact[path_index],
        first_slots[path_index] % params.link_resources,
    )
    action = path_index * params.link_resources + slot_index
    return action

ksp_ff(state, params)

Get the first available slot from the shortest available path Method: Go through action mask and find the first available slot, starting from shortest path

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
@jax.jit
def ksp_ff(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """Get the first available slot from the shortest available path
    Method: Go through action mask and find the first available slot, starting from shortest path

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    first_slots = first_fit(state, params)
    # Chosen path is the first one with an available slot
    path_index = jnp.argmax(first_slots < params.link_resources)
    slot_index = first_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

ksp_ff_multiband(state, params)

Get the first available slot from all k-shortest paths in multiband scenario Method: Go through action mask and find the first available slot, starting from shortest path

Parameters:

Name Type Description Default
state MultiBandRSAEnvState

Environment state specific to multiband operations

required
params MultiBandRSAEnvParams

Environment parameters including multiband details

required

Returns: Array: Action

Source code in xlron/heuristics/heuristics.py
64
65
66
67
68
69
70
71
72
73
74
def ksp_ff_multiband(state: EnvState, params: RSAEnvParams) -> None:
    """Get the first available slot from all k-shortest paths in multiband scenario
    Method: Go through action mask and find the first available slot, starting from shortest path

    Args:
        state (MultiBandRSAEnvState): Environment state specific to multiband operations
        params (MultiBandRSAEnvParams): Environment parameters including multiband details
    Returns:
        Array: Action
    """
    pass

ksp_flef(state, params)

K-Shortest Path, First-Last-Exact-Fit. Only suitable for RSA/RMSA. On the shortest available path: small requests take the lowest exactly-fitting free block, falling back to first-fit; large requests take the highest exactly-fitting free block, falling back to last-fit. Combines the size-class segregation of first-last-fit with exact-fit's fragment avoidance. Reference: Chatterjee, Fadini & Oki, "A spectrum allocation scheme based on first-last-exact fit policy for elastic optical networks", JNCA 68, 2016.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@jax.jit
def ksp_flef(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """K-Shortest Path, First-Last-Exact-Fit. Only suitable for RSA/RMSA.
    On the shortest available path: small requests take the lowest exactly-fitting
    free block, falling back to first-fit; large requests take the highest
    exactly-fitting free block, falling back to last-fit. Combines the size-class
    segregation of first-last-fit with exact-fit's fragment avoidance.
    Reference: Chatterjee, Fadini & Oki, "A spectrum allocation scheme based on
    first-last-exact fit policy for elastic optical networks", JNCA 68, 2016.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    is_large = is_large_request(state, params)
    first_exact, last_exact, _ = exact_fit(state, params)
    first_slots = first_fit(state, params)
    last_slots = last_fit(state, params)
    # Chosen path is the first one with an available slot (as in ksp_ff)
    path_index = jnp.argmax(first_slots < params.link_resources)
    small_slot = jnp.where(
        first_exact[path_index] < params.link_resources,
        first_exact[path_index],
        first_slots[path_index] % params.link_resources,
    )
    large_slot = jnp.where(
        last_exact[path_index] < params.link_resources,
        last_exact[path_index],
        last_slots[path_index] % params.link_resources,
    )
    slot_index = jnp.where(is_large, large_slot, small_slot)
    action = path_index * params.link_resources + slot_index
    return action

ksp_flf(state, params)

K-Shortest Path, First-Last-Fit. On the shortest available path, allocate small requests first-fit (from the low end of the spectrum) and large requests last-fit (from the high end). Requests are "large" if their datarate exceeds the midpoint of the requestable range. Segregating request sizes to opposite spectrum ends reduces the size-mismatch fragmentation that a single first-fit pointer creates. Reference: Fadini & Oki, "A subcarrier-slot partition scheme for wavelength assignment in elastic optical networks", IEEE ICC 2014; Chatterjee, Sarma & Oki, IEEE Comms. Surveys & Tutorials 17(3), 2015.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
@jax.jit
def ksp_flf(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """K-Shortest Path, First-Last-Fit.
    On the shortest available path, allocate small requests first-fit (from the low
    end of the spectrum) and large requests last-fit (from the high end). Requests
    are "large" if their datarate exceeds the midpoint of the requestable range.
    Segregating request sizes to opposite spectrum ends reduces the size-mismatch
    fragmentation that a single first-fit pointer creates.
    Reference: Fadini & Oki, "A subcarrier-slot partition scheme for wavelength
    assignment in elastic optical networks", IEEE ICC 2014; Chatterjee, Sarma & Oki,
    IEEE Comms. Surveys & Tutorials 17(3), 2015.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    is_large = is_large_request(state, params)
    ff_action = ksp_ff(state, params)
    lf_action = ksp_lf(state, params)
    return jnp.where(is_large, lf_action, ff_action)

ksp_lf(state, params)

Get the last available slot on the shortest available path Method: Go through action mask and find the last available slot, starting from shortest path

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@jax.jit
def ksp_lf(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """Get the last available slot on the shortest available path
    Method: Go through action mask and find the last available slot, starting from shortest path

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    last_slots = last_fit(state, params)
    # Chosen path is the first one with an available slot.
    # last_fit signals "no slot" with -1 (standard branch) or
    # params.link_resources (GN band-order branch); exclude both.
    available = (last_slots >= 0) & (last_slots < params.link_resources)
    path_index = jnp.argmax(available)
    slot_index = last_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

ksp_mscl(state, params)

K-Shortest Path, Minimum Slot-continuity Capacity Loss (MSCL). Only suitable for RSA/RMSA.

Path selection follows KSP order (first candidate path with any valid slot, exactly as in ksp_ff); the slot on that path is then chosen to minimise the slot-continuity capacity loss. In short: every placement destroys some of the network's remaining ability to host future contiguous-slot requests - on the chosen route and on every route sharing a link with it. MSCL evaluates that destruction exactly, one step ahead, for every candidate slot, and picks the placement that destroys least. See capacity_loss for the metric definition, the closed-form computation, and full references.

The loss is accounted over the first --mscl_interfering_k stored routes of every node pair sharing a link with the candidate path (0 = all k_paths). With the default of 1 this is the single-route interfering set of the original 2013 formulation; with 0 it is the multi-route set of dos Santos (2021), whose MSCL Sequencial is exactly this heuristic (sequential route choice, min-loss slot). Cost scales linearly with the interfering-set size.

References

R. C. Almeida Jr. et al., "Slot assignment strategy to reduce loss of capacity of contiguous-slot path requests in flexible grid optical networks", Electronics Letters 49(5), 2013, doi:10.1049/el.2012.4247. M. L. dos Santos, "Abordagens para atribuicao de espectro em redes opticas elasticas baseadas em perda de capacidade sob multiplas rotas", M.Sc. dissertation, Universidade Federal de Pernambuco, Recife, 2021, sec. 3.1 (MSCL Sequencial). https://repositorio.ufpe.br/handle/123456789/45594

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
@jax.jit
def ksp_mscl(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """K-Shortest Path, Minimum Slot-continuity Capacity Loss (MSCL).
    Only suitable for RSA/RMSA.

    Path selection follows KSP order (first candidate path with any valid slot,
    exactly as in ksp_ff); the slot on that path is then chosen to minimise the
    slot-continuity capacity loss. In short: every placement destroys some of the
    network's remaining ability to host future contiguous-slot requests - on the
    chosen route and on every route sharing a link with it. MSCL evaluates that
    destruction exactly, one step ahead, for every candidate slot, and picks the
    placement that destroys least. See capacity_loss for the metric definition,
    the closed-form computation, and full references.

    The loss is accounted over the first --mscl_interfering_k stored routes of
    every node pair sharing a link with the candidate path (0 = all k_paths).
    With the default of 1 this is the single-route interfering set of the
    original 2013 formulation; with 0 it is the multi-route set of dos Santos
    (2021), whose MSCL Sequencial is exactly this heuristic (sequential route
    choice, min-loss slot). Cost scales linearly with the interfering-set size.

    References:
        R. C. Almeida Jr. et al., "Slot assignment strategy to reduce loss of
        capacity of contiguous-slot path requests in flexible grid optical
        networks", Electronics Letters 49(5), 2013, doi:10.1049/el.2012.4247.
        M. L. dos Santos, "Abordagens para atribuicao de espectro em redes
        opticas elasticas baseadas em perda de capacidade sob multiplas rotas",
        M.Sc. dissertation, Universidade Federal de Pernambuco, Recife, 2021,
        sec. 3.1 (MSCL Sequencial).
        https://repositorio.ufpe.br/handle/123456789/45594

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    n_int = _mscl_num_interfering_routes(params)
    loss, mask = capacity_loss(state, params, num_interfering_routes=n_int)
    # Chosen path is the first one with an available slot
    available_paths = jnp.max(mask, axis=1)
    path_index = jnp.argmax(available_paths)
    slot_index = jnp.argmin(loss[path_index])
    action = path_index * params.link_resources + slot_index
    return action

ksp_mu(state, params, unique_lightpaths, relative)

Get the most-used slot on the shortest available path. Method: Go through action mask and find the utilisation of available slots on each path. Find the shortest available path and choose the most utilised slot on that path.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required
unique_lightpaths bool

Whether to consider unique lightpaths

required
relative bool

Whether to return relative utilisation

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
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
@partial(jax.jit, static_argnums=(2, 3))
def ksp_mu(state: EnvState, params: RSAEnvParams, unique_lightpaths: bool, relative: bool) -> Array:
    """Get the most-used slot on the shortest available path.
    Method: Go through action mask and find the utilisation of available slots on each path.
    Find the shortest available path and choose the most utilised slot on that path.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
        unique_lightpaths (bool): Whether to consider unique lightpaths
        relative (bool): Whether to return relative utilisation

    Returns:
        Array: Action
    """
    mask = get_action_mask(state, params)
    most_used_slots = most_used(state, params, unique_lightpaths, relative)
    # Get usage of available slots
    most_used_mask = most_used_slots * mask
    # Get index of most-used available slot for each path
    most_used_slots = jnp.argmax(most_used_mask, axis=1).astype(jnp.int32)
    # Chosen path is the first one with an available slot
    available_paths = jnp.max(mask, axis=1)
    path_index = jnp.argmax(available_paths)
    slot_index = most_used_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

last_fit(state, params)

Last-Fit Spectrum Allocation. Returns the last fit slot for each path.

When band_slot_order_lf is set (GN model envs with --band_preference), slots are searched in band preference order (descending within each band).

Source code in xlron/heuristics/heuristics.py
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
def last_fit(state: EnvState, params: RSAEnvParams) -> Array:
    """Last-Fit Spectrum Allocation. Returns the last fit slot for each path.

    When band_slot_order_lf is set (GN model envs with --band_preference),
    slots are searched in band preference order (descending within each band).
    """
    mask = get_action_mask(state, params)
    if isinstance(params, GNModelEnvParams) and len(params.band_slot_order_lf) > 0:
        order = params.band_slot_order_lf
        reordered = mask[:, order]
        reordered = jnp.concatenate((reordered, jnp.full((reordered.shape[0], 1), 1)), axis=1)
        idx = jnp.argmax(reordered, axis=1)
        safe_idx = jnp.clip(idx, 0, params.link_resources - 1)
        last_slots = jnp.where(idx < params.link_resources, order[safe_idx], params.link_resources)
    else:
        # Add a column of ones to make sure occupied paths have non-zero index in "last_slots"
        mask = jnp.concatenate((jnp.full((mask.shape[0], 1), 1), mask), axis=1)
        last_slots = jnp.argmax(mask[:, ::-1], axis=1)
        last_slots = params.link_resources - last_slots - 1
    return last_slots

lf_ksp(state, params)

Get the last available slot from all paths Method: Go through action mask and find the last available slot on all paths

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
@jax.jit
def lf_ksp(state: EnvState, params: RSAEnvParams) -> Array:
    """Get the last available slot from all paths
    Method: Go through action mask and find the last available slot on all paths

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    last_slots = last_fit(state, params)
    # Normalise the GN band-order "no slot" sentinel (params.link_resources) to -1
    # (the standard branch sentinel) so fully-occupied paths lose the argmax below
    last_slots = jnp.where(last_slots >= params.link_resources, -1, last_slots)
    # Chosen path is the one with the highest index of last available slot
    # (treat the band-ordered GN-model no-slot sentinel of link_resources as invalid)
    last_slots = jnp.where(last_slots < params.link_resources, last_slots, -1)
    path_index = jnp.argmax(last_slots)
    slot_index = last_slots[path_index] % params.link_resources
    # Convert indices to action
    action = path_index * params.link_resources + slot_index
    return action

most_used(state, params, unique_lightpaths, relative)

Get the amount of utilised bandwidth on each lightpath. If RWA-LR environment, the utilisation of a slot is defined by either the count of unique active lightpahts on the slot (if unique_lightpaths is True) or the count of active lightpaths on the slot (if unique_lightpaths is False). If RSA-type environment, utilisation is the count of active lightpaths on that slot.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required
unique_lightpaths bool

Whether to consider unique lightpaths

required
relative bool

Whether to return relative utilisation

required

Returns:

Name Type Description
Array Array

Most used slots (array length = link_resources)

Source code in xlron/heuristics/heuristics.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
@partial(jax.jit, static_argnums=(2, 3))
def most_used(state: EnvState, params: RSAEnvParams, unique_lightpaths, relative) -> Array:
    """Get the amount of utilised bandwidth on each lightpath.
    If RWA-LR environment, the utilisation of a slot is defined by either the count of unique active lightpahts on the
    slot (if unique_lightpaths is True) or the count of active lightpaths on the slot (if unique_lightpaths is False).
    If RSA-type environment, utilisation is the count of active lightpaths on that slot.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
        unique_lightpaths (bool): Whether to consider unique lightpaths
        relative (bool): Whether to return relative utilisation

    Returns:
        Array: Most used slots (array length = link_resources)
    """
    if isinstance(params, RWALightpathReuseEnvParams) and unique_lightpaths:
        rwalr_state = cast(RWALightpathReuseEnvState, state)
        most_used_slots = jnp.count_nonzero(rwalr_state.path_index_array + 1, axis=0) + 1
    elif isinstance(params, RWALightpathReuseEnvParams) and not unique_lightpaths:
        rwalr_state = cast(RWALightpathReuseEnvState, state)
        # Get initial path capacity
        initial_path_capacity = params.initial_path_capacity_array
        initial_path_capacity = jnp.squeeze(
            jax.vmap(lambda x: initial_path_capacity[x])(rwalr_state.path_index_array)
        )
        utilisation = jnp.where(
            initial_path_capacity - rwalr_state.link_capacity_array < 0,
            0,
            initial_path_capacity - rwalr_state.link_capacity_array,
        )
        if relative:
            utilisation = utilisation / initial_path_capacity
        # Get most used slots by summing the utilisation along the slots
        most_used_slots = jnp.sum(utilisation, axis=0) + 1
    else:
        most_used_slots = jnp.count_nonzero(state.link_slot_array, axis=0) + 1
    return most_used_slots

mscl_ksp(state, params)

Minimum Slot-continuity Capacity Loss (MSCL) across K-Shortest Paths. Only suitable for RSA/RMSA.

Jointly selects the (path, slot) pair minimising the slot-continuity capacity loss over all k candidate paths and all slots - i.e. routing and spectrum assignment are decided together by the same one-step-lookahead metric, rather than fixing the path first as ksp_mscl does. Ties break to the shortest path, then the lowest slot index. See capacity_loss for the metric definition, the closed-form computation, and full references.

The loss is accounted over the first --mscl_interfering_k stored routes of every node pair sharing a link with the candidate path (0 = all k_paths). With the default of 1 this is the single-route interfering set of the original 2013 formulation; with 0 it is the multi-route set of dos Santos (2021), whose MSCL Combinado is exactly this heuristic (joint route-slot choice; the flowchart's strict-improvement scan over routes and slots in order yields the same tie-breaks as the flattened argmin here). Cost scales linearly with the interfering-set size.

References

R. C. Almeida Jr. et al., Electronics Letters 49(5), 2013, doi:10.1049/el.2012.4247 (see ksp_mscl). M. L. dos Santos, M.Sc. dissertation, Universidade Federal de Pernambuco, Recife, 2021, sec. 3.2 (MSCL Combinado). https://repositorio.ufpe.br/handle/123456789/45594

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
271
272
273
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
299
300
301
302
303
304
305
306
307
308
309
310
@jax.jit
def mscl_ksp(state: RSAEnvState, params: RSAEnvParams) -> Array:
    """Minimum Slot-continuity Capacity Loss (MSCL) across K-Shortest Paths.
    Only suitable for RSA/RMSA.

    Jointly selects the (path, slot) pair minimising the slot-continuity capacity
    loss over all k candidate paths and all slots - i.e. routing and spectrum
    assignment are decided together by the same one-step-lookahead metric, rather
    than fixing the path first as ksp_mscl does. Ties break to the shortest path,
    then the lowest slot index. See capacity_loss for the metric definition, the
    closed-form computation, and full references.

    The loss is accounted over the first --mscl_interfering_k stored routes of
    every node pair sharing a link with the candidate path (0 = all k_paths).
    With the default of 1 this is the single-route interfering set of the
    original 2013 formulation; with 0 it is the multi-route set of dos Santos
    (2021), whose MSCL Combinado is exactly this heuristic (joint route-slot
    choice; the flowchart's strict-improvement scan over routes and slots in
    order yields the same tie-breaks as the flattened argmin here). Cost scales
    linearly with the interfering-set size.

    References:
        R. C. Almeida Jr. et al., Electronics Letters 49(5), 2013,
        doi:10.1049/el.2012.4247 (see ksp_mscl).
        M. L. dos Santos, M.Sc. dissertation, Universidade Federal de
        Pernambuco, Recife, 2021, sec. 3.2 (MSCL Combinado).
        https://repositorio.ufpe.br/handle/123456789/45594

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters

    Returns:
        Array: Action
    """
    n_int = _mscl_num_interfering_routes(params)
    loss, _ = capacity_loss(state, params, num_interfering_routes=n_int)
    # argmin over path-major flattened array ties-breaks to shortest path, lowest slot
    action = jnp.argmin(loss.reshape(-1))
    return action

mu_ksp(state, params, unique_lightpaths, relative)

Use the most-used available slot on any path. The most-used slot is that which has the most unique lightpaths (if unique_lightpaths=True) or active lightpaths. Method: Go through action mask and find the usage of available slots, choose available slot that is most utilised.

Parameters:

Name Type Description Default
state EnvState

Environment state

required
params EnvParams

Environment parameters

required
unique_lightpaths bool

Whether to consider unique lightpaths

required
relative bool

Whether to return relative utilisation

required

Returns:

Name Type Description
Array Array

Action

Source code in xlron/heuristics/heuristics.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
@partial(jax.jit, static_argnums=(2, 3))
def mu_ksp(state: EnvState, params: RSAEnvParams, unique_lightpaths: bool, relative: bool) -> Array:
    """Use the most-used available slot on any path.
    The most-used slot is that which has the most unique lightpaths (if unique_lightpaths=True) or active lightpaths.
    Method: Go through action mask and find the usage of available slots, choose available slot that is most utilised.

    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
        unique_lightpaths (bool): Whether to consider unique lightpaths
        relative (bool): Whether to return relative utilisation

    Returns:
        Array: Action
    """
    mask = get_action_mask(state, params)
    # Get most used slots by summing the link_slot_array along the links
    most_used_slots = most_used(state, params, unique_lightpaths, relative)
    # Get usage of available slots
    most_used_mask = most_used_slots * mask
    # Chosen slot is the most used globally
    action = jnp.argmax(most_used_mask)
    return action