# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """Tests of datasets: the target's generated e2e test, run by the tree's own runner. A test of datasets (``spec/verification.py``) runs, at each member, one engine that goes through its datasets in order: the boot prompts (``generate``), the benchmarks (``accuracy_core``) and a speculator's acceptance. The tree runs it, not the flow: per target the flow writes two files into the tree (:func:`write_generated`), and commits them at the start of the run:: tests/integration/defs/accuracy/modeling_v2/// test_e2e.py a fixed thin test (:func:`render_test`) e2e_cases.yaml one case per check of a test of datasets (:func:`build_cases`) ``tests/integration/defs/accuracy/modeling_v2/_e2e.py`` loads the cases and runs one (``load_cases``, ``run_case``). CI runs the same file from a test list, judged by the references rows alone. A check of the run runs its case's node (:func:`node_id`) through ``checks/pytest_node.py``, with :data:`RESULTS_ENV` naming a file the runner writes one JSON line per dataset to, and :data:`REFERENCES_ENV` giving a dataset the score it is judged against where the flow judges against a measured anchor (a placeholder row's first score, a variant's unit's score). A case is the configuration the flow builds for the feature at the member (``check_config.check_configuration``: core's settings, the features built up to it, a variant's overlay, the member's parallelism) with ``modeling_v2: require``. A path under the models root is written as ``${LLM_MODELS_ROOT}/...``, so CI finds the checkpoint under its own root. """ from __future__ import annotations import json import os import re import subprocess from dataclasses import replace from pathlib import Path from typing import Any, Iterable, Mapping, Sequence import yaml from ..infra.compute.environment import RunEnvironment from ..spec.task_schema import parse_parallel_segment from ..spec.verification import ( BENCHMARKS, DATASET_ACCEPTANCE, DATASET_GENERATE, Test, extra_check_function, ) from . import acceptance as acceptance_checks from . import check_config, pytest_node from .boot import chunk_probe_tokens, resolve_boot_spec from .check_runtime import MODE_REQUIRE, ShellRunner, default_shell_runner, gate_workdir from .harness import workload_io from .verdict import GateResult #: The tree's modeling_v2 accuracy tests, and its runner of the generated tests. ACCURACY_ROOT = "tests/integration/defs/accuracy/modeling_v2" RUNNER_MODULE = f"{ACCURACY_ROOT}/_e2e.py" #: The ``accuracy_core`` references, one file per dataset. REFERENCES_DIR = "tests/integration/defs/accuracy/references" TEST_FILENAME = "test_e2e.py" #: Extra checks (``spec/verification.py``): the shared ones beside the runner, and a #: target's own beside its generated test. SHARED_EXTRA_CHECKS = f"{ACCURACY_ROOT}/_extra_checks.py" TARGET_EXTRA_CHECKS = "extra_checks.py" CASES_FILENAME = "e2e_cases.yaml" CASES_VERSION = 1 #: The file the runner appends one JSON line per dataset to. RESULTS_ENV = "MV2_E2E_RESULTS" #: A JSON object ``{dataset: score}``: the score a benchmark is judged against instead of its row. REFERENCES_ENV = "MV2_E2E_REFERENCES" #: Comma-separated dataset names: a debugging run's subset of the case (``gate --datasets``). DATASETS_ENV = "MV2_E2E_DATASETS" MODELS_ROOT_ENV = "LLM_MODELS_ROOT" #: How a case names a path under the models root. MODELS_ROOT_PREFIX = "${LLM_MODELS_ROOT}" #: Where the tree's tests read a benchmark's dataset under the models root. DATASET_DIRS: dict[str, str] = {"gsm8k": "datasets/openai/gsm8k"} #: The message of the flow's own commit of the generated files. COMMIT_SUBJECT = "[None][test] {target}: the e2e test the trtllm_modeling_v2 run generated" _TEST_TEMPLATE = '''# SPDX-FileCopyrightText: Copyright (c) {year} NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """Whole-model tests of the modeling_v2 target {target}. Generated by the trtllm_modeling_v2 agent flow from its spec (`verification`), with e2e_cases.yaml beside it: change the spec and regenerate, do not edit either file. """ import pytest from ....accuracy_core import LlmapiAccuracyTestHarness from ..._e2e import load_cases, run_case class TestModelingV2{cls}(LlmapiAccuracyTestHarness): @pytest.mark.parametrize("case", load_cases(__file__)) def test_e2e(self, case): run_case(case) ''' #: The year the generated files' copyright header carries. COPYRIGHT_YEAR = 2026 def target_dir(family: str, target: str) -> str: """Where the target's accuracy tests live, relative to the repository.""" return f"{ACCURACY_ROOT}/{family}/{Path(target).name}" def generated_paths(family: str, target: str) -> tuple[str, str]: """The generated test and its cases, relative to the repository.""" where = target_dir(family, target) return f"{where}/{TEST_FILENAME}", f"{where}/{CASES_FILENAME}" def extra_check_files(family: str, target: str) -> tuple[str, str]: """Where a test's extra checks are looked up, in order: the target's own file, then the shared one.""" return f"{target_dir(family, target)}/{TARGET_EXTRA_CHECKS}", SHARED_EXTRA_CHECKS def resolve_extra_checks( repo: str | Path, family: str, target: str, names: Iterable[str] ) -> tuple[dict[str, str], list[str]]: """Each of ``names`` to where it is defined (``::``), and what could not be. Looked up in :func:`extra_check_files`; read from the source, nothing imported. """ files = extra_check_files(family, target) found: dict[str, str] = {} problems: list[str] = [] for name in names: node, said = extra_check_function(repo, files, name) if node is None: problems.append(said) else: found[name] = node return found, problems def class_name(target: str) -> str: """``TestModelingV2``'s name: the target directory in CamelCase (``glm_5_2__tp8`` -> ``Glm52Tp8``).""" return "".join( part[:1].upper() + part[1:] for part in re.split(r"_+", Path(target).name) if part ) def render_test(target: str) -> str: """The generated ``test_e2e.py`` of ``target``.""" name = Path(target).name return _TEST_TEMPLATE.format(year=COPYRIGHT_YEAR, target=name, cls=class_name(name)) def case_id(feature: str, test: str, member: str) -> str: """A case's id, its pytest id: ``--``.""" return f"{feature}-{test}-{member}" def node_id(family: str, target: str, feature: str, test: str, member: str) -> str: """The pytest node of one case, relative to the repository.""" path, _ = generated_paths(family, target) return f"{path}::TestModelingV2{class_name(target)}::test_e2e[{case_id(feature, test, member)}]" # ------------------------------------------------------------------------ cases def models_root(task_data: Mapping[str, Any]) -> str: """The models root the spec's environment names; ``""`` when it names none.""" environment = task_data.get("environment") or {} env = environment.get("env") if isinstance(environment, Mapping) else None root = (env or {}).get(MODELS_ROOT_ENV) if isinstance(env, Mapping) else None return str(root or "").rstrip("/") def portable(value: Any, root: str) -> Any: """``value`` with every string path under ``root`` written as ``${LLM_MODELS_ROOT}/...``.""" if isinstance(value, Mapping): return {str(k): portable(v, root) for k, v in value.items()} if isinstance(value, (list, tuple)): return [portable(v, root) for v in value] if root and isinstance(value, str) and (value == root or value.startswith(root + "/")): return MODELS_ROOT_PREFIX + value[len(root) :] return value def _generate(spec: Mapping[str, Any], config: Mapping[str, Any], feature: str, features) -> dict: """The ``generate`` dataset: the boot prompts, a prompt the engine must split, the reuse probe.""" boot = resolve_boot_spec(spec, feature, features) prompts: list[Any] = list(boot.prompts) for item in boot.items: prompt: dict[str, Any] = {"prompt": item.prompt} if item.images: prompt.update(images=list(item.images), render=item.render) prompts.append(prompt) limits = check_config.EngineLimits.from_config(config) chunk = None if check_config.sets_chunking(spec, feature) and limits.chunked_prefill: chunk = chunk_probe_tokens(limits.max_num_tokens, limits.max_seq_len) if chunk is None: raise ValueError( f"{feature} is about chunked prefill, and its engine's limits (max_num_tokens " f"{limits.max_num_tokens}, max_seq_len {limits.max_seq_len}) leave no room " "for a prompt the engine would have to split" ) kv = config["llm"].get("kv_cache_config") or {} return { "name": DATASET_GENERATE, "kind": "generate", "prompts": prompts, "max_tokens": boot.max_tokens, "apply_chat_template": bool(config.get("apply_chat_template")), "chunk_probe_tokens": chunk, "reuse_probe": bool(kv.get("enable_block_reuse")), } def _benchmark(spec: Mapping[str, Any], name: str, test: Test) -> dict: """A benchmark dataset: its ``accuracy_core`` task, under the spec's protocol as ``test`` changes it.""" kwargs = dict((spec.get("accuracy") or {}).get("evaluator_kwargs") or {}) kwargs.update(test.evaluator_kwargs or {}) dataset = { "name": name, "kind": "benchmark", "task": BENCHMARKS[name], "extra_acc_spec": None, "evaluator_kwargs": kwargs, } return dataset def _acceptance( spec: Mapping[str, Any], config: Mapping[str, Any], feature: str, features, root: str ) -> dict: accuracy = spec.get("accuracy") or {} workload = acceptance_checks.resolve_acceptance_workload(accuracy, feature) floor = acceptance_checks.resolve_acceptance_floor_spec(accuracy, feature, features) load: dict[str, Any] = { "max_tokens": workload.max_tokens, "apply_chat_template": bool(config.get("apply_chat_template")), } if workload.prompts: load["prompts"] = list(workload.prompts) else: dataset = dict(workload.dataset or {}) known = { name: f"{MODELS_ROOT_PREFIX}/{where}" for name, where in DATASET_DIRS.items() if root and workload_io.KNOWN_DATASETS.get(name, {}).get("source") == dataset["source"] } if known: dataset["source"] = next(iter(known.values())) load["dataset"] = dataset return { "name": DATASET_ACCEPTANCE, "kind": "acceptance", "workload": load, "min_draft_iterations": workload.min_draft_iterations, "floor": None if floor is None else round(floor.value, 6), "floor_source": "" if floor is None else str(floor.source or ""), } def build_case( environment: RunEnvironment, spec: Mapping[str, Any], test: Test, member: str, features: Sequence[str], extra_checks: Mapping[str, str] | None = None, ) -> dict[str, Any]: """The case of ``test`` at ``member``: its engine's options and its datasets, in order. ``spec`` is the one ``test``'s feature runs under (a variant's with its overlay), and ``features`` those its target implements. The test's own ``config`` is laid over the engine's options last. ``extra_checks`` gives where each of the test's extra checks is defined (:func:`resolve_extra_checks`). """ feature = test.feature config = check_config.check_configuration( spec, environment, unit=feature, features=features, max_tokens=32, member=member ) accuracy = spec.get("accuracy") or {} llm = dict(config["llm"]) llm.pop("model", None) llm["modeling_v2"] = MODE_REQUIRE for key in ("max_seq_len", "max_batch_size"): if accuracy.get(key) is not None: llm[key] = accuracy[key] if accuracy.get("max_batch_size") is not None: # A benchmark's batch is a global total too: each attention-DP rank serves its share. check_config.share_batch(llm, member, llm.get("tensor_parallel_size")) if test.config: # The test's own options are the engine's last word, and its probes' limits. llm = check_config.merge_options(llm, test.config) config = {**config, "llm": check_config.merge_options(config["llm"], test.config)} sampling = {k: v for k, v in config["sampling"].items() if k != "max_tokens"} root = models_root(spec) datasets: list[dict[str, Any]] = [] for name in test.datasets: if name == DATASET_GENERATE: datasets.append(_generate(spec, config, feature, features)) elif name == DATASET_ACCEPTANCE: datasets.append(_acceptance(spec, config, feature, features, root)) else: datasets.append(_benchmark(spec, name, test)) _, size = parse_parallel_segment(member) case = { "id": case_id(feature, test.name, member), "feature": feature, "test": test.name, "member": member, "devices": int(size or environment.world_size or 1), "llm": portable(llm, root), "sampling": sampling, "datasets": portable(datasets, root), } if test.extra_checks: where = dict(extra_checks or {}) unfound = [name for name in test.extra_checks if name not in where] if unfound: raise ValueError( f"{test.feature}.{test.name}: extra check(s) {unfound} were not looked up in the tree" ) case["extra_checks"] = [{"check": where[name]} for name in test.extra_checks] return case def build_cases( task_data: Mapping[str, Any], model_name: str, cases: Iterable[Mapping[str, Any]], ) -> dict[str, Any]: """The whole ``e2e_cases.yaml``: the model, and ``cases`` in order.""" root = models_root(task_data) return { "version": CASES_VERSION, "model_name": model_name, "model_dir": portable(str(task_data["checkpoint_path"]).rstrip("/"), root), "cases": [dict(c) for c in cases], } def render_cases(document: Mapping[str, Any]) -> str: """``e2e_cases.yaml``'s text.""" header = ( "# Generated by the trtllm_modeling_v2 agent flow from its spec (`verification`): " "change the spec,\n# not this file. Read by test_e2e.py beside it " "(tests/integration/defs/accuracy/modeling_v2/_e2e.py).\n" ) return header + yaml.safe_dump(dict(document), sort_keys=False, width=100) def write_generated( repo: str | Path, family: str, target: str, document: Mapping[str, Any] ) -> list[str]: """Write the target's generated test and cases into ``repo``; the paths that changed. The target's test directory gets an empty ``__init__.py`` when it has none. """ root = Path(repo) test_path, cases_path = generated_paths(family, target) wanted = {test_path: render_test(target), cases_path: render_cases(document)} package = f"{target_dir(family, target)}/__init__.py" if not (root / package).is_file(): wanted[package] = "" family_package = f"{ACCURACY_ROOT}/{family}/__init__.py" if not (root / family_package).is_file(): wanted[family_package] = "" changed: list[str] = [] for rel, text in wanted.items(): path = root / rel if path.is_file() and path.read_text(encoding="utf-8") == text: continue path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") changed.append(rel) return changed def commit_generated( repo: str | Path, paths: Sequence[str], target: str, identity_env: Mapping[str, str] ) -> str: """Commit ``paths`` alone in ``repo``, signed off as the run's identity; the commit, ``""`` if none.""" if not paths: return "" env = {**os.environ, **identity_env} def git(*args: str) -> subprocess.CompletedProcess: return subprocess.run( ["git", "-C", str(repo), *args], capture_output=True, text=True, env=env, check=False ) added = git("add", "--", *paths) if added.returncode != 0: raise RuntimeError(f"git add of the generated tests failed: {added.stderr.strip()}") staged = git("diff", "--cached", "--quiet", "--", *paths) if staged.returncode == 0: return "" message = COMMIT_SUBJECT.format(target=Path(target).name) + ( "\n\nThe test and its cases are generated from the run's spec; the run's agents do not " "edit them." ) done = git("commit", "-q", "-s", "-m", message, "--", *paths) if done.returncode != 0: raise RuntimeError(f"committing the generated tests failed: {done.stderr.strip()}") head = git("rev-parse", "HEAD") return head.stdout.strip() # ------------------------------------------------------------------------ a run def read_results(path: Path) -> list[dict[str, Any]]: """The runner's lines in ``path``, one per dataset run; ``[]`` when it wrote none.""" try: text = Path(path).read_text(encoding="utf-8") except OSError: return [] out = [] for line in text.splitlines(): try: data = json.loads(line) except ValueError: continue if isinstance(data, dict): out.append(data) return out def describe(line: Mapping[str, Any]) -> str: """One dataset's or extra check's line, as a verdict says it; a check that passed says what it saw.""" name = str(line.get("dataset") or "?") verdict = "passed" if line.get("passed") else "FAILED" score = line.get("score") said = f"{name} {verdict}" if isinstance(score, (int, float)): said += f" ({score:.4g}" threshold = line.get("threshold") if isinstance(threshold, (int, float)): said += f" vs threshold {threshold:.4g}" reference = line.get("reference") if isinstance(reference, (int, float)): said += f", reference {reference:.4g}" said += ")" detail = str(line.get("detail") or "").strip() if detail and (not line.get("passed") or line.get("kind") == "extra_check"): said += f": {detail[:300]}" return said def run_e2e( environment: RunEnvironment, *, task_data: Mapping[str, Any], test: Test, member: str, node: str, workdir: str | Path, runner: ShellRunner = default_shell_runner, references: Mapping[str, float] | None = None, env: Mapping[str, str] | None = None, datasets: Sequence[str] = (), ) -> tuple[GateResult, list[dict[str, Any]]]: """Run ``test``'s case at ``member`` (``node``) and judge it; the verdict and the runner's lines. The verdict is the node's (``pytest_node.run_node``), with each dataset's line in its detail and the first benchmark's score as ``measured``. ``references`` judges a benchmark against a score instead of its row. ``datasets`` runs only those of the case: a debugging run, never a check's. """ token = pytest_node.run_token() results = ( gate_workdir(workdir) / f"e2e.{test.feature}.{test.name}.{member}.{token}.results.jsonl" ) variables = { **(test.env or {}), **(env or {}), RESULTS_ENV: str(results), "HF_DATASETS_OFFLINE": "1", "HF_HUB_OFFLINE": "1", } if datasets: variables[DATASETS_ENV] = ",".join(datasets) if references: variables[REFERENCES_ENV] = json.dumps( {k: float(v) for k, v in references.items()}, sort_keys=True ) result = pytest_node.run_node( environment, name=test.name, node=node, task_data=task_data, workdir=workdir, timeout=test.timeout, runner=runner, env=variables, unit=test.feature, member=member, what="the e2e test", # Every process's record of where it imported the package under test reaches the # command's output, as the engine's own prints do. capture=False, token=token, ) lines = read_results(results) if not lines: return result, lines measured = next( ( float(line["score"]) for name in test.benchmarks for line in lines if line.get("dataset") == name and isinstance(line.get("score"), (int, float)) ), None, ) first = next( ( line for name in test.benchmarks for line in lines if line.get("dataset") == name and isinstance(line.get("score"), (int, float)) ), {}, ) reference, threshold = first.get("reference"), first.get("threshold") detail = "; ".join(describe(line) for line in lines) ran = [d for d in (*test.datasets, *test.extra_checks) if not datasets or d in datasets] missing = [d for d in ran if d not in {line.get("dataset") for line in lines}] if missing: detail += f"; no result for {', '.join(missing)} ({result.detail})" return ( replace( result, detail=detail, measured=measured, reference=float(reference) if isinstance(reference, (int, float)) else None, floor=float(threshold) if isinstance(threshold, (int, float)) else None, floor_rule="accuracy_core hypothesis test" if threshold is not None else "", explained=True, ), lines, ) def scores(lines: Iterable[Mapping[str, Any]]) -> dict[str, float]: """Each benchmark's score in the runner's lines, by dataset.""" return { str(line["dataset"]): float(line["score"]) for line in lines if line.get("kind") == "benchmark" and isinstance(line.get("score"), (int, float)) } __all__ = [ "ACCURACY_ROOT", "CASES_FILENAME", "CASES_VERSION", "COMMIT_SUBJECT", "DATASETS_ENV", "MODELS_ROOT_PREFIX", "REFERENCES_DIR", "REFERENCES_ENV", "RESULTS_ENV", "RUNNER_MODULE", "SHARED_EXTRA_CHECKS", "TARGET_EXTRA_CHECKS", "TEST_FILENAME", "build_case", "extra_check_files", "build_cases", "case_id", "class_name", "commit_generated", "describe", "generated_paths", "models_root", "node_id", "portable", "read_results", "resolve_extra_checks", "render_cases", "render_test", "run_e2e", "scores", "target_dir", "write_generated", ]