Spaces:
Running

Libratio / test_fleet.py
Aaryan Parik
fix: align training plot metrics, real-log graphing, and add eval comparison mode
0131132
Raw History Blame Contribute Delete
7.62 kB
"""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