billshockley's picture
Upload folder using huggingface_hub
d39fee6 verified
#!/bin/bash
# Copyright lowRISC contributors (OpenTitan project).
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
#
# TitanBench verifier for SRAM_CTRL testpoint: executable
set -euo pipefail
REPO_TOP="/home/dev/src"
IP_NAME="sram_ctrl"
WORKSPACE="/home/dev/workspace"
DV_DIR="${REPO_TOP}/hw/ip/${IP_NAME}/dv"
SIM_CFG="${DV_DIR}/sram_ctrl_main_sim_cfg.hjson"
SCRATCH_DIR="${HOME}/master/${IP_NAME}-sim-xcelium"
SEED=${TITANBENCH_SEED:-1}
REWARD_DIR="/logs/verifier"
mkdir -p "$REWARD_DIR"
echo "=== TitanBench Verifier: SRAM_CTRL executable ==="
# ─── Check agent produced output ─────────────────────────────────────
if [ ! -f "${WORKSPACE}/agent_sim_cfg.hjson" ]; then
echo "ERROR: No agent_sim_cfg.hjson found"
echo '{"score": 0}' > "${REWARD_DIR}/reward.json"
exit 0
fi
NUM_SEQS=$(find "${WORKSPACE}/sequences/" -name "*_vseq.sv" 2>/dev/null | wc -l)
if [ "$NUM_SEQS" -eq 0 ]; then
echo "ERROR: No sequences found in workspace/sequences/"
echo '{"score": 0}' > "${REWARD_DIR}/reward.json"
exit 0
fi
echo "Found ${NUM_SEQS} agent sequence(s)"
# ─── Wire agent sequence into environment ────────────────────────────
python3 /home/dev/scripts/wire_sequences.py
# Get test name from agent config
TEST_NAME=$(python3 -c "
import hjson
with open('${WORKSPACE}/agent_sim_cfg.hjson') as f:
cfg = hjson.load(f)
for t in cfg.get('tests', []):
print(t['name'])
" | head -1)
if [ -z "$TEST_NAME" ]; then
echo "ERROR: No test entry in agent_sim_cfg.hjson"
echo '{"score": 0}' > "${REWARD_DIR}/reward.json"
exit 0
fi
echo "Running test: ${TEST_NAME}"
# ─── Clean and run ───────────────────────────────────────────────────
pkill -9 -f "xrun.*${IP_NAME}" 2>/dev/null || true
pkill -9 -f "xmsim.*${IP_NAME}" 2>/dev/null || true
rm -rf "${SCRATCH_DIR}" 2>/dev/null || true
cd "$REPO_TOP"
python3 util/dvsim/dvsim.py "$SIM_CFG" \
--tool xcelium \
-i $TEST_NAME \
--fixed-seed "$SEED" \
${TITANBENCH_NO_COV:---cov} \
--build-timeout-mins 120 \
--max-parallel ${TITANBENCH_MAX_PARALLEL:-5} \
2>&1 | tee /tmp/verifier_run.log || true
cp /tmp/verifier_run.log /logs/artifacts/verifier_run.log 2>/dev/null || true
# ─── Extract agent coverage bins ─────────────────────────────────────
AGENT_BINS_JSON="/tmp/agent_cov_bins.json"
MERGED_DB=$(find /home/dev/src/scratch -path "*/cov_merge/merged" -type d 2>/dev/null | head -1)
if [ -n "$MERGED_DB" ] && [ -d "$MERGED_DB" ]; then
echo "Extracting coverage bins from $MERGED_DB..."
# Write TCL extraction script inline
cat > /tmp/extract_bins.tcl << 'TCLEOF'
report -detail -metrics covergroup -all -out /tmp/agent_cov_detail.txt
exit
TCLEOF
COV_BINS_OUT=/tmp/agent_cov_detail.txt \
imc -64bit -load "$MERGED_DB" -exec /tmp/extract_bins.tcl 2>/dev/null || true
# Parse the detail report into JSON
if [ -f /tmp/agent_cov_detail.txt ]; then
python3 - /tmp/agent_cov_detail.txt "$AGENT_BINS_JSON" << 'PARSEOF'
import json, re, sys
report_path, output_path = sys.argv[1], sys.argv[2]
hit_bins, all_bins = set(), set()
hierarchy = []
with open(report_path) as f:
for line in f:
line = line.rstrip()
if not line:
continue
if not line.startswith('|') and not line.startswith(' '):
m = re.match(r'^(\S+.*?)\s+\d+\.\d+%', line)
if m:
hierarchy = [m.group(1).strip()]
continue
m = re.match(r'^((?:\| )*)\|--(\S+)\s+(.*)', line)
if not m:
continue
depth = m.group(1).count('| ') + 1
name = m.group(2).strip()
remainder = m.group(3).strip()
while len(hierarchy) > depth:
hierarchy.pop()
hierarchy.append(name)
pct = re.match(r'(\d+\.\d+)%\s+\((\d+)/(\d+)\)', remainder)
if pct and int(pct.group(3)) == 1:
bin_path = "::".join(hierarchy)
all_bins.add(bin_path)
if int(pct.group(2)) > 0:
hit_bins.add(bin_path)
with open(output_path, 'w') as f:
json.dump({"total_bins": len(all_bins), "hit_bins": len(hit_bins), "bins": sorted(hit_bins)}, f)
print(f"Agent bins: {len(hit_bins)}/{len(all_bins)}")
PARSEOF
fi
fi
# ─── Parse results ────────────────────────────────────────────────────
echo "Parsing results..."
TOTAL=0
PASSED=0
FAILED=0
if grep -q "StatusPrinter.*\[.*run.*\]" /tmp/verifier_run.log 2>/dev/null; then
LAST_LINE=$(grep "StatusPrinter.*\[.*run.*\]" /tmp/verifier_run.log | tail -1)
PASSED=$(echo "$LAST_LINE" | grep -oP 'P:\s*\K\d+' || echo 0)
FAILED=$(echo "$LAST_LINE" | grep -oP 'F:\s*\K\d+' || echo 0)
TOTAL=$(echo "$LAST_LINE" | grep -oP 'T:\s*\K\d+' || echo 0)
fi
PASS_RATE=0
if [ "$TOTAL" -gt 0 ]; then
PASS_RATE=$(echo "scale=4; $PASSED / $TOTAL" | bc)
fi
echo "Pass rate: ${PASSED}/${TOTAL} (${PASS_RATE})"
# ─── Compute score ───────────────────────────────────────────────────
python3 - /tmp/verifier_run.log "${REWARD_DIR}/reward.json" "$PASSED" "$FAILED" "$TOTAL" <<'PYEOF'
import json
import re
import sys
import os
import glob
log_path = sys.argv[1]
reward_path = sys.argv[2]
total_passed = int(sys.argv[3])
total_failed = int(sys.argv[4])
total_runs = int(sys.argv[5])
pass_rate = total_passed / total_runs if total_runs > 0 else 0.0
# ── Parse per-seed UVM errors from run logs ──────────────────────────
scratch = "/home/dev/src/scratch"
per_seed_details = []
run_logs = glob.glob(f"{scratch}/*/latest/run.log")
for run_log in sorted(run_logs):
test_dir = os.path.basename(os.path.dirname(os.path.dirname(run_log)))
uvm_errors = 0
uvm_fatals = 0
scoreboard_mismatches = 0
try:
with open(run_log) as f:
for line in f:
if "UVM_ERROR" in line and ":" in line:
m = re.search(r"UVM_ERROR\s*:\s*(\d+)", line)
if m:
uvm_errors = max(uvm_errors, int(m.group(1)))
if "UVM_FATAL" in line and ":" in line:
m = re.search(r"UVM_FATAL\s*:\s*(\d+)", line)
if m:
uvm_fatals = max(uvm_fatals, int(m.group(1)))
if "mismatch" in line.lower():
scoreboard_mismatches += 1
except Exception:
pass
per_seed_details.append({
"test_dir": test_dir,
"uvm_errors": uvm_errors,
"uvm_fatals": uvm_fatals,
"scoreboard_mismatches": scoreboard_mismatches,
"passed": uvm_errors == 0 and uvm_fatals == 0,
})
total_scoreboard_mismatches = sum(d["scoreboard_mismatches"] for d in per_seed_details)
seeds_with_errors = sum(1 for d in per_seed_details if not d["passed"])
total_seeds = len(per_seed_details) if per_seed_details else total_runs
# Correctness
if total_passed == 0 and total_runs > 0:
correctness = 0.0
elif per_seed_details:
correctness = (total_seeds - seeds_with_errors) / total_seeds if total_seeds > 0 else 0.0
else:
correctness = pass_rate
# ── Compute normalized coverage ─────────────────────────────────────
normalized_cov = 0.0
# Load agent coverage bins
agent_bins = set()
agent_bins_path = "/tmp/agent_cov_bins.json"
if os.path.exists(agent_bins_path):
try:
with open(agent_bins_path) as f:
agent_data = json.load(f)
agent_bins = set(agent_data.get("bins", []))
except Exception:
pass
# Load oracle coverage bins
oracle_bins = set()
oracle_bins_path = "/tests/oracle_coverage_bins.json"
if os.path.exists(oracle_bins_path):
try:
with open(oracle_bins_path) as f:
oracle_data = json.load(f)
oracle_bins = set(oracle_data.get("bins", []))
except Exception:
pass
# Compute intersection ratio
if oracle_bins:
intersection = agent_bins & oracle_bins
normalized_cov = len(intersection) / len(oracle_bins)
# ── Weighted score ───────────────────────────────────────────────────
weighted_score = (
0.70 * correctness +
0.30 * normalized_cov
)
# ── Write rewards ────────────────────────────────────────────────────
reward = {
"weighted_score": round(weighted_score, 4),
"correctness": round(correctness, 4),
"pass_rate": round(pass_rate, 4),
"total_passed": total_passed,
"total_failed": total_failed,
"total_runs": total_runs,
"scoreboard_mismatches": total_scoreboard_mismatches,
"normalized_coverage": round(normalized_cov, 4),
"agent_bins_hit": len(agent_bins),
"oracle_bins_total": len(oracle_bins),
"oracle_bins_matched": len(agent_bins & oracle_bins) if oracle_bins else 0,
"per_seed_summary": {
"total_seeds": total_seeds,
"seeds_passed": total_seeds - seeds_with_errors,
"seeds_with_errors": seeds_with_errors,
"total_scoreboard_mismatches": total_scoreboard_mismatches,
},
}
# Harbor: single-key reward.json
with open(reward_path, "w") as f:
json.dump({"score": round(weighted_score, 4)}, f, indent=2)
# Full details
with open(reward_path.replace("reward.json", "reward_details.json"), "w") as f:
json.dump(reward, f, indent=2)
print(f"\n{'='*60}")
print(f"SCORING: {correctness:.2%} correct, {normalized_cov:.2%} normalized coverage")
print(f" Agent bins: {len(agent_bins)}, Oracle bins: {len(oracle_bins)}, Matched: {len(agent_bins & oracle_bins) if oracle_bins else 0}")
print(f"WEIGHTED SCORE: {weighted_score:.2%}")
print(f"{'='*60}")
PYEOF
echo ""
echo "=== Verification complete ==="
cat "${REWARD_DIR}/reward.json"