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
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
@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: HashableArrayWrapper = struct.field(pytree_node=False)
    slot_size: int = struct.field(pytree_node=False)
    consider_modulation_format: bool = struct.field(pytree_node=False)
    link_length_array: HashableArrayWrapper = struct.field(pytree_node=False)
    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: HashableArrayWrapper = struct.field(pytree_node=False)
    values_bw_probs: HashableArrayWrapper | None = struct.field(pytree_node=False)
    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: HashableArrayWrapper | None = struct.field(pytree_node=False)
    path_link_array: HashableArrayWrapper = struct.field(pytree_node=False)
    path_se_array: HashableArrayWrapper = struct.field(pytree_node=False)
    unique_se_values: HashableArrayWrapper = struct.field(pytree_node=False)
    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: HashableArrayWrapper | None = struct.field(pytree_node=False)

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
 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
@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
465
466
467
468
469
470
@struct.dataclass
class RSAMultibandEnvParams(RSAEnvParams):
    """Dataclass to hold environment parameters for MultiBandRSA (RBSA)."""

    gap_starts: HashableArrayWrapper = struct.field(pytree_node=False)
    gap_widths: HashableArrayWrapper = struct.field(pytree_node=False)

RSAMultibandEnvState

Bases: RSAEnvState

Dataclass to hold environment state for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
458
459
460
461
462
@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
257
258
259
260
261
262
263
264
265
266
267
268
269
@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
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
@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: HashableArrayWrapper = struct.field(pytree_node=False)
    slot_size: int = struct.field(pytree_node=False)
    consider_modulation_format: bool = struct.field(pytree_node=False)
    link_length_array: HashableArrayWrapper = struct.field(pytree_node=False)
    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: HashableArrayWrapper = struct.field(pytree_node=False)
    values_bw_probs: HashableArrayWrapper | None = struct.field(pytree_node=False)
    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: HashableArrayWrapper | None = struct.field(pytree_node=False)
    path_link_array: HashableArrayWrapper = struct.field(pytree_node=False)
    path_se_array: HashableArrayWrapper = struct.field(pytree_node=False)
    unique_se_values: HashableArrayWrapper = struct.field(pytree_node=False)
    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: HashableArrayWrapper | None = struct.field(pytree_node=False)

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
 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
@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
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
@struct.dataclass
class GNModelEnvParams(RSAEnvParams):
    """Dataclass to hold environment state for GN model environments."""

    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: HashableArrayWrapper = struct.field(pytree_node=False)
    amplifier_noise_figure: HashableArrayWrapper = struct.field(pytree_node=False)
    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: HashableArrayWrapper = struct.field(pytree_node=False)
    roadm_add_drop_loss: HashableArrayWrapper = struct.field(pytree_node=False)
    roadm_noise_figure: HashableArrayWrapper = struct.field(pytree_node=False)
    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: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # (link_resources,): per-slot launch power in linear Watts
    mod_format_correction: bool = struct.field(pytree_node=False)
    gap_starts: HashableArrayWrapper = struct.field(pytree_node=False)
    gap_widths: HashableArrayWrapper = struct.field(pytree_node=False)
    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: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # Slot permutation for band-preference first-fit (empty if unused)
    band_slot_order_lf: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # Slot permutation for band-preference last-fit (empty if unused)
    slot_centre_freq_array: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # 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: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # (6, num_channels, max_spans) — [C_f, a_f, C_b, a_b, a, raman_gain] Neper-scale + linear
    raman_pump_power_fw: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # (max_spans, num_pumps_fw) — forward pump powers [W]
    raman_pump_power_bw: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # (max_spans, num_pumps_bw) — backward pump powers [W]
    raman_pump_freq_fw: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # (max_spans, num_pumps_fw) — forward pump frequencies [Hz]
    raman_pump_freq_bw: HashableArrayWrapper = struct.field(
        pytree_node=False
    )  # (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
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
@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

HashableArrayWrapper

Bases: Generic[T]

Wrapper for making arrays hashable. In order to access pre-computed data, such as shortest paths between node-pairs or the constituent links of a path, within a jitted function, we need to make the arrays containing this data hashable. By defining this wrapper, we can define a hash method that returns a hash of the array's bytes, thus making the array hashable. From: https://github.com/google/jax/issues/4572#issuecomment-709677518

Source code in xlron/environments/dataclasses.py
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
class HashableArrayWrapper(Generic[T]):
    """Wrapper for making arrays hashable.
    In order to access pre-computed data, such as shortest paths between node-pairs or the constituent links of a path,
    within a jitted function, we need to make the arrays containing this data hashable. By defining this wrapper, we can
    define a __hash__ method that returns a hash of the array's bytes, thus making the array hashable.
    From: https://github.com/google/jax/issues/4572#issuecomment-709677518
    """

    def __init__(self, val: Array):
        self.val = val

    def __getattribute__(self, prop):
        if prop == "val" or prop == "__hash__" or prop == "__eq__":
            return super(HashableArrayWrapper, self).__getattribute__(prop)
        return getattr(self.val, prop)

    def __getitem__(self, key):
        return self.val[key]

    def __setitem__(self, key, val):
        self.val[key] = val

    def __hash__(self):
        return hash(self.val.tobytes())

    def __eq__(self, other):
        if isinstance(other, HashableArrayWrapper):
            return self.__hash__() == other.__hash__()
        if other is None:
            # Optional wrapper fields (e.g. values_bw_probs) compare against None
            # during jit-cache equality checks of static params
            return False

        f = getattr(self.val, "__eq__")
        return f(self, other)

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
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
@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
305
306
307
308
309
310
@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
298
299
300
301
302
@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
431
432
433
434
435
436
437
438
439
440
@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: HashableArrayWrapper = struct.field(pytree_node=False)
    fec_rate: chex.Scalar = struct.field(pytree_node=False)

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
443
444
445
446
447
448
449
450
451
452
453
454
455
@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
Source code in xlron/environments/dataclasses.py
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
@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)
    """

    max_slots: chex.Scalar = 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)

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
212
213
214
215
216
217
218
219
220
221
222
223
224
@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
415
416
417
418
419
@struct.dataclass
class RSAGNModelEnvParams(GNModelEnvParams):
    """Dataclass to hold environment params for RSA with GN model."""

    pass

RSAGNModelEnvState

Bases: GNModelEnvState

Dataclass to hold environment state for RSA with GN model.

Source code in xlron/environments/dataclasses.py
422
423
424
425
426
427
428
@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
465
466
467
468
469
470
@struct.dataclass
class RSAMultibandEnvParams(RSAEnvParams):
    """Dataclass to hold environment parameters for MultiBandRSA (RBSA)."""

    gap_starts: HashableArrayWrapper = struct.field(pytree_node=False)
    gap_widths: HashableArrayWrapper = struct.field(pytree_node=False)

RSAMultibandEnvState

Bases: RSAEnvState

Dataclass to hold environment state for MultiBandRSA (RBSA).

Source code in xlron/environments/dataclasses.py
458
459
460
461
462
@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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
@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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
@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
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
@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
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
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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
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
433
434
435
436
437
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
418
419
420
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
422
423
424
425
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
427
428
429
430
431
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
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
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
212
213
214
215
216
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(
                    cast(GNModelEnvParams, 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_link_array = (
                        jnp.unpackbits(params.path_link_array.val, axis=1)[:, : params.num_links]
                        if params.pack_path_bits
                        else params.path_link_array.val
                    )
                    path = path_link_array[(i + path_index).astype(jnp.int32)]
                    # 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
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
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):
        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")

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
260
261
262
263
264
265
266
267
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
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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
@partial(jax.jit, static_argnums=(1,))
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
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
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
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
@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)

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
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
@partial(jax.jit, static_argnums=(2,))
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
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
@partial(jax.jit, static_argnums=(2,))
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)
    """
    snr_sufficient_check = check_snr_sufficient(state, params)
    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
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
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
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
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
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
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
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
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
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
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
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
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)

