API reference¶
Rewards¶
rlsa.rewards
¶
Composite reward used to train RLSA (paper Eq. 1).
R = lambda_make * R_make + lambda_util * R_util + lambda_cost * R_cost
where
R_make = -(tau_end - tau_arr) / d_hat normalized flow time
R_util = mean(u) - eta * std(u) utilization minus imbalance
R_cost = -beta * g * (dt_llm / dt_budget) LLM-invocation cost
The module is numpy-only and side-effect free so it can be unit-tested without building an environment.
RewardWeights(lambda_make=1.0, lambda_util=0.5, lambda_cost=1.0, util_imbalance_eta=0.2, cost_beta=1.0, cost_budget_seconds=2.0)
dataclass
¶
Weights of the composite reward.
makespan_reward(actual_seconds, estimated_seconds)
¶
Negative normalized flow time; -1 means the job finished on estimate.
utilization_reward(utilization, imbalance_eta=0.2)
¶
Mean utilization minus a penalty on cross-resource imbalance.
llm_cost_penalty(gate, llm_latency_seconds, budget_seconds=1.0, beta=1.0)
¶
Zero when the surrogate is used; negative and latency-proportional otherwise.
composite_reward(actual_seconds, estimated_seconds, utilization, gate, llm_latency_seconds, weights=None)
¶
Return the total composite reward and its per-term breakdown.
The breakdown values (r_make, r_util, r_cost) are unweighted;
total applies the lambda_* weights.
Gating¶
rlsa.gating.policy
¶
RLSA per-agent gating policy (paper Fig. 1).
A shared encoder phi maps the local observation to a latent z, which
feeds three heads:
- gate head
G(z)-> probability of invoking the LLM - surrogate head
pi(z)-> fast bid in[bid_min, bid_max] - value head
V(z)-> PPO critic (training only)
The LLM itself is called outside this module, by the environment / agent loop.
StateEncoder(obs_dim, hidden_dim)
¶
Bases: Module
phi(o): two-layer MLP with LayerNorm.
SurrogateBidder(hidden_dim, bid_min, bid_max)
¶
Bases: Module
pi(z): fast bid score in [bid_min, bid_max].
GatingHead(hidden_dim)
¶
Bases: Module
G(z): probability of invoking the LLM.
ValueHead(hidden_dim)
¶
Bases: Module
V(z): state value for the PPO critic.
GatingPolicy(cfg)
¶
Bases: Module
Encoder + gate + surrogate + value head.
forward returns (bid, p_gate, value, latent).
act(obs, deterministic=False)
¶
Single-step inference.
With deterministic=True the gate is thresholded at
cfg.gate_threshold; moving the threshold changes the LLM call rate
of a trained policy without retraining.
evaluate(obs, gate_actions)
¶
Log-probability of the gate actions, value, and gate entropy.
rlsa.gating.confidence_gate
¶
Non-RL confidence-gate baseline.
Reuses a trained RLSA policy's encoder and surrogate (frozen) and adds a small
residual-error head r(z) ~ |surrogate_bid - LLM_bid|. The LLM is invoked when
the predicted error exceeds a threshold tau. Sweeping tau lets the
baseline be compared to RLSA at a matched LLM budget and with identical
surrogate quality. It never looks at the ground-truth job difficulty.
ResidualHead(hidden_dim=128)
¶
Bases: Module
r(z) -> predicted absolute bid error (softplus, >= 0).
ConfidenceGate(policy, residual_head, tau)
¶
Frozen RLSA surrogate + residual-error threshold. The RL gate head is unused.
decide(obs_t)
¶
Return (gate, surrogate_bid, predicted_error) for one observation.
obs_t has shape (1, obs_dim).
train_residual_head(policy, obs, err, epochs=400, lr=0.001)
¶
Fit a :class:ResidualHead on the frozen encoder's latents.
obs holds observations from gated steps of a trained RLSA run and err
the matching |LLM_bid - surrogate_bid|. Returns the head and final MSE.
Bidders¶
rlsa.bidders.base
¶
Bidder interface: what the gate=1 path calls.
A bidder scores an (AgentState, JobSpec) pair on a 0..100 scale and reports
how long it took. The reward penalizes that latency, so the gate learns when a
call is worth it. This module has no heavy dependencies.
AgentState(cpu_util, gpu_util, ram_util, disk_util, queue_length, neighbor_load, historical_success_rate=1.0)
dataclass
¶
The part of an agent's observation that a bidder (or a human) would use.
JobSpec(cpus, gpus=0, ram_gb=0.0, disk_gb=0.0, estimated_seconds=0.0, user='', job_id='')
dataclass
¶
The job being bid on.
BidResult(score, latency_seconds, succeeded=True, explanation='', provider='', model='', extra=dict())
dataclass
¶
One bid response. succeeded=False means a fallback score was returned.
Bidder
¶
Bases: Protocol
Anything that can produce a bid.
true_bid is only consumed by the mock oracle; real bidders ignore it.
capacity_bid(cpu_util, gpu_util, ram_util, disk_util)
¶
Resource-based heuristic bid in [0, 100]: more free capacity, higher bid.
Used by the capacity / always_surrogate baselines of the auction.
rlsa.bidders.mock
¶
Mock LLM bidder: a perfect oracle with Gaussian (reported) latency.
The environment knows the ground-truth bid and passes it via true_bid; the
mock echoes it back. Latency is reported, not slept, so training stays fast
while the reward still pays for every call.
rlsa.bidders.hf_local
¶
HuggingFace Transformers-backed local LLM bidder (used with Qwen-2.5 in the paper).
Loads an instruction-tuned model once and answers each bid() call with a
single integer in [0, 100]. Requires the hf extra (pip install rlsa[hf]).
Design choices¶
- Short
max_new_tokensplus an integer parse instead of grammar-constrained decoding; if no integer can be parsed the bidder returnsfallback_score. Load or generation errors also returnfallback_scorewithsucceeded=False. - Lazy model load on the first
bid()call, so importing this module is cheap. - Greedy decoding by default (
temperature=0) for reproducibility.
HFLocalBidder(model_name='Qwen/Qwen2.5-3B-Instruct', dtype='bfloat16', max_new_tokens=4, temperature=0.0, device_map='auto', fallback_score=50.0, prompt_name='baseline')
dataclass
¶
Local transformers-based LLM bidder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
HuggingFace model id (e.g. 'Qwen/Qwen2.5-3B-Instruct'). |
'Qwen/Qwen2.5-3B-Instruct'
|
dtype
|
str
|
'float16' or 'bfloat16' (bf16 on A100+); 'auto' lets HF decide. |
'bfloat16'
|
max_new_tokens
|
int
|
cap on generation length per bid. |
4
|
temperature
|
float
|
0.0 for greedy (default, reproducible). |
0.0
|
device_map
|
str
|
'auto' uses accelerate to place on GPU(s). |
'auto'
|
fallback_score
|
float
|
returned when generation fails to parse. |
50.0
|
Environments¶
rlsa.envs.gating_env
¶
Controlled single-agent gating environment (paper Sec. V-A).
Every step is one job. The agent emits a dual action {bid, gate}:
gate=0: the surrogatebidis used, corrupted by noise whose scale grows with the (hidden) job difficulty, so the surrogate is accurate on easy jobs and unreliable on hard ones;gate=1: the LLM bidder answers instead. By default the built-in oracle returns the true bid after a Gaussian latency; a real :class:~rlsa.bidders.Bidder(for example :class:~rlsa.bidders.hf_local.HFLocalBidder) can be attached viaGatingEnvConfig.bidder.
A bid error delays the job quadratically, which drives R_make; each LLM call
pays R_cost. The policy has to learn to gate only when difficulty is high.
Observation layout (obs_dim floats in [0, 1])::
obs[0:4] agent utilization (cpu, gpu, ram, disk)
obs[4:8] job resource request
obs[8] noisy difficulty signal
obs[9:] filler features
GatingEnv(cfg=None, seed=None)
¶
Bases: Env
Gymnasium environment for learning when to call the LLM.
rlsa.envs.auction
¶
Shared-cluster auction environment.
- one shared cluster with finite CPU / GPU / RAM / disk;
- a pre-generated job stream (identical for every algorithm under a given seed, so seeds are valid units of paired comparison);
- every agent bids on every job, the highest bid wins (ties: lowest agent id);
- the winner holds the job's resources for its whole (possibly bid-error inflated) duration;
- the winner receives the composite reward, losers receive 0.
This module also provides the :class:Cluster and :class:MetricsTracker used
by the threaded distributed auction (:mod:rlsa.envs.distributed) and the
FABRIC coordinator (:mod:rlsa.fabric.coordinator).
The auction is coordinated centrally (argmax); a decentralized consensus protocol is out of scope.
Cluster(cpus=64, gpus=8, ram_gb=256.0, disk_gb=4096.0, _t=0.0, _running=list(), _completed=list())
dataclass
¶
Shared HPC resource pool advanced by explicit, synchronous tick() calls.
Simulated time is decoupled from wall-clock time, so results do not depend on host speed.
AuctionEnv(cfg=None, seed=None)
¶
N agents bid on a shared cluster; one wins per job.
Synchronous usage::
env = AuctionEnv(cfg, seed=0)
env.reset()
while not env.done():
env.next_job()
for agent_id in range(cfg.n_agents):
obs, state = env.get_obs(agent_id)
... # compute (bid, gate, llm_latency) from obs/state
env.submit_bid(agent_id, bid, gate, llm_latency)
rewards = env.resolve_round() # picks winner, assigns the job
metrics = env.finalize()
next_job()
¶
Pop the next job from the stream and advance cluster time to its arrival.
get_obs(agent_id)
¶
Build the observation for one agent. Job is the round's current job.
Each agent has a slightly different "local view" via a per-agent noise on the difficulty signal slot. Resources are shared, so utilization is identical across agents (this is the centralized auction property).
submit_bid(agent_id, bid, gate, llm_latency, effective_bid=None)
¶
Record an agent's bid. effective_bid is the bid that will be compared (overrides bid if LLM was called and produced its own value).
resolve_round()
¶
Pick winner, assign job, return per-agent rewards (winner=composite, losers=0).
rlsa.envs.distributed
¶
Threaded asynchronous auction (paper Sec. V-B onward).
Each round (one job):
coordinator (main thread)
- builds every agent's local observation
- starts one worker thread per agent
- waits for bids; bids that arrive after ``bid_deadline_ms`` are flagged
stale (lightly penalized, still counted); dropped messages are lost
- the highest bid wins (deterministic or random tiebreak) and the winner
holds the job's resources until completion
agent worker (one thread per agent per round)
- inbound network delay / drop -> compute the bid (surrogate, LLM, or the
RLSA gate deciding between them) -> outbound delay / drop
RLSA agents learn online with PPO. In CTDE mode all agents share one policy (pooled updates); in DTDE mode every agent owns its policy and optimizer.
Scope: threads in one process with a simulated network (Gaussian delay plus
optional drop). Real processes over a real WAN are covered by
:mod:rlsa.fabric.
Supported algorithms: random, capacity, always_surrogate,
always_llm, oracle (privileged: calls the LLM exactly on hard jobs),
confidence_gate (non-RL baseline over a frozen RLSA surrogate) and rlsa.
DistributedConfig(base=AuctionConfig(), bid_deadline_ms=50.0, net_mean_ms=2.0, net_std_ms=0.5, net_drop_prob=0.0, net_mean_ms_per_agent=None, net_std_ms_per_agent=None, net_drop_prob_per_agent=None, bidder_kinds=None, bidder_kind='mock', hf_model_name='Qwen/Qwen2.5-7B-Instruct', hf_model_names_per_agent=None, sharing_mode='ctde', pretrain_steps=200, update_every_rounds=8, gamma=0.0, gae_lambda=0.95, confidence_tau=0.0, residual_path='', dump_residual_data='', tiebreak='deterministic', tiebreak_tol=1e-09, save_policy_path='', load_policy_path='')
dataclass
¶
NetworkSim(mean_ms=2.0, std_ms=0.5, drop_prob=0.0, seed=0)
dataclass
¶
Gaussian per-message delay (ms) plus Bernoulli message drop.
run_distributed(algo, cfg, seed, verbose=False)
¶
Run one thread-per-agent asynchronous auction episode.
Returns the :class:~rlsa.envs.auction.MetricsTracker metrics (makespan,
llm_calls_per_job, jain_fairness, per-agent wins, ...) plus
distributed fields: stale_bids, dropped_msgs,
bid_latency_ms_{mean,p95,p99}, deadline_misses_per_agent,
per_model_analysis and distributed_config.
clear_hf_cache()
¶
Drop cached HF bidders (e.g. between experiment cells) to free GPU memory.
Training¶
rlsa.ppo
¶
PPO trainer for the single-agent gating environment.
The gate is the RL-controlled Bernoulli action; the bid comes from the surrogate head. Whenever the gate calls the LLM, the returned bid is also used as a supervision target for the surrogate (auxiliary teacher loss), and an optional imitation pretraining stage warm-starts the surrogate before PPO.
Example::
from rlsa.envs.gating_env import GatingEnv, GatingEnvConfig
from rlsa.ppo import PPOConfig, RLSATrainer
env_cfg = GatingEnvConfig()
trainer = RLSATrainer(
env_fn=lambda: GatingEnv(cfg=env_cfg, seed=0),
cfg=PPOConfig(obs_dim=env_cfg.obs_dim, gamma=0.0, gae_lambda=0.0),
)
trainer.train(total_timesteps=20_000, pretrain_steps=3_000)
RLSATrainer(env_fn, cfg=None)
¶
A compact PPO trainer specialized for the RLSA gating policy.
pretrain_surrogate(n_steps=2000, lr=0.001)
¶
Run with gate=1 always, collect (obs, llm_bid) pairs, and train the surrogate head + encoder to imitate the LLM. This bootstraps a useful surrogate before PPO has to decide whether to trust it. Without this step PPO sees "gate=0 always gives a bad bid" and never explores the gate=0 path.
train(total_timesteps=10000, log_every=1, pretrain_steps=0, csv_log_path=None)
¶
Run training. If csv_log_path is given, write one row per PPO
update with rollout stats, loss components, and per-bucket gate
rates (see experiments/plots/plot_training.py).
FABRIC¶
rlsa.fabric.coordinator
¶
Auction coordinator for the real-network (FABRIC) deployment.
The coordinator owns the :class:~rlsa.envs.auction.AuctionEnv (the single
source of truth for jobs, cluster and metrics); agents are remote TCP peers
running :mod:rlsa.fabric.agent. Each round the job is broadcast to all live
agents concurrently and bids are collected with select() until a shared
deadline. Replies tagged with an older round_id are drained and discarded, so
an agent that misses one deadline rejoins in the next round instead of being
excluded. Connections that fail are marked dead and skipped.
The result dict has the same metric keys as the simulated auction, plus
wan_rtt_ms_{p50,p95,p99} and round_walltime_ms_{mean,p95}.
Run on the coordinator VM::
python -m rlsa.fabric.coordinator --algo rlsa --n-agents 4 --out result.json
accept_agents(server, n, timeout_s=120.0)
¶
Block until n agents have dialed in and sent hello. Returns {agent_id: sock}.
run_coordinator(algo, cfg, seed, host='0.0.0.0', port=0, deadline_s=5.0, server=None, conns=None, extra=None)
¶
Run one auction episode against remote agents.
If conns is given the agents are already connected (local harness);
otherwise a server socket is opened (or server is used) and the call
blocks until cfg.n_agents agents have registered.
main()
¶
Command-line entry point; binds 0.0.0.0 and writes the result JSON.
rlsa.fabric.agent
¶
Bidding agent for the real-network (FABRIC) deployment.
Connects to :mod:rlsa.fabric.coordinator over TCP and answers one bid per
round with a frozen policy (no training happens on the agents).
Protocol::
agent -> coord {"type": "hello", "agent_id"}
coord -> agent {"type": "job", "round_id", "obs", "state_tuple", "job_kw", "true_bid"}
agent -> coord {"type": "bid", "round_id", "agent_id", "bid", "gate", "llm_latency", "compute_s"}
coord -> agent {"type": "stop"} (or the socket closes)
Run on an agent VM::
python -m rlsa.fabric.agent --host <coord-ip> --port 9009 --agent-id 0 --obs-dim 20 --algo rlsa --policy-path policy.pt
compute_bid(algo, policy, bidder, msg, seed, agent_id)
¶
Return (bid, gate, llm_latency) for one round message.
rlsa.fabric.local
¶
Run the coordinator and N agents over 127.0.0.1 TCP in one process.
No testbed needed: every bid crosses a real socket, so this exercises the full wire path. Used by the tests and as a pre-flight check before a FABRIC run.
rlsa.fabric.wire
¶
Length-prefixed pickle framing over a stream socket.
Wire format: 4-byte big-endian unsigned length, then that many bytes of a pickled Python object. Transport only -- no domain knowledge.
Security note: pickle.loads runs arbitrary code from the payload. All peers must be trusted (same FABRIC slice / localhost). Do not expose these sockets to an untrusted network.
recv_msg(sock)
¶
Returns the next object, or None if the peer closed cleanly before a message started. Raises EOFError if the peer closed mid-message.