Spaces:
Running
Running
File size: 7,618 Bytes
0a7b128 4d76b14 0a7b128 4d76b14 0a7b128 4d76b14 0a7b128 4d76b14 0a7b128 4d76b14 0a7b128 4d76b14 0a7b128 4d76b14 0a7b128 0131132 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 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 | """Automated pytest suite for Libratio Fleet environment, physics, and kernel."""
from environment.fleet_env import FleetEnvironment
from environment.physics_model import compute_training_cost, score_precision_layer
from kernel_interface import AgenticKernel
OPTIMAL_NVIDIA = {
"embedding": "FP32",
"attention": "BF16",
"ffn": "FP8",
"layernorm": "BF16",
"output": "FP32",
}
def test_all_tasks_reset():
env = FleetEnvironment()
for task_id in ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]:
obs = env.reset(task_id)
assert obs["task_id"] == task_id
assert "scenario_id" in obs
def test_fleet_precision_episode():
env = FleetEnvironment()
env.reset("fleet_precision", scenario_id="small_fleet")
done = False
steps = 0
while not done:
steps += 1
res = env.step({"precision_strategy": OPTIMAL_NVIDIA, "reasoning": "optimal config"})
score = res["reward"]["score"]
assert 0.01 <= score <= 0.99
done = res["done"]
assert steps == 2
assert "fleet_summary" in res["info"]
assert res["info"]["fleet_summary"]["all_stable"] is True
def test_fleet_oversight_and_spike_detection():
env = FleetEnvironment()
env.reset("fleet_oversight", scenario_id="one_crash_two_healthy")
# Window 0: steps 0..20 (healthy)
r1 = env.step({"action_type": "continue_monitoring", "analysis": "initial healthy window"})
assert 0.01 <= r1["reward"]["score"] <= 0.99
assert r1["done"] is False
# Window 1: steps 20..40 contains crash_step=35 (1e8 spike + NaN)
r2 = env.step({"action_type": "continue_monitoring", "analysis": "checking next window"})
assert "Issues visible" in r2["reward"]["feedback"]
# String flagged_step must be coerced cleanly rather than raising TypeError
r3 = env.step({
"action_type": "flag_instability",
"flagged_model": "model_b",
"flagged_step": "35",
"root_cause": "fp8 embedding underflow model_b",
"analysis": "NaN detected in model_b",
})
assert r3["done"] is True
assert r3["reward"]["score"] > 0.80
def test_fleet_oversight_spike_at_window_boundary():
env = FleetEnvironment()
env.reset("fleet_oversight", scenario_id="one_crash_two_healthy")
# Force spike (1e8) as last element of window 0 without NaN yet
env.scenario["trajectories"]["model_b"]["loss"][19] = 1e8
r = env.step({"action_type": "continue_monitoring", "analysis": "checking spike"})
assert "Issues visible" in r["reward"]["feedback"]
def test_fleet_resource_cost_respects_gpu_count_and_rate():
env = FleetEnvironment()
obs = env.reset("fleet_resource", scenario_id="micro_fleet")
models = obs["models"]
alloc_1 = {
models[0]["model_id"]: {"gpus": 1, "precision_strategy": OPTIMAL_NVIDIA},
models[1]["model_id"]: {"gpus": 1, "precision_strategy": OPTIMAL_NVIDIA},
}
r1 = env.step({"allocations": alloc_1})
assert 0.01 <= r1["reward"]["score"] <= 0.99
cost_1_gpu = r1["info"]["per_model"][models[0]["model_id"]]["cost_usd"]
# Compare against compute_training_cost for 2 GPUs at $1.50/hr
m_2gpu = compute_training_cost(
total_params=3_800_000_000,
precision_strategy=OPTIMAL_NVIDIA,
layer_distribution={"embedding": 0.15, "attention": 0.25, "ffn": 0.40, "layernorm": 0.002, "output": 0.198},
num_gpus=2,
cost_per_gpu_hour=1.50,
)
assert abs(m_2gpu["cost_usd"] - 2 * cost_1_gpu) <= 2.0
def test_fleet_recovery_episode():
env = FleetEnvironment()
obs = env.reset("fleet_recovery")
assert obs["phase"] == "diagnose"
r1 = env.step({
"diagnosed_model": obs["crashed_model"]["model_id"],
"root_cause": "fp8 embedding output overflow",
"reasoning": "NaN in loss trajectory indicates precision failure",
})
assert r1["done"] is False
assert r1["reward"]["score"] >= 0.50
r2 = env.step({
"new_precision_strategy": OPTIMAL_NVIDIA,
"reasoning": "Switch to safe config: FP32 embedding and output",
})
assert r2["done"] is False
assert r2["reward"]["score"] >= 0.70
r3 = env.step({
"reasoning": "Recovery plan is stable and safe. Will monitor loss for 100 steps.",
"confidence": "high",
})
assert r3["done"] is True
assert r3["reward"]["score"] >= 0.80
def test_invalid_inputs_never_crash():
env = FleetEnvironment()
env.reset("fleet_precision", scenario_id="small_fleet")
# Non-dict action
r_bad_action = env.step(["not", "a", "dict"])
assert r_bad_action["reward"]["score"] == 0.01
# Unsupported precision in compute_training_cost must not raise KeyError
res = compute_training_cost(
total_params=7_000_000_000,
precision_strategy={"embedding": "INT4", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"},
layer_distribution={"embedding": 0.15, "attention": 0.25, "ffn": 0.40, "layernorm": 0.002, "output": 0.198},
)
assert res["estimated_stable"] is False
assert res["unsupported_precisions"]
# Invalid gpu type in fleet_resource
env.reset("fleet_resource", scenario_id="small_fleet")
r_bad_gpu = env.step({"allocations": {"model_a": {"gpus": "four"}, "model_b": {"gpus": 2}}})
assert r_bad_gpu["reward"]["score"] == 0.01
# Kernel latency buffer stays bounded
kernel = AgenticKernel()
assert kernel._latencies.maxlen == 10_000
score, _ = score_precision_layer("ffn", "INVALID")
assert score == 0.01
def test_training_log_metric_alignment(tmp_path):
import json
from generate_training_graphs import load_training_metrics
log_file = tmp_path / "training_logs.json"
# Simulate separate TRL reward and loss events for the same step
log_file.write_text(
json.dumps([
{"step": 10, "reward": 0.42, "completions/mean_length": 280},
{"step": 10, "loss": 1.25, "learning_rate": 2e-5},
{"step": 20, "loss": 0.65, "learning_rate": 1e-5},
{"step": 20, "reward": 0.88, "completion_length": 254},
]),
encoding="utf-8",
)
metrics = load_training_metrics(str(log_file))
assert metrics["steps"] == [10, 20]
assert metrics["rewards"] == [0.42, 0.88]
assert metrics["losses"] == [1.25, 0.65]
assert metrics["learning_rates"] == [2e-5, 1e-5]
assert metrics["completion_lengths"] == [280.0, 254.0]
def test_eval_comparison_mode(tmp_path):
from fleet_inference import run_eval
def mock_hardware_aware_llm(_sys, obs, **_kw):
prec = obs.get("available_precisions", [])
ffn = "INT8" if "INT8" in prec and "FP8" not in prec else "FP8"
return {
"precision_strategy": {
"embedding": "FP32",
"attention": "BF16",
"ffn": ffn,
"layernorm": "BF16",
"output": "FP32",
},
"reasoning": "mock eval",
}
out_path = tmp_path / "eval.json"
report = run_eval(
task_id="fleet_precision",
scenarios=["small_fleet", "google_tpu_fleet"],
episodes=1,
baselines_only=False,
trained_model="mock-grpo",
output_path=str(out_path),
llm_caller=mock_hardware_aware_llm,
)
assert out_path.exists()
assert "Random Baseline" in report["overall"]
assert "Greedy Baseline" in report["overall"]
assert "Trained (mock-grpo)" in report["overall"]
assert report["overall"]["Trained (mock-grpo)"]["mean_score"] > 0.80
|