Check if SNR is sufficient for all active connections. 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
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
def check_snr_sufficient(state: RMSAGNModelEnvState, params: RMSAGNModelEnvParams) -> Array:
    """Check if SNR is sufficient for all active connections.
    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
    )
    lightpath_snr_array = get_lightpath_snr(state, params)
    # Only check slots that are actually occupied (have nonzero channel bandwidth)
    is_occupied = state.channel_centre_bw_array != 0
    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
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
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
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
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
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
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
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
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
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
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
3603
3604
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
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
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
3758
3759
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
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
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
3673
3674
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
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
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
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
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
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
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
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
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
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
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
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
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
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
2216
2217
2218
2219
2220
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
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
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
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
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)

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
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
@partial(jax.jit, static_argnums=(1,))
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
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
@partial(jax.jit, static_argnums=(3,))
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.val.shape[0]
    acceptable_mod_format_indices = jnp.arange(mod_format_count)
    req_snr = params.modulations_array.val[:, 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_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
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
@partial(jax.jit, static_argnums=(2,))
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.val  # (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_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
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
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_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
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
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
@partial(jax.jit, static_argnums=(4,))
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.val[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 length = path-link incidence row dotted with per-link total (span-summed)
        # lengths. (Indexing the per-link length vector with a path index, and taking the
        # max over per-span partial sums, both produced garbage scalings here.)
        link_length_array = jnp.sum(params.link_length_array.val, axis=1, promote_integers=False)
        path_link_array = (
            jnp.unpackbits(params.path_link_array.val, axis=1)[:, : params.num_links]
            if params.pack_path_bits
            else params.path_link_array.val
        )
        path = path_link_array[(i + k_path_index).astype(dtype_config.INDEX_DTYPE)]
        path_length = jnp.dot(path.astype(link_length_array.dtype), link_length_array)
        maximum_path_length = jnp.max(
            jnp.dot(path_link_array.astype(link_length_array.dtype), link_length_array)
        )
        return params.slot_launch_power_array.val[initial_slot_index] * (
            path_length / maximum_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)

Get SNR for each link on path. N.B. that in most cases it is more efficient to calculate the SNR for every possible path, rather than a slot-by-slot basis. But in some cases slot-by-slot is better i.e. when kN(N-1)/2 > LS Args: state (RSAGNModelEnvState): Environment state params (RSAGNModelEnvParams): Environment parameters

Returns:

Name Type Description
Array Array

SNR for each link on path

Source code in xlron/environments/env_funcs.py
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
def get_lightpath_snr(state: GNModelEnvState, params: GNModelEnvParams) -> Array:
    """Get SNR for each link on path.
    N.B. that in most cases it is more efficient to calculate the SNR for every possible path, rather than a slot-by-slot basis.
    But in some cases slot-by-slot is better i.e. when k*N(N-1)/2 > L*S
    Args:
        state (RSAGNModelEnvState): Environment state
        params (RSAGNModelEnvParams): Environment parameters

    Returns:
        Array: SNR for each link on path
    """
    # Get the SNR for the channel that the path occupies.
    # Batched path-level SNR as a single (P, num_links) @ (num_links, S) matmul, mirroring
    # calculate_throughput_from_active_lightpaths (replaces a vmap of get_snr_for_path over
    # all P paths, which materialises a (P, num_links, S) broadcast/select intermediate).
    paths = params.path_link_array.val
    if params.pack_path_bits:
        paths = jnp.unpackbits(paths, axis=1)[:, : params.num_links]
    paths_float = paths.astype(state.link_snr_array.dtype)  # (P, num_links)

    # NSR accumulation: nsr_all[p, s] = sum_over_links( path[p, l] * (1 / link_snr[l, s]) )
    # Zero SNR entries (e.g. slots zeroed by lightpath removal before the next SNR refresh)
    # must not enter the matmul as 1/0 = inf, since off-path 0 * inf = NaN would poison the
    # column for every path. Divide with zeros masked, then restore the inf total for paths
    # that actually traverse a zero-SNR entry (matching the where/select semantics).
    snr_is_zero = (state.link_snr_array == 0).astype(paths_float.dtype)  # (num_links, S)
    inv_snr = jnp.where(
        state.link_snr_array == 0, 0.0, 1.0 / state.link_snr_array
    )  # (num_links, S)
    nsr_all = paths_float @ inv_snr  # (P, S) matmul
    nsr_all = jnp.where(paths_float @ snr_is_zero > 0, jnp.inf, nsr_all)

    # Add path-level ROADM ASE noise (vectorised over paths, as in get_snr_for_path)
    if hasattr(params, "roadm_express_loss"):
        num_links_on_path = jnp.sum(paths_float, axis=1)  # (P,)
        num_express = jnp.maximum(num_links_on_path - 1, 0)  # (P,)
        # Channel power/bandwidth from first link on path
        # (all links on a path carry the same channels)
        first_link_idx = jnp.argmax(paths, axis=1)  # (P,)
        ch_power = state.channel_power_array[first_link_idx]  # (P, S)
        ch_bw_hz = state.channel_centre_bw_array[first_link_idx] * 1e9  # GHz -> Hz
        ch_centres_hz = state.channel_centre_freq_array[first_link_idx] * 1e9  # GHz -> Hz
        roadm_ase = jax.vmap(
            lambda ne, cc, cb: isrs_gn_model.calculate_roadm_ase(
                roadm_express_loss=params.roadm_express_loss.val,
                roadm_add_drop_loss=params.roadm_add_drop_loss.val,
                roadm_noise_figure=params.roadm_noise_figure.val,
                num_roadm_express=ne,
                ref_lambda=params.ref_lambda,
                ch_centre_i=cc,
                ch_bandwidth_i=cb,
            )
        )(num_express, ch_centres_hz, ch_bw_hz)  # (P, S)
        nsr_roadm = jnp.where(ch_power > 0, roadm_ase / ch_power, 0.0)
        nsr_all = nsr_all + nsr_roadm

    # 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.val)
        nsr_trx = jnp.where(trx_snr_linear > 1.0, 1.0 / trx_snr_linear, 0.0)
        nsr_all = nsr_all + nsr_trx

    path_snr_array = jnp.nan_to_num(
        isrs_gn_model.to_db(1 / nsr_all), nan=-50, neginf=-50, posinf=50
    )  # Link SNR array must be in linear units so that 1/inf = 0
    # Where value in path_index_array matches index of path_snr_array, substitute in SNR value
    slot_indices = jnp.arange(params.link_resources)
    lightpath_snr_array = jax.vmap(
        jax.vmap(lambda x, si: path_snr_array[x][si], in_axes=(0, 0)), in_axes=(0, None)
    )(state.path_index_array, slot_indices)
    return lightpath_snr_array

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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
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
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 minimum value of the SNR on newly assigned channels. N.B. this requires the link_snr_array to have already been calculated and present in state.

Source code in xlron/environments/env_funcs.py
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
@partial(jax.jit, static_argnums=(2,))
def get_minimum_snr_of_channels_on_path(
    state: RSAGNModelEnvState,
    path: Array,
    slot_index: Array,
    req_slots: int,
    params: RSAGNModelEnvParams,
) -> Array:
    """Get the minimum value of the SNR on newly assigned channels.
    N.B. this requires the link_snr_array to have already been calculated and present in state."""
    snr_value_all_channels = get_snr_for_path(path, state.link_snr_array, params, state)
    min_snr_value_sub_channels = jnp.min(
        jnp.concatenate(
            [
                snr_value_all_channels[slot_index].reshape((1,)),
                snr_value_all_channels[slot_index + req_slots - 1].reshape((1,)),
            ],
            axis=0,
        )
    )
    return min_snr_value_sub_channels

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 mode 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
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
@partial(jax.jit, static_argnums=(1,))
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 mode 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.val

    # 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 == "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.val) * 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.val[:, 0].astype(jnp.int32)  # (E,)
    link_dst = params.edges.val[:, 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.val)
    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(),  # ty: ignore[unresolved-attribute]
        )
        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())  # ty: ignore[unresolved-attribute]
        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 == "departure":
        holding_time_col = jnp.full(
            (params.num_links, 1),
            state.holding_time / state.mean_service_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
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
@partial(jax.jit, static_argnums=(0,))
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.val,
        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
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
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.val,
        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.val, 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
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
@partial(jax.jit, static_argnums=(1,))
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
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
@partial(jax.jit, static_argnums=(0,))
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
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
@partial(jax.jit, static_argnums=(0,))
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
1509
1510
1511
1512
1513
1514
1515
@partial(jax.jit, static_argnums=(0,))
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.val, 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
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
@partial(jax.jit, static_argnums=(1, 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
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
@partial(jax.jit, static_argnums=(0,))
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.val,
        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
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
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
@partial(jax.jit, static_argnums=(1,))
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:]
    link_length_array = jnp.sum(params.link_length_array.val, axis=1, promote_integers=False)
    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_link_array = (
            jnp.unpackbits(params.path_link_array.val, axis=1)[:, : params.num_links]
            if params.pack_path_bits
            else params.path_link_array.val
        )
        path = path_link_array[path_index.astype(dtype_config.INDEX_DTYPE)]
        path_length = jnp.dot(path, link_length_array)
        max_path_length = jnp.max(jnp.dot(path_link_array, link_length_array))
        path_length_norm = path_length / max_path_length
        max_path_length_hops = jnp.max(jnp.sum(path_link_array, axis=1, promote_integers=False))
        path_length_hops_norm = (
            jnp.sum(path, promote_integers=False).astype(dtype_config.LARGE_FLOAT_DTYPE)
            / max_path_length_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
1518
1519
1520
1521
1522
1523
1524
1525
@partial(jax.jit, static_argnums=(0,))
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.val, 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
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
@partial(
    jax.jit,
    static_argnums=(
        1,
        2,
    ),
)
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 Returns: jnp.array: SNR per link

Source code in xlron/environments/env_funcs.py
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
@partial(jax.jit, static_argnums=(1,))
def get_snr_link_array(state: GNModelEnvState, params: GNModelEnvParams) -> Array:
    """Get SNR per link
    Args:
        state (EnvState): Environment state
        params (EnvParams): Environment parameters
    Returns:
        jnp.array: SNR per link
    """

    def get_link_snr(link_index, state, params):
        # 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
        )
        if params.mod_format_correction:
            mod_format_link = state.modulation_format_index_array[link_index, :]
            kurtosis_link = get_required_snr_se_kurtosis_on_link(mod_format_link, 4, params)
        else:
            kurtosis_link = jnp.zeros(params.link_resources).astype(jnp.float32)
        bw_link = state.channel_centre_bw_array[link_index, :]
        ch_power_link = state.channel_power_array[link_index, :]
        ch_centres_link = state.channel_centre_freq_array[link_index, :]

        # Calculate SNR
        P = dict(
            num_channels=params.link_resources,
            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=params.amplifier_noise_figure.val,
            transceiver_snr=params.transceiver_snr.val,
            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=params.raman_fit_params.val,
                raman_pump_power_fw=params.raman_pump_power_fw.val,
                raman_pump_power_bw=params.raman_pump_power_bw.val,
                raman_pump_freq_fw=params.raman_pump_freq_fw.val,
                raman_pump_freq_bw=params.raman_pump_freq_bw.val,
            )[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,
            )[0]

        return snr

    link_snr_array = jax.vmap(get_link_snr, in_axes=(0, None, None))(
        jnp.arange(params.num_links), state, params
    )
    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
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
4443
4444
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
4479
4480
4481
4482
4483
4484
4485
4486
4487
@partial(jax.jit, static_argnums=(1,))
def get_snr_link_array_fused(state: GNModelEnvState, params: GNModelEnvParams) -> 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)

    # Precompute per-link num_spans and span_length from static link_length_array
    # link_length_array is (L, max_spans) in metres
    link_lengths_m = params.link_length_array.val  # (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 channel data from state: (L, N)
    ch_power_all = state.channel_power_array  # (L, N)
    bw_all = state.channel_centre_bw_array  # (L, N) in GHz

    # Use cached centre frequencies from state
    ch_centres_hz = state.channel_centre_freq_array * 1e9  # (L, N) GHz -> Hz
    bw_hz = bw_all * 1e9  # (L, N)

    # Tile amplifier noise figure and transceiver SNR to (L, N) for vmap
    amp_nf = jnp.broadcast_to(params.amplifier_noise_figure.val, ch_power_all.shape)
    trx_snr = jnp.broadcast_to(params.transceiver_snr.val, ch_power_all.shape)

    def _link_snr_fused(ch_pow, ch_centre, ch_bw, n_spans, s_length, amp_nf_link, trx_snr_link):
        return isrs_gn_model.get_snr_fused(
            ch_power_w_i=ch_pow,
            ch_centre_i=ch_centre,
            ch_bandwidth_i=ch_bw,
            num_spans=n_spans,
            span_length=s_length,
            num_channels=params.link_resources,
            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=amp_nf_link,
            transceiver_snr=trx_snr_link,
            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,
        )

    link_snr_array = jax.vmap(_link_snr_fused)(
        ch_power_all,
        ch_centres_hz,
        bw_hz,
        num_spans_per_link,
        span_length_per_link,
        amp_nf,
        trx_snr,
    )
    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
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
@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)

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
4735
4736
4737
4738
4739
4740
4741
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
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
@partial(jax.jit, static_argnums=(2,))
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_launch_power(
        state, path_action, action_info.power_action, action_info.initial_slot_index, params
    )
    # 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,
            action_info.affected_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,
            action_info.affected_slots_mask,
            params.slot_size,
        ),
        channel_centre_freq_array=set_path_links(
            state.channel_centre_freq_array,
            action_info.affected_slots_mask,
            get_centre_frequency(action_info.initial_slot_index, action_info.num_slots, params),
        ),
    )
    # Update link_snr_array
    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.val[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
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
@partial(jax.jit, static_argnums=(2,), 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
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
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
@partial(jax.jit, static_argnums=(2,))
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_launch_power(
        state, path_action, action_info.power_action, action_info.initial_slot_index, params
    )
    # 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,
            action_info.affected_slots_mask,
            launch_power,
        ),
        channel_centre_bw_array=set_path_links(
            state.channel_centre_bw_array,
            action_info.affected_slots_mask,
            params.slot_size,
        ),
        channel_centre_freq_array=set_path_links(
            state.channel_centre_freq_array,
            action_info.affected_slots_mask,
            get_centre_frequency(action_info.initial_slot_index, action_info.num_slots, params),
        ),
    )
    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
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
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
4097
4098
4099
4100
4101
4102
4103
4104
4105
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
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
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
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
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
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
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
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
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
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
@partial(jax.jit, static_argnums=(1, 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.val.T[0].astype(dtype_config.LARGE_INT_DTYPE)
    receivers = params.edges.val.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.val)], 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
3027
3028
3029
3030
3031
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
392
393
394
395
396
397
398
399
400
401
402
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
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
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
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
@partial(jax.jit, static_argnums=(0,))
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
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
@partial(jax.jit, static_argnums=(0, 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
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
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
1181
1182
1183
1184
1185
1186
1187
1188
1189
@partial(jax.jit, static_argnums=(0,))
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
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
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
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
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
3034
3035
3036
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
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
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
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
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
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
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
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
1159
1160
1161
1162
1163
1164
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
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
@partial(jax.jit, static_argnums=(1,))
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
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
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
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]
    amplifier_noise_db = noise_data[:, 4]  # NF_ASE_dB
    transceiver_snr_db = noise_data[:, 5]  # SNR_TRX_dB
    roadm_express_loss_db = noise_data[:, 6]  # roadm_express_loss_dB
    roadm_add_drop_loss_db = noise_data[:, 7]  # roadm_add_drop_loss_dB
    roadm_nf_db = noise_data[:, 8]  # roadm_NF_dB

    if slot_frequencies_ghz is None:
        # Legacy uniform formula
        slot_centres = (jnp.arange(link_resources) - (link_resources - 1) / 2) * slot_size
        ref_frequency_ghz = c / ref_lambda / 1e9
        slot_frequencies_ghz = ref_frequency_ghz + slot_centres

    # Initialize output arrays
    transceiver_snr_array = jnp.zeros(link_resources)
    amplifier_noise_figure_array = jnp.zeros(link_resources)
    roadm_express_loss_array = jnp.zeros(link_resources)
    roadm_add_drop_loss_array = jnp.zeros(link_resources)
    roadm_noise_figure_array = jnp.zeros(link_resources)

    # For each slot, find which band it belongs to
    for i, freq in enumerate(slot_frequencies_ghz):
        # Find the band this frequency falls into
        found = False
        for j in range(len(frequency_min_ghz)):
            if frequency_min_ghz[j] <= freq <= frequency_max_ghz[j]:
                transceiver_snr_array = transceiver_snr_array.at[i].set(transceiver_snr_db[j])
                amplifier_noise_figure_array = amplifier_noise_figure_array.at[i].set(
                    amplifier_noise_db[j]
                )
                roadm_express_loss_array = roadm_express_loss_array.at[i].set(
                    roadm_express_loss_db[j]
                )
                roadm_add_drop_loss_array = roadm_add_drop_loss_array.at[i].set(
                    roadm_add_drop_loss_db[j]
                )
                roadm_noise_figure_array = roadm_noise_figure_array.at[i].set(roadm_nf_db[j])
                found = True
                break
        if not found:
            # Gap slots fall between bands — leave at zero (they are never occupied)
            pass

    return (
        transceiver_snr_array,
        amplifier_noise_figure_array,
        roadm_express_loss_array,
        roadm_add_drop_loss_array,
        roadm_noise_figure_array,
    )

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
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
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
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
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 action mask for RMSA with GN model physical layer.

For each (path, modulation_format) pair, finds first-fit and last-fit candidate slot positions, evaluates them via the ISRS GN model, and builds a mask indicating which slots are valid (with the modulation format index stored in mod_format_mask).

Parameters:

Name Type Description Default
state RMSAGNModelEnvState

Environment state

required
params RMSAGNModelEnvParams

Environment parameters

required
request Array

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

required

Returns:

Name Type Description
state EnvState

Updated environment state with link_slot_mask and mod_format_mask

Source code in xlron/environments/env_funcs.py
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
4965
4966
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
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
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
5133
5134
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
5166
5167
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
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
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
@partial(jax.jit, static_argnums=(1,))
def mask_slots_rmsa_gn_model(
    state: RMSAGNModelEnvState, params: RMSAGNModelEnvParams, request: Array
) -> EnvState:
    """Compute action mask for RMSA with GN model physical layer.

    For each (path, modulation_format) pair, finds first-fit and last-fit candidate
    slot positions, evaluates them via the ISRS GN model, and builds a mask indicating
    which slots are valid (with the modulation format index stored in mod_format_mask).

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

    Returns:
        state: Updated environment state with link_slot_mask and mod_format_mask
    """
    nodes_sd, requested_datarate = read_rsa_request(request)
    num_mods = params.modulations_array.val.shape[0]

    # --- Phase 1: Vectorized slot availability via cumsum ---
    paths = get_paths(params, nodes_sd)  # (k, num_links)
    slots_occupied = (state.link_slot_array != 0).astype(dtype_config.LARGE_FLOAT_DTYPE)
    occupied = (paths @ slots_occupied) > 0  # (k, link_resources) True if occupied on any path link

    # Modulation format data
    mod_formats = params.modulations_array.val  # (num_mods, >=3)
    se_values = mod_formats[:, 1]  # (num_mods,)
    req_snr_values = mod_formats[:, 2] + params.snr_margin  # (num_mods,) in dB

    # Required slots per modulation format
    all_req_slots = jax.vmap(
        lambda se: required_slots(
            requested_datarate,
            se,
            params.slot_size,
            guardband=params.guardband,
            temperature=params.temperature,
        )
    )(se_values)  # (num_mods,)

    # Cumsum sliding window for contiguous free slots
    padded = jnp.concatenate(
        [
            jnp.zeros((params.k_paths, 1), dtype=dtype_config.LARGE_FLOAT_DTYPE),
            occupied.astype(dtype_config.LARGE_FLOAT_DTYPE),
            jnp.ones((params.k_paths, params.max_slots - 1), dtype=dtype_config.LARGE_FLOAT_DTYPE),
        ],
        axis=1,
    )  # (k, link_resources + max_slots)
    cumsum = jnp.cumsum(padded, axis=1)

    slot_indices = jnp.arange(params.link_resources)
    end_indices = slot_indices[None, :] + all_req_slots[:, None]  # (num_mods, link_resources)

    cumsum_at_end = cumsum[:, end_indices]  # (k, num_mods, link_resources)
    cumsum_at_start = cumsum[:, slot_indices]  # (k, link_resources)
    window_sums = cumsum_at_end - cumsum_at_start[:, None, :]  # (k, num_mods, link_resources)
    slot_available = window_sums == 0  # (k, num_mods, link_resources)

    # Zero out dummy (all-zero) paths
    path_valid = jnp.max(paths, axis=1) > 0  # (k,)
    slot_available = slot_available & path_valid[:, None, None]

    # Extract FF and LF slot indices
    has_candidate = jnp.any(slot_available, axis=2)  # (k, num_mods)

    use_band_order = (
        hasattr(params, "band_slot_order_ff")
        and hasattr(params, "band_slot_order_lf")
        and params.band_slot_order_ff.val.shape[0] == params.link_resources
        and params.band_slot_order_lf.val.shape[0] == params.link_resources
    )

    def _first_true_in_order(avail_3d, order):
        """Return first available raw slot index for each (path, mod) in given slot order."""
        ordered = avail_3d[:, :, order]
        sent = jnp.zeros((params.k_paths, num_mods, 1), dtype=bool)
        idx_in_order = jnp.argmax(jnp.concatenate([ordered, sent], axis=2), axis=2)
        has_any = jnp.any(ordered, axis=2)
        safe = jnp.clip(idx_in_order, 0, params.link_resources - 1)
        raw_idx = order[safe]
        return jnp.where(has_any, raw_idx, params.link_resources)

    if use_band_order:
        order_ff = params.band_slot_order_ff.val.astype(dtype_config.LARGE_INT_DTYPE)
        order_lf = params.band_slot_order_lf.val.astype(dtype_config.LARGE_INT_DTYPE)
        ff_indices = _first_true_in_order(slot_available, order_ff)  # (k, num_mods)
        lf_indices = _first_true_in_order(slot_available, order_lf)  # (k, num_mods)
    else:
        # FF: first True along axis=2 (append False sentinel so argmax returns link_resources when empty)
        ff_sentinel = jnp.zeros((params.k_paths, num_mods, 1), dtype=bool)
        ff_indices = jnp.argmax(
            jnp.concatenate([slot_available, ff_sentinel], axis=2), axis=2
        )  # (k, num_mods)

        # LF: last True along axis=2
        lf_sentinel = jnp.zeros((params.k_paths, num_mods, 1), dtype=bool)
        lf_from_end = jnp.argmax(
            jnp.concatenate([jnp.flip(slot_available, axis=2), lf_sentinel], axis=2), axis=2
        )  # (k, num_mods)
        lf_indices = params.link_resources - 1 - lf_from_end  # (k, num_mods)

    # Skip LF evaluation when FF == LF (same slot, would be duplicate)
    is_same = ff_indices == lf_indices

    # --- Phase 2: Batch candidate construction ---
    # Flatten to (2 * k * M) candidates: [FF candidates..., LF candidates...]
    # Order within each half: path0_mod0, path0_mod1, ..., pathK_modM
    flat_ff_indices = ff_indices.reshape(-1)  # (k*M,)
    flat_lf_indices = lf_indices.reshape(-1)  # (k*M,)
    all_slot_indices = jnp.concatenate([flat_ff_indices, flat_lf_indices])  # (2*k*M,)

    # Path index for each candidate
    path_idx_per_km = jnp.repeat(jnp.arange(params.k_paths), num_mods)  # (k*M,)
    path_idx_all = jnp.concatenate([path_idx_per_km, path_idx_per_km])  # (2*k*M,)
    all_paths = paths[path_idx_all]  # (2*k*M, num_links)

    # Mod format index for each candidate
    mod_idx_per_km = jnp.tile(jnp.arange(num_mods), params.k_paths)  # (k*M,)
    mod_idx_all = jnp.concatenate([mod_idx_per_km, mod_idx_per_km])  # (2*k*M,)

    # Required slots and SNR per candidate
    all_req_slots_flat = all_req_slots[mod_idx_all]  # (2*k*M,)
    all_req_snr_flat = req_snr_values[mod_idx_all]  # (2*k*M,)

    # Lightpath indices per candidate
    all_lightpath_indices = jax.vmap(lambda i: get_lightpath_index(params, nodes_sd, i))(
        path_idx_all
    )  # (2*k*M,)

    # Launch power per path
    if params.launch_power_type == "fixed":
        all_launch_powers = params.slot_launch_power_array.val[all_slot_indices]
    else:
        # Synthesise a path action for path i in the aggregated action space; must use
        # ceil to round-trip through process_path_action (floor mis-decodes the path
        # index whenever link_resources % aggregate_slots != 0)
        per_path_launch_powers = jax.vmap(
            lambda i, si: get_launch_power(
                state,
                i * math.ceil(params.link_resources / params.aggregate_slots),
                state.launch_power_array[i],
                si,
                params,
            )
        )(
            jnp.arange(params.k_paths), flat_ff_indices[: params.k_paths * num_mods : num_mods]
        )  # (k,)
        all_launch_powers = per_path_launch_powers[path_idx_all]  # (2*k*M,)

    # Validity flags: FF candidates use has_candidate, LF also requires FF != LF
    flat_has_ff = has_candidate.reshape(-1)  # (k*M,)
    flat_has_lf = (has_candidate & ~is_same).reshape(-1)  # (k*M,)
    all_has_candidate = jnp.concatenate([flat_has_ff, flat_has_lf])  # (2*k*M,)

    # Build affected_slots_masks for all candidates
    all_masks = jax.vmap(lambda si, rs, p: get_affected_slots_mask(si, rs, p, params))(
        all_slot_indices, all_req_slots_flat, all_paths
    )  # (2*k*M, num_links, link_resources)

    # Construct modified state arrays for all candidates
    all_ch_bw = jax.vmap(
        lambda mask: set_path_links(state.channel_centre_bw_array, mask, params.slot_size)
    )(all_masks)  # (2*k*M, num_links, link_resources)

    all_ch_power = jax.vmap(lambda mask, lp: set_path_links(state.channel_power_array, mask, lp))(
        all_masks, all_launch_powers
    )  # (2*k*M, num_links, link_resources)

    all_path_idx_arrays = jax.vmap(
        lambda mask, li: set_path_links(state.path_index_array, mask, li)
    )(all_masks, all_lightpath_indices)  # (2*k*M, num_links, link_resources)

    all_mod_fmt_arrays = jax.vmap(
        lambda mask, mi: set_path_links(
            state.modulation_format_index_array,
            mask,
            mi.astype(state.modulation_format_index_array.dtype),
        )
    )(all_masks, mod_idx_all)  # (2*k*M, num_links, link_resources)

    # Compute centre frequencies for each candidate placement
    all_centre_freqs = jax.vmap(
        lambda mask, si, rs: set_path_links(
            state.channel_centre_freq_array,
            mask,
            get_centre_frequency(si, rs, params),
        )
    )(all_masks, all_slot_indices, all_req_slots_flat)  # (2*k*M, num_links, link_resources)

    # --- Phase 3: Vmapped GN model evaluation ---
    def evaluate_one_candidate(
        ch_bw,
        ch_power,
        path_idx_arr,
        mod_fmt_arr,
        centre_freq_arr,
        slot_idx,
        req_slots_val,
        req_snr_val,
        path_vec,
        has_cand,
    ):
        """Evaluate a single candidate placement. Returns 1.0 if valid, 0.0 if not."""
        temp_state = state.replace(
            channel_centre_bw_array=ch_bw,
            channel_power_array=ch_power,
            path_index_array=path_idx_arr,
            modulation_format_index_array=mod_fmt_arr,
            channel_centre_freq_array=centre_freq_arr,
        )

        # Compute SNR for all links
        if params.uniform_spans and not params.mod_format_correction:
            link_snr = get_snr_link_array_fused(temp_state, params)
        else:
            link_snr = get_snr_link_array(temp_state, params)
        temp_state = temp_state.replace(link_snr_array=link_snr)

        # Check 1: New lightpath SNR meets modulation format threshold
        # (inlined get_minimum_snr_of_channels_on_path to avoid static_argnums issue in vmap)
        snr_all_channels = get_snr_for_path(path_vec, temp_state.link_snr_array, params, temp_state)
        new_snr = jnp.min(
            jnp.concatenate(
                [
                    snr_all_channels[slot_idx].reshape((1,)),
                    snr_all_channels[slot_idx + req_slots_val - 1].reshape((1,)),
                ],
                axis=0,
            )
        )
        new_ok = (new_snr >= req_snr_val).astype(jnp.float32)
        if DEBUG_SNR_TRACE:
            should_trace = jnp.logical_and(has_cand, state.total_requests < 3)

            def _trace(_):
                trx_snr_db = params.transceiver_snr.val[slot_idx]
                trx_snr_linear = from_db(trx_snr_db)
                nsr_trx = jnp.where(trx_snr_linear > 1.0, 1.0 / trx_snr_linear, 0.0)
                new_nsr = 1.0 / jnp.maximum(from_db(new_snr), 1e-20)
                optical_nsr = jnp.maximum(new_nsr - nsr_trx, 1e-20)
                optical_snr_db = isrs_gn_model.to_db(1.0 / optical_nsr)
                jax.debug.print(
                    "RMSA_SNR_TRACE req={} slot={} req_slots={} path_links={} "
                    "req_snr_db={:.2f} new_snr_db={:.2f} optical_snr_db={:.2f} trx_snr_db={:.2f}",
                    state.total_requests,
                    slot_idx,
                    req_slots_val,
                    jnp.sum(path_vec),
                    req_snr_val,
                    new_snr,
                    optical_snr_db,
                    trx_snr_db,
                    ordered=True,
                )
                return jnp.array(0, dtype=jnp.int32)

            _ = jax.lax.cond(
                should_trace,
                _trace,
                lambda _: jnp.array(0, dtype=jnp.int32),
                operand=jnp.array(0, dtype=jnp.int32),
            )

        # Check 2: Existing lightpaths still meet their SNR thresholds
        existing_fail = check_snr_sufficient(temp_state, params)
        existing_ok = (1.0 - existing_fail).astype(jnp.float32)

        # Check 3: Total power on each link doesn't exceed max_power_per_fibre
        total_power = compute_total_power_per_link(ch_power, path_idx_arr, centre_freq_arr)
        power_ok = (~jnp.any(total_power > params.max_power_per_fibre)).astype(jnp.float32)

        return new_ok * existing_ok * power_ok * has_cand.astype(jnp.float32)

    all_results = jax.vmap(evaluate_one_candidate)(
        all_ch_bw,
        all_ch_power,
        all_path_idx_arrays,
        all_mod_fmt_arrays,
        all_centre_freqs,
        all_slot_indices,
        all_req_slots_flat,
        all_req_snr_flat,
        all_paths,
        all_has_candidate,
    )  # (2*k*M,)

    # --- Phase 4: Assemble final mask ---
    ff_results = all_results[: params.k_paths * num_mods].reshape(params.k_paths, num_mods)
    lf_results = all_results[params.k_paths * num_mods :].reshape(params.k_paths, num_mods)

    # Build mod_format_mask: for each (path, slot), store the valid modulation
    # format with the highest spectral efficiency (SE), or -1 if none.
    slot_idx_range = jnp.arange(params.link_resources, dtype=dtype_config.LARGE_INT_DTYPE)
    se_values_typed = se_values.astype(dtype_config.LARGE_FLOAT_DTYPE)

    def build_path_mask(path_idx):
        best_idx = jnp.full((params.link_resources,), -1, dtype=dtype_config.LARGE_INT_DTYPE)
        best_se = jnp.full(
            (params.link_resources,),
            -jnp.inf,
            dtype=dtype_config.LARGE_FLOAT_DTYPE,
        )

        def apply_mod(mod_idx, carry):
            best_idx_i, best_se_i = carry
            ff_idx = ff_indices[path_idx, mod_idx]
            lf_idx = lf_indices[path_idx, mod_idx]
            ff_ok = ff_results[path_idx, mod_idx]
            lf_ok = lf_results[path_idx, mod_idx]
            mod_se = se_values_typed[mod_idx]
            mod_idx_i = mod_idx.astype(dtype_config.LARGE_INT_DTYPE)

            ff_valid = (slot_idx_range == ff_idx) & (ff_ok > 0) & (mod_se > best_se_i)
            best_se_i = jnp.where(ff_valid, mod_se, best_se_i)
            best_idx_i = jnp.where(ff_valid, mod_idx_i, best_idx_i)

            lf_valid = (slot_idx_range == lf_idx) & (lf_ok > 0) & (mod_se > best_se_i)
            best_se_i = jnp.where(lf_valid, mod_se, best_se_i)
            best_idx_i = jnp.where(lf_valid, mod_idx_i, best_idx_i)
            return best_idx_i, best_se_i

        best_idx, _ = jax.lax.fori_loop(
            0,
            num_mods,
            apply_mod,
            (best_idx, best_se),
        )
        return best_idx.astype(dtype_config.LARGE_FLOAT_DTYPE)

    mod_format_mask = jax.vmap(build_path_mask)(jnp.arange(params.k_paths)).reshape(
        -1
    )  # (k * link_resources,)

    # Validity mask on the MASK tier (bool in non-differentiable modes). NOTE: validity here
    # comes from the SNR-based mod_format_mask (>= 0 means some modulation format works), NOT
    # from the spectrum mask — only the dtype changes.
    link_slot_mask = (mod_format_mask >= 0).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.hstack([link_slot_mask, jnp.ones((1,), dtype=dtype_config.MASK_DTYPE)])
    # Store the validity masks at MASK_DTYPE and mod_format_mask at SMALL_FLOAT to keep the
    # carried field dtypes stable (matches init_link_slot_mask / init_mod_format_mask);
    # mod_format_mask stays float: it holds -1 sentinels / small modulation indices.
    state = state.replace(
        link_slot_mask=link_slot_mask.astype(dtype_config.MASK_DTYPE),  # ty: ignore[unresolved-attribute]
        full_link_slot_mask=full_link_slot_mask.astype(dtype_config.MASK_DTYPE),
        mod_format_mask=mod_format_mask.astype(dtype_config.SMALL_FLOAT_DTYPE),
    )
    return state

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
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
@partial(jax.jit, static_argnums=(1,))
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

normalise_traffic_matrix(traffic_matrix)

Normalise traffic matrix to sum to 1

Source code in xlron/environments/env_funcs.py
1206
1207
1208
1209
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
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
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
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
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
@partial(jax.jit, static_argnums=(1,))
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
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
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

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
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
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
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
@partial(jax.jit, static_argnums=(1,))
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)  # ty: ignore[unresolved-attribute]
        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
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
@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
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
@partial(jax.jit, static_argnums=(1, 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.val.shape[0]
    if num_gaps > 0:

        def set_band_gap(i, arr):
            gap_start = params.gap_starts.val[i]
            gap_end = gap_start + params.gap_widths.val[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

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
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
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
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
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
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
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
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.val)], 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

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
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
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
    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
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
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
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
@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
219
220
221
222
223
224
225
226
227
228
229
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, float] | 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
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
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
def build_run_summary(
    run_type: str,
    config: dict,
    metrics_dict: Dict[str, Dict[str, float]],
    timing: Dict[str, float] | 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
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
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
271
272
273
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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
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
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
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
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
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
1434
1435
1436
1437
1438
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

    def warmup_fn(warmup_state) -> 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,)),  # ty: ignore[unresolved-attribute]
                        jnp.array(
                            [
                                params.default_launch_power,
                            ]
                        ),
                    ],
                    axis=0,
                )
            elif (
                "gn_model" in config.env_type.lower()
                and config.launch_power_type != "rl"
                and not config.USE_GNN
                and not use_heuristic_warmup
                and not use_random_warmup
            ):
                # GNN policies emit plain path actions, which GN-model envs accept with
                # non-RL launch power (process_action defaults the power element).
                raise ValueError("Check that EVAL_HEURISTIC is set to True if using a heuristic")
            # 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, params)
            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, 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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
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),)

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
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
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
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
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
2520
2521
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
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."""

    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()))
        for metric_name, value in (("utilisation", util), ("fragmentation", frag)):
            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",
        ]

    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"{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["training_time"] = 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"{metric}_{agg}": processed_data[metric][agg][i]
                        for metric in all_metrics
                        for agg in ["mean", "std", "iqr_upper", "iqr_lower"]
                    }
                    log_dict["training_time"] = training_time[i]
                    log_dict["env_step"] = (i * config.DOWNSAMPLE_FACTOR) + step_count
                    wandb.log(log_dict)

            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
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
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
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
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
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
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
1655
1656
1657
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
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
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)

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
506
507
508
509
510
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
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
500
501
502
503
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)
    if hasattr(values_bw, "val"):
        values_bw = values_bw.val
    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"
        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})")
        print(f"  Activation:               {config.get('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
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
def print_metrics(
    processed_data: Dict[str, Dict[str, Array]],
    config: Union[Box, Dict[str, Any]],
    user_flags: dict | None = None,
    timing: Dict[str, float] | 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
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
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
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
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
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
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
1791
1792
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
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
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

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
266
267
268
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
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
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, env_params)
    model = eqx.combine(train_state.model_params, train_state.model_static)
    model = cast_model_for_compute(model)
    pi, value = model(*last_obs)
    # Action masking
    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

    # 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)  # ty: ignore[unresolved-attribute]
        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
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
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
540
541
542
543
544
545
546
547
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
530
531
532
533
534
535
536
537
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)

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
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
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
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("compilation_time_s") is not None:
                print(f"{'Compilation time:':<22s} {t['compilation_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
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
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
240
241
242
243
244
245
246
247
248
249
250
251
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
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
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
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):
        if self.activation == "relu":
            return jax.nn.relu(x)
        elif self.activation == "crelu":
            return crelu(x)
        return jnp.tanh(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
475
476
477
478
479
480
481
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
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
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
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
82
83
84
85
86
87
88
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
91
92
93
94
95
96
97
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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)

