Download testing/agent_evaluation/evaluators/ut_env_code.py from yuhanqin/ut-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/evaluators/ut_env_code.py
- Command line
-
hf download hf://datasets/yuhanqin/ut-evaluation/testing/agent_evaluation/evaluators/ut_env_code.py
-
curl -L -o ut_env_code.py https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/evaluators/ut_env_code.py
18 kB
| """Environment-code evaluators UT-C001 through UT-C013. | |
| C005 through C013 locate the force target with ``script_locate`` only. | |
| ``ut_c_force_target`` can ask a model when that parse fails; its record is | |
| not passed into those nine metrics. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from pathlib import Path | |
| from typing import Any | |
| from .contracts import (EmptyParams, EvaluationContext, EvaluatorDefinition, | |
| EvaluatorResult, EvidenceBinding, LLMJudgeDefinition, | |
| LLMJudgeRequest, ScorePolicy, assessment_result, | |
| incomplete_result) | |
| from .ut_common import check, measurement, normalize_empty, unavailable | |
| from .ut_mechanical import _manifest, _path_from_manifest, _task_dir | |
| _WIDTH = re.compile(r"logic\s*\[(\d+)\s*:\s*(\d+)\]\s*(\w+)") | |
| _CHECK = re.compile(r"\bcheck_actual\s*\(\s*(\w+)\s*\)") | |
| _PASS_FAIL = ScorePolicy( | |
| label_mapping={"pass": "pass", "partial": "partial", "fail": "fail"}, | |
| score_mapping={"pass": 1.0, "partial": 0.5, "fail": 0.0}, | |
| ) | |
| def _env(context: EvaluationContext) -> dict[str, Any] | None: | |
| task = _task_dir(context) | |
| manifest = _manifest(task) if task is not None else None | |
| if task is None or manifest is None: | |
| return None | |
| env = _path_from_manifest(task, manifest, "env_output_dir") | |
| if env is None: | |
| return None | |
| identity = manifest.get("identity") if isinstance(manifest.get("identity"), dict) else {} | |
| dut = identity.get("dut_name") if isinstance(identity.get("dut_name"), str) else "" | |
| tb = env / "tb" / f"tb_{dut}.sv" | |
| checker = env / "tb" / f"{dut}_checker.sv" | |
| model = env / "tb" / f"{dut}_ref_model.sv" | |
| return { | |
| "env": env, "dut": dut, "tb": tb, "checker": checker, "model": model, | |
| "tb_text": tb.read_text(encoding="utf-8", errors="replace") if tb.is_file() else "", | |
| "checker_text": checker.read_text(encoding="utf-8", errors="replace") if checker.is_file() else "", | |
| "model_text": model.read_text(encoding="utf-8", errors="replace") if model.is_file() else "", | |
| "sim": env / "sim", | |
| } | |
| def _strip_comments(text: str) -> str: | |
| no_block = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL) | |
| return "\n".join(line.split("//", 1)[0] for line in no_block.splitlines()) | |
| def _widths(text: str) -> dict[str, int]: | |
| found = {} | |
| for high, low, name in _WIDTH.findall(text): | |
| found[name] = abs(int(high) - int(low)) + 1 | |
| return found | |
| def _signal_in_expr(expr: str, widths: dict[str, int]) -> str | None: | |
| names = [name for name in re.findall(r"\b[A-Za-z_]\w*\b", expr) if name in widths] | |
| if not names: | |
| return None | |
| return max(names, key=lambda name: widths[name]) | |
| def script_locate(tb: str) -> dict[str, Any] | None: | |
| """Pick the widest data signal that a check_actual call actually samples.""" | |
| code = _strip_comments(tb) | |
| widths = _widths(code) | |
| lines = code.splitlines() | |
| best: dict[str, Any] | None = None | |
| for index, line in enumerate(lines): | |
| match = _CHECK.search(line) | |
| if match is None: | |
| continue | |
| txn = match.group(1) | |
| window = lines[max(0, index - 20):index + 1] | |
| assignment = next( | |
| (item for item in reversed(window) if re.search(rf"\b{txn}\s*\.\s*data\s*=", item)), | |
| None, | |
| ) | |
| if assignment is None: | |
| continue | |
| expr = assignment.split("=", 1)[1] | |
| signal = _signal_in_expr(expr, widths) | |
| if signal is None or widths[signal] <= 1: | |
| continue | |
| condition = "" | |
| for item in reversed(window): | |
| found = re.search(r"\bif\s*\((.+)\)", item) | |
| if found: | |
| condition = found.group(1).strip() | |
| break | |
| quote = "\n".join(line for line in window if line.strip()) | |
| candidate = { | |
| "signal": signal, "width": widths[signal], "condition": condition, | |
| "quote": quote, "lsb": 0, "msb": widths[signal] - 1, | |
| } | |
| if best is None or candidate["width"] > best["width"]: | |
| best = candidate | |
| return best | |
| def validate_extraction(tb: str, record: dict[str, Any]) -> dict[str, Any] | None: | |
| """Keep a model record only when its quote, signal, and width match the TB.""" | |
| quote = record.get("quote") | |
| signal = record.get("signal") | |
| width = record.get("width") | |
| condition = record.get("condition") | |
| if not isinstance(quote, str) or quote.strip() not in tb: | |
| return None | |
| if not isinstance(signal, str) or signal not in _widths(tb): | |
| return None | |
| if width != _widths(tb)[signal] or width <= 1: | |
| return None | |
| if not isinstance(condition, str) or condition not in tb: | |
| return None | |
| return {"signal": signal, "width": width, "condition": condition, "quote": quote, | |
| "lsb": 0, "msb": width - 1} | |
| def force_snippet(target: dict[str, Any], kind: str) -> str: | |
| """Render the force/release lines for one metric. The signal comes from the TB.""" | |
| signal = target["signal"] | |
| condition = target["condition"] or "1'b1" | |
| msb = target["msb"] | |
| if kind == "lsb": | |
| body = f"{signal}[{target['lsb']}] = ~{signal}[{target['lsb']}]" | |
| elif kind == "x": | |
| body = f"{signal} = {{{target['width']}{{1'bx}}}}" | |
| elif kind == "msb": | |
| body = f"{signal}[{msb}] = ~{signal}[{msb}]" | |
| elif kind == "multi": | |
| body = f"{signal}[{msb}:{target['lsb']}] = ~{signal}[{msb}:{target['lsb']}]" | |
| elif kind == "delay": | |
| body = f"{signal} <= {signal}" | |
| elif kind == "drop": | |
| body = f"{condition.split('&&', 1)[0].strip()} = 1'b0" | |
| elif kind == "repeat": | |
| body = f"{signal} = {signal}" | |
| elif kind == "zeros": | |
| body = f"{signal} = '0" | |
| elif kind == "ones": | |
| body = f"{signal} = {{{target['width']}{{1'b1}}}}" | |
| else: | |
| body = f"{signal}[{target['lsb']}] = ~{signal}[{target['lsb']}]" | |
| return f"if ({condition}) begin force {body}; release {signal}; end" | |
| def _log_text(env: dict[str, Any], name: str) -> str: | |
| path = env["sim"] / name | |
| if not path.is_file(): | |
| return "" | |
| return path.read_text(encoding="utf-8", errors="replace") | |
| def score_c005(log: str) -> bool: | |
| return "[SB] mismatch" in log | |
| def score_c006(log: str) -> bool: | |
| return "[SB] mismatch" in log and re.search(r"act=.*[Xx]", log, re.DOTALL) is not None | |
| def score_c007(log: str) -> bool: | |
| return "[SB] mismatch" in log | |
| def score_c008(log: str, exit_code: int | None) -> bool: | |
| return "[SB] mismatch" in log and "exp=" in log and "act=" in log and exit_code not in (None, 0) | |
| def score_c009(delay_log: str, legal_log: str) -> bool: | |
| return "[SB] mismatch" in delay_log and "[SB] mismatch" not in legal_log and bool(legal_log) | |
| def score_c010(log: str) -> bool: | |
| match = re.search(r"residue=([1-9]\d*)", log) | |
| return match is not None | |
| def score_c011(log: str) -> bool: | |
| return "unexpected output" in log | |
| def score_c012(bad_log: str, legal_log: str) -> bool: | |
| bad_hits = len(re.findall(r"\[SB\] mismatch", bad_log)) | |
| return bad_hits >= 2 and "[SB] mismatch" not in legal_log and bool(legal_log) | |
| def score_c013(log: str, injected: int) -> bool: | |
| summaries = re.findall(r"\[SB_SUMMARY\].*failed=(\d+).*residue=(\d+)", log) | |
| if len(summaries) != 1: | |
| return False | |
| failed, residue = summaries[0] | |
| return int(failed) == injected and "residue=" in log and int(residue) != int(failed) | |
| def ut_c001_scoreboard(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"] or not env["checker_text"]: | |
| return unavailable("UT-C001", "TB 或 checker 不存在") | |
| return check("UT-C001", { | |
| "checker": "function void check_actual" in env["checker_text"] and "add_expected" in env["checker_text"], | |
| "tb": "check_actual(" in env["tb_text"] and "add_expected(" in env["tb_text"], | |
| "both_paths": "rm.predict" in env["tb_text"] and "add_expected(" in env["tb_text"], | |
| }, "scoreboard 两路接入") | |
| def ut_c002_monitor(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return unavailable("UT-C002", "TB 不存在") | |
| text = env["tb_text"] | |
| return check("UT-C002", { | |
| "clock": "posedge" in text and "check_actual(" in text, | |
| }, "采样后比对") | |
| def ut_c003_reference_model(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["model_text"] or not env["tb_text"]: | |
| return unavailable("UT-C003", "reference model 或 TB 不存在") | |
| return check("UT-C003", { | |
| "predict": "function" in env["model_text"] and "predict" in env["model_text"], | |
| "called": "rm.predict(" in env["tb_text"], | |
| }, "reference model 输入输出") | |
| def ut_c004_connections(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return unavailable("UT-C004", "TB 不存在") | |
| text = env["tb_text"] | |
| return check("UT-C004", { | |
| "same_input": "rm.predict(" in text and "add_expected(" in text, | |
| "sampled_output": "check_actual(" in text, | |
| }, "激励、采样和比对") | |
| def _located(env: dict[str, Any]) -> dict[str, Any] | None: | |
| return script_locate(env["tb_text"]) | |
| def _force_metric(context: EvaluationContext, metric: str, log_name: str, score) -> EvaluatorResult: | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return unavailable(metric, "TB 不存在") | |
| target = _located(env) | |
| if target is None: | |
| return unavailable(metric, "TB 里没有解析出数据采样点") | |
| log = _log_text(env, log_name) | |
| if not log: | |
| return unavailable(metric, f"注入点是 {target['signal']}[{target['msb']}:{target['lsb']}],还没有 {log_name}") | |
| return check(metric, {"detected": bool(score(log))}, f"force {target['signal']}") | |
| def ut_c005_lsb(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| return _force_metric(context, "UT-C005", "force_c005.log", score_c005) | |
| def ut_c006_x(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| return _force_metric(context, "UT-C006", "force_c006.log", score_c006) | |
| def ut_c007_msb(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| return _force_metric(context, "UT-C007", "force_c007.log", score_c007) | |
| def ut_c008_multibit(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return unavailable("UT-C008", "TB 不存在") | |
| target = _located(env) | |
| if target is None: | |
| return unavailable("UT-C008", "TB 里没有解析出数据采样点") | |
| log = _log_text(env, "force_c008.log") | |
| code_path = env["sim"] / "force_c008.exit" | |
| if not log or not code_path.is_file(): | |
| return unavailable("UT-C008", f"注入点是 {target['signal']},还没有日志或退出码") | |
| try: | |
| code = int(code_path.read_text(encoding="utf-8").strip()) | |
| except ValueError: | |
| return unavailable("UT-C008", "退出码不是整数") | |
| return check("UT-C008", {"detected": score_c008(log, code)}, f"force {target['signal']}") | |
| def ut_c009_delay(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return unavailable("UT-C009", "TB 不存在") | |
| if _located(env) is None: | |
| return unavailable("UT-C009", "TB 里没有解析出数据采样点") | |
| delay = _log_text(env, "force_c009_delay.log") | |
| legal = _log_text(env, "force_c009_legal.log") | |
| if not delay or not legal: | |
| return unavailable("UT-C009", "缺少延迟违例日志或合法等待日志") | |
| return check("UT-C009", {"detected": score_c009(delay, legal)}, "延迟违例与合法等待") | |
| def ut_c010_drop(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| return _force_metric(context, "UT-C010", "force_c010.log", score_c010) | |
| def ut_c011_repeat(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| return _force_metric(context, "UT-C011", "force_c011.log", score_c011) | |
| def ut_c012_constants(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return unavailable("UT-C012", "TB 不存在") | |
| if _located(env) is None: | |
| return unavailable("UT-C012", "TB 里没有解析出数据采样点") | |
| bad = _log_text(env, "force_c012_bad.log") | |
| legal = _log_text(env, "force_c012_legal.log") | |
| if not bad or not legal: | |
| return unavailable("UT-C012", "缺少全 0/全 1 日志或合法对照日志") | |
| return check("UT-C012", {"detected": score_c012(bad, legal)}, "全 0/全 1") | |
| def ut_c013_count(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return unavailable("UT-C013", "TB 不存在") | |
| if _located(env) is None: | |
| return unavailable("UT-C013", "TB 里没有解析出数据采样点") | |
| log = _log_text(env, "force_c013.log") | |
| if not log: | |
| return unavailable("UT-C013", "还没有 force_c013.log") | |
| return check("UT-C013", {"detected": score_c013(log, 2)}, "failed 计数") | |
| FORCE_TARGET_JUDGE = LLMJudgeDefinition( | |
| prompt_template="""从 TB 中抽出唯一的数据采样点,供后续 force 脚本使用。不要写 force,不要判断测试是否通过。 | |
| 检查对象: | |
| - 文件:${tb_path} | |
| - 正文里每次 check_actual 之前,把 DUT 输出写进事务数据字段的语句。 | |
| 检查标准: | |
| - 选择位宽大于 1、并且会被 sanity 用例采样到的那一路。 | |
| - signal 必须是正文里的信号名。width 必须等于它的 logic 声明位宽。condition 必须是包住这次采样的 if 条件。quote 必须是正文中的连续原文。 | |
| - 找不到这样一路时 label 用 fail,其余字段留空字符串,width 用 0。 | |
| 返回: | |
| - label 只能是 pass、partial、fail。partial 表示有多路同样宽,已任选一路并在 reason 里说明。 | |
| - reason 说明为什么选这根信号。 | |
| - evidence_refs 只能从这些名字里选,至少一项:${evidence_refs} | |
| - signal、width、condition、quote 按上面的标准填写。 | |
| TB 正文: | |
| ${tb_text}""", | |
| input_mapping={ | |
| "tb_path": EvidenceBinding("tb_path", "text"), | |
| "tb_text": EvidenceBinding("tb_text", "text"), | |
| "evidence_refs": EvidenceBinding("evidence_refs", "json"), | |
| }, | |
| response_schema={ | |
| "type": "object", "additionalProperties": False, | |
| "required": ["label", "reason", "evidence_refs", "signal", "width", "condition", "quote"], | |
| "properties": { | |
| "label": {"type": "string", "enum": ["pass", "partial", "fail"]}, | |
| "reason": {"type": "string", "minLength": 1}, | |
| "evidence_refs": {"type": "array", "minItems": 1, "items": {"type": "string"}}, | |
| "signal": {"type": "string"}, | |
| "width": {"type": "integer", "minimum": 0}, | |
| "condition": {"type": "string"}, | |
| "quote": {"type": "string"}, | |
| }, | |
| }, | |
| output_mapping={ | |
| "label": "label", "reason": "explanation", "evidence_refs": "evidence_refs", | |
| "signal": "metadata.signal", "width": "metadata.width", | |
| "condition": "metadata.condition", "quote": "metadata.quote", | |
| }, | |
| score_policy=_PASS_FAIL, | |
| ) | |
| def ut_c_force_target(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult | LLMJudgeRequest: | |
| del params | |
| env = _env(context) | |
| if env is None or not env["tb_text"]: | |
| return incomplete_result("TB 不存在") | |
| target = script_locate(env["tb_text"]) | |
| if target is not None: | |
| return assessment_result( | |
| score=1.0, label="pass", | |
| explanation=f"{target['signal']}[{target['msb']}:{target['lsb']}] when {target['condition']}", | |
| metadata=target, | |
| ) | |
| return LLMJudgeRequest( | |
| evidence={"tb_path": str(env["tb"]), "tb_text": env["tb_text"][:12000]}, | |
| evidence_refs=("tb_text",), | |
| projection_truncated=len(env["tb_text"]) > 12000, | |
| ) | |
| def _assessment(evaluator_id: str, rule: Any) -> EvaluatorDefinition: | |
| return EvaluatorDefinition( | |
| evaluator_id=evaluator_id, family="execution", result_kind="assessment", | |
| expansion="once", rule=rule, scope="skill", judge=FORCE_TARGET_JUDGE, | |
| required_evidence=frozenset({"execution_workspace"}), aggregation="mean", | |
| direction="maximize", params_type=EmptyParams, normalize_params=normalize_empty, | |
| params_schema={"type": "object", "additionalProperties": False}, | |
| ) | |
| UT_ENV_EVALUATORS = { | |
| **{ | |
| item[0]: measurement(item[0], item[1], item[2]) | |
| for item in ( | |
| ("ut_c001_scoreboard", ut_c001_scoreboard, "UT-C001"), | |
| ("ut_c002_monitor", ut_c002_monitor, "UT-C002"), | |
| ("ut_c003_reference_model", ut_c003_reference_model, "UT-C003"), | |
| ("ut_c004_connections", ut_c004_connections, "UT-C004"), | |
| ("ut_c005_lsb", ut_c005_lsb, "UT-C005"), | |
| ("ut_c006_x", ut_c006_x, "UT-C006"), | |
| ("ut_c007_msb", ut_c007_msb, "UT-C007"), | |
| ("ut_c008_multibit", ut_c008_multibit, "UT-C008"), | |
| ("ut_c009_delay", ut_c009_delay, "UT-C009"), | |
| ("ut_c010_drop", ut_c010_drop, "UT-C010"), | |
| ("ut_c011_repeat", ut_c011_repeat, "UT-C011"), | |
| ("ut_c012_constants", ut_c012_constants, "UT-C012"), | |
| ("ut_c013_count", ut_c013_count, "UT-C013"), | |
| ) | |
| }, | |
| "ut_c_force_target": _assessment("ut_c_force_target", ut_c_force_target), | |
| } | |