select_activation(activation)

Selects the activation function based on the provided string.

Source code in xlron/models/mlp.py
72
73
74
75
76
77
78
79
def select_activation(activation: str) -> Callable[[ArrayLike], Array]:
    """Selects the activation function based on the provided string."""
    if activation == "relu":
        return jax.nn.relu
    elif activation == "crelu":
        return crelu
    else:
        return jax.nn.tanh  # Default to tanh if no valid activation is specified

ActorCriticGNN

Bases: Module

Combined Actor-Critic GNN model.

Source code in xlron/models/gnn.py
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
1313
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
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
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
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
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
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
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
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
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
1072
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.val
                / jnp.sum(params.link_length_array.val, 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
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
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
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",
    ):
        (
            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,
        )
        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,
        )
        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)  # ty: ignore[unresolved-attribute]

        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"]

        # Project per-link embeddings to slot logits, then pool across path links
        action_tokens = jax.vmap(self.actor_mlp)(action_tokens)

        # ACTOR POOLING
        nodes_sd, requested_bw = read_rsa_request(state.request_array)
        if self.actor_pooling == "min_mean_max":

            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
            def path_action_dist(i):
                return get_path_slots(
                    action_tokens,
                    params,
                    nodes_sd,
                    i,
                    agg_func="sum",
                )

            path_action_logits = jax.vmap(path_action_dist)(jnp.arange(params.k_paths))
        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
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
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)  # ty: ignore[unresolved-attribute]

    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"]

    # Project per-link embeddings to slot logits, then pool across path links
    action_tokens = jax.vmap(self.actor_mlp)(action_tokens)

    # ACTOR POOLING
    nodes_sd, requested_bw = read_rsa_request(state.request_array)
    if self.actor_pooling == "min_mean_max":

        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
        def path_action_dist(i):
            return get_path_slots(
                action_tokens,
                params,
                nodes_sd,
                i,
                agg_func="sum",
            )

        path_action_logits = jax.vmap(path_action_dist)(jnp.arange(params.k_paths))
    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
617
618
619
620
621
622
623
624
625
626
627
628
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
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
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
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
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

    def __init__(
        self,
        embedding_size: int,
        intermediate_size: int,
        dropout_rate: float,
        key: chex.PRNGKey,
    ):
        mlp_key, output_key = jax.random.split(key)
        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 = jax.nn.gelu(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
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
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,
    ):
        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,
        )

    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
 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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
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
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
79
80
81
82
83
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
 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
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

Heuristics

best_fit(state, params)

Best-Fit Spectrum Allocation. Returns the best fit slot for each path.

Source code in xlron/heuristics/heuristics.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
@partial(jax.jit, static_argnums=(1,))
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
 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
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
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 = get_action_mask(state, params)
    nodes_sd, _ = read_rsa_request(state.request_array)
    num_slots = get_request_num_slots(state, params)
    num_resources = params.link_resources

    # Maximum future demand size (in slots, incl. guardband) to account capacity for.
    # params fields are static under jit so this is computed at trace time.
    values_bw = np.asarray(params.values_bw.val)
    min_se = (
        float(np.min(np.asarray(params.path_se_array.val)))
        if params.consider_modulation_format
        else 1.0
    )
    w_cap = int(np.ceil(float(np.max(values_bw)) / (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}"
        )
    pair_major_rows = (
        np.arange(params.path_link_array.val.shape[0])
        .reshape(-1, params.k_paths)[:, :n_int]
        .reshape(-1)
    )
    interfering_paths = params.path_link_array.val[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[:, None], 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
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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
@partial(jax.jit, static_argnums=(1,))
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
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)
    if isinstance(params, GNModelEnvParams) and len(params.band_slot_order_ff.val) > 0:
        order = params.band_slot_order_ff.val
        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)
        first_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 "first_slots"
        mask = jnp.concatenate((mask, jnp.full((mask.shape[0], 1), 1)), axis=1)
        first_slots = jnp.argmax(mask, axis=1)
    return first_slots

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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@partial(jax.jit, static_argnums=(1,))
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 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
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
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 = init_path_capacity_array(
            params.link_length_array.val, params.path_link_array.val, scale_factor=1.0
        )
        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.val.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
876
877
878
879
880
881
882
883
884
885
886
887
888
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
862
863
864
865
866
867
868
869
870
871
872
873
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
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
853
854
855
856
857
858
859
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.val) + jnp.max(params.values_bw.val)) / 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
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
@partial(jax.jit, static_argnums=(1,))
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
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
@partial(jax.jit, static_argnums=(1,))
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
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
@partial(jax.jit, static_argnums=(1,))
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
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
@partial(jax.jit, static_argnums=(1,))
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
@partial(jax.jit, static_argnums=(1,))
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
 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
@partial(jax.jit, static_argnums=(1,))
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@partial(jax.jit, static_argnums=(1,))
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
60
61
62
63
64
65
66
67
68
69
70
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
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
@partial(jax.jit, static_argnums=(1,))
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@partial(jax.jit, static_argnums=(1,))
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@partial(jax.jit, static_argnums=(1,))
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
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
@partial(jax.jit, static_argnums=(1,))
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
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
@partial(jax.jit, static_argnums=(1, 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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
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.val) > 0:
        order = params.band_slot_order_lf.val
        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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
@partial(jax.jit, static_argnums=(1,))
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
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
@partial(jax.jit, static_argnums=(1, 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 = init_path_capacity_array(
            params.link_length_array.val, params.path_link_array.val, scale_factor=1.0
        )
        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
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
@partial(jax.jit, static_argnums=(1,))
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
@partial(jax.jit, static_argnums=(1, 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