diff --git a/tests/accept/atomesh_mm/accept.sh b/tests/accept/atomesh_mm/accept.sh new file mode 100644 index 00000000000..76608c633ad --- /dev/null +++ b/tests/accept/atomesh_mm/accept.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# Acceptance harness for ATOMesh multimodal requests. +# +# bash tests/accept/atomesh_mm/accept.sh +# +# Sources models/.env (image, model, nodes and GPUs per role, server +# arguments) and then checks/.env when the check has one (what the +# check needs changed in the profile), brings the deployment up with +# topologies/.sh, runs checks/.py (dashes read as +# underscores) in a client container against it, and removes its containers +# at exit. stdout carries one JSON line and then PASS or FAIL ; the +# JSON is also kept as $ACCEPT_DIR/results///.json, +# where later checks read their references, beside the run's logs. +set -euo pipefail + +if (($# != 3)); then + echo "usage: $0 " >&2 + exit 2 +fi +MODEL=$1 TOPOLOGY=$2 CHECK=$3 +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +ROOT=$(cd "$HERE/../../.." && pwd) +ACCEPT_ISSUE=${ACCEPT_ISSUE:-2} +CHECK_PY=$HERE/checks/${CHECK//-/_}.py + +report() { # report : the JSON line and FAIL for a run that ended before its check + python3 -c 'import json, sys; print(json.dumps(dict(zip(["model", "topology", "check", "reason"], sys.argv[1:]), passed=False)))' \ + "$MODEL" "$TOPOLOGY" "$CHECK" "$1" + echo "FAIL $1" +} + +for f in "$HERE/models/$MODEL.env" "$HERE/topologies/$TOPOLOGY.sh" "$CHECK_PY"; do + [[ -f $f ]] || { report "no such file: ${f#"$HERE"/}"; exit 1; } +done + +source "$HERE/models/$MODEL.env" +CHECK_ENV=${CHECK_PY%.py}.env +[[ ! -f $CHECK_ENV ]] || source "$CHECK_ENV" +source "$HERE/lib.sh" +REF_TOPOLOGY="" +source "$HERE/topologies/$TOPOLOGY.sh" +# A check that reads ATOMesh's log (REQUIRES_MESH in checks/.env) +# cannot run on a topology that starts no ATOMesh. +if [[ -n ${REQUIRES_MESH:-} ]] && ! declare -f topology_up | grep -q launch_mesh; then + report "$CHECK needs ATOMesh, which topology $TOPOLOGY does not run" + exit 1 +fi + +RESULTS_DIR=$ACCEPT_DIR/results +RUN_DIR=$RESULTS_DIR/$MODEL/$TOPOLOGY/$CHECK.$(date +%Y%m%d-%H%M%S) +mkdir -p "$RUN_DIR" +log "run directory $RUN_DIR" + +# A failing step exits through set -e; the check reports for itself. +STAGE="$TOPOLOGY deployment" +on_exit() { + local status=$? + ((status == 0)) || [[ -z $STAGE ]] || report "$STAGE failed; logs in $RUN_DIR" + cleanup_containers +} +trap on_exit EXIT + +topology_up +STAGE="client container" +start_client +STAGE="" +in_role client \ + -e "ACCEPT_MODEL=$MODEL" -e "ACCEPT_TOPOLOGY=$TOPOLOGY" -e "ACCEPT_CHECK=$CHECK" \ + -e "ENDPOINT=$ENDPOINT" -e "SERVED_MODEL=$SERVED_MODEL" -e "RUN_DIR=$RUN_DIR" \ + -e "RESULTS_DIR=$RESULTS_DIR" -e "REF_TOPOLOGY=$REF_TOPOLOGY" -e "LIMIT=${LIMIT:-}" \ + -e "MMSTAR_THRESHOLD=${MMSTAR_THRESHOLD:-}" \ + -e "MMMU_PRO_REF_STANDARD=${MMMU_PRO_REF_STANDARD:-}" -e "MMMU_PRO_REF_VISION=${MMMU_PRO_REF_VISION:-}" \ + -- python3 "$CHECK_PY" diff --git a/tests/accept/atomesh_mm/checks/_common.py b/tests/accept/atomesh_mm/checks/_common.py new file mode 100644 index 00000000000..6e4c070d27b --- /dev/null +++ b/tests/accept/atomesh_mm/checks/_common.py @@ -0,0 +1,152 @@ +"""Helpers the lmms-eval checks share: the environment accept.sh passes, the +lmms-eval run, the reference topology's result and the verdict. Run in the +client container, imported by checks/.py from this directory. +""" + +import json +import math +import os +import subprocess +import sys +import traceback +from pathlib import Path + +# The text lmms-eval's OpenAI client answers with once a request has failed. +FAILED_MARK = "[LMMS_EVAL_REQUEST_FAILED" + + +def env(name): + return os.environ[name] + + +def stderr(score, n): + """Standard error of an accuracy over n questions.""" + return math.sqrt(score * (1 - score) / n) + + +# lmms-eval's OpenAI client builds its SDK client with the SDK's 600 s timeout +# and two silent retries, and sends no sampling parameter but the +# temperature. Run it with a client that waits as long as ATOMesh does, never +# retries, and adds the check's extra request fields. +LMMS_EVAL_MAIN = """ +import json, sys +import openai +import lmms_eval.models.simple.openai as backend +extra = json.loads(sys.argv.pop(1)) + +def client(*args, **kwargs): + sdk = openai.OpenAI(*args, timeout=14400, max_retries=0, **kwargs) + create = sdk.chat.completions.create + sdk.chat.completions.create = lambda **body: create(**extra, **body) + return sdk + +backend.OpenAI = client +from lmms_eval.__main__ import cli_evaluate +cli_evaluate() +""" + + +def run_lmms_eval(name, tasks, gen_kwargs, concurrency, include_path=None, extra=None): + """Run lmms-eval on tasks against ENDPOINT, one attempt per request, with + extra (a dict) added to every request body. + + Returns lmms-eval's results per task and, per task, its sample lines. + """ + out = Path(env("RUN_DIR")) / name + model_args = ( + f"model={env('SERVED_MODEL')},base_url={env('ENDPOINT')}/v1,api_key=EMPTY," + f"max_retries=1,num_concurrent={concurrency},max_size_in_mb=50" + ) + args = [ + sys.executable, + "-c", + LMMS_EVAL_MAIN, + json.dumps(extra or {}), + "--model", + "openai", + "--model_args", + model_args, + "--tasks", + ",".join(tasks), + "--batch_size", + "1", + "--process_with_media", + "--gen_kwargs", + gen_kwargs, + "--log_samples", + "--output_path", + str(out), + ] + if include_path: + args += ["--include_path", str(include_path)] + limit = os.environ.get("LIMIT") + if limit: + args += ["--limit", limit] + with open(f"{out}.log", "w") as log: + subprocess.run(args, stdout=log, stderr=subprocess.STDOUT, check=True) + results = json.loads(max(out.rglob("*_results.json")).read_text())["results"] + samples = { + task: max(out.rglob(f"*_samples_{task}.jsonl")).read_text().splitlines() + for task in tasks + } + return results, samples + + +def within(score, ref_score, ref_stderr): + """Whether score is within 2 x the reference's standard error of the + reference's score. The tolerance comes from the reference, so a worse run + under test does not widen it.""" + return abs(score - ref_score) <= 2 * ref_stderr + + +def failed_requests(lines): + return sum(FAILED_MARK in line for line in lines) + + +def reference(): + """The reference topology's recorded result for this model and check.""" + path = Path(env("RESULTS_DIR"), env("ACCEPT_MODEL"), env("REF_TOPOLOGY")) + path = path / f"{env('ACCEPT_CHECK')}.json" + if not path.exists(): + raise RuntimeError(f"no reference at {path}") + ref = json.loads(path.read_text()) + if not ref["passed"]: + raise RuntimeError(f"reference {path} did not pass") + return ref + + +def finish(result, failures): + """Record the result, print its JSON line and PASS or FAIL, and exit.""" + result = { + "model": env("ACCEPT_MODEL"), + "topology": env("ACCEPT_TOPOLOGY"), + "check": env("ACCEPT_CHECK"), + "passed": not failures, + "reason": "; ".join(failures), + **result, + "run_dir": env("RUN_DIR"), + } + line = json.dumps(result) + Path(env("RUN_DIR"), "result.json").write_text(line + "\n") + if not os.environ.get("LIMIT"): + Path(env("RESULTS_DIR"), result["model"], result["topology"]).mkdir( + parents=True, exist_ok=True + ) + Path( + env("RESULTS_DIR"), + result["model"], + result["topology"], + f"{result['check']}.json", + ).write_text(line + "\n") + print(line) + print("PASS" if not failures else f"FAIL {result['reason']}") + sys.exit(0 if not failures else 1) + + +def run_check(check): + """Run check(), reporting an exception as a FAIL.""" + try: + check() + except Exception as exc: # noqa: BLE001 - any error is a FAIL + traceback.print_exc() + finish({}, [f"{type(exc).__name__}: {exc}"]) diff --git a/tests/accept/atomesh_mm/checks/distinct.env b/tests/accept/atomesh_mm/checks/distinct.env new file mode 100644 index 00000000000..9fac2f61430 --- /dev/null +++ b/tests/accept/atomesh_mm/checks/distinct.env @@ -0,0 +1,8 @@ +# The distinction check needs the engine's prefix cache, which the profile +# may turn off; the last occurrence of the flag wins. +ATOM_ARGS+=(--enable_prefix_caching) +# It reads ATOMesh's route log, so accept.sh refuses a topology without +# ATOMesh (direct). +REQUIRES_MESH=1 +# Every request logs its routing decision (target mesh::route). +MESH_ARGS+=(--route-log-sample-rate 1) diff --git a/tests/accept/atomesh_mm/checks/distinct.py b/tests/accept/atomesh_mm/checks/distinct.py new file mode 100644 index 00000000000..d1a96d334de --- /dev/null +++ b/tests/accept/atomesh_mm/checks/distinct.py @@ -0,0 +1,159 @@ +"""Red/blue image distinction through ATOMesh: one text, sent once with a red +and once with a blue image, one request after the other, with the engine's +prefix cache on and every routing decision logged (checks/distinct.env). + +Passes when each answer names its own color and not the other, and ATOMesh's +log ($RUN_DIR/mesh.log) holds one `Selected worker` event (target +`mesh::route`) per request, each with `media_count=1`, the blue one with a +`match_ratio` below 1. A media request routes on cache_aware's prefix tree, +which by then holds the red request's routing key: a blue key equal to it +would match whole. With the text shared, only the images' media digests can +tell the two keys apart, and only the images' cache_seed keeps the second +request off the first one's cached KV. + +Needs ROCm/ATOM#3407, which puts `media_count` on the route log and keys a +media chat's route by its images; on main the blue request's key equals the +red one's and the check fails. +""" + +import json +import re +import struct +import time +import urllib.request +import zlib +from base64 import b64encode +from pathlib import Path + +from _common import env, finish, run_check + +COLORS = {"red": (255, 0, 0), "blue": (0, 0, 255)} +SIDE = 448 # large enough that the image's tokens fill whole KV blocks +PROMPT = "What color is this image? Answer with one word." +EVENT_WAIT_S = 30 + +ANSI = re.compile(r"\x1b\[[0-9;]*m") +FIELD = re.compile(r"(\w+)=(\"[^\"]*\"|\S+)") + + +def png(rgb, side=SIDE): + """A solid side x side RGB PNG.""" + + def chunk(kind, data): + body = kind + data + return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) + + row = b"\x00" + bytes(rgb) * side + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", side, side, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(row * side)) + + chunk(b"IEND", b"") + ) + + +def image_url(color): + return "data:image/png;base64," + b64encode(png(COLORS[color])).decode() + + +def ask(color): + """The answer (content, without reasoning) to the prompt with color's image.""" + body = { + "model": env("SERVED_MODEL"), + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": PROMPT}, + {"type": "image_url", "image_url": {"url": image_url(color)}}, + ], + } + ], + "temperature": 0, + "max_tokens": 8192, + } + request = urllib.request.Request( + env("ENDPOINT") + "/v1/chat/completions", + data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=1800) as response: + reply = json.loads(response.read()) + return reply["choices"][0]["message"]["content"] or "" + + +def decision_events(log): + """The `Selected worker` events in a router log, as dicts of the event's + own fields (not its span's).""" + events = [] + for line in log.splitlines(): + _, mark, fields = ANSI.sub("", line).partition("Selected worker") + if mark: + events.append({k: v.strip('"') for k, v in FIELD.findall(fields)}) + return events + + +def read_log(path): + return path.read_text(errors="replace") if path.exists() else "" + + +def new_events(path, seen): + """The decision events after the first seen, waiting for at least one.""" + deadline = time.monotonic() + EVENT_WAIT_S + while True: + events = decision_events(read_log(path))[seen:] + if events or time.monotonic() > deadline: + return events + time.sleep(1) + + +def names(answer, color): + return re.search(rf"\b{color}\b", answer, re.IGNORECASE) is not None + + +def main(): + log = Path(env("RUN_DIR"), "mesh.log") + seen = len(decision_events(read_log(log))) + result, failures = {}, [] + for color in COLORS: + answer = ask(color) + events = new_events(log, seen) + seen += len(events) + event = events[0] if len(events) == 1 else {} + result[color] = { + "answer": answer, + "branch": event.get("branch"), + "match_ratio": event.get("match_ratio"), + "media_count": event.get("media_count"), + "events": events, + } + other = next(c for c in COLORS if c != color) + if not names(answer, color) or names(answer, other): + failures.append( + f"the {color} image's answer {answer!r} does not name {color} alone" + ) + if len(events) != 1: + failures.append( + f"{len(events)} Selected worker events in {log} for the {color} request" + ) + elif event.get("media_count") != "1": + failures.append( + f"the {color} request routed with media_count " + f"{event.get('media_count')}, not 1" + ) + blue = result["blue"] + if len(blue["events"]) == 1: + if blue["match_ratio"] is None: + failures.append( + f"the blue request's route ({blue['branch']}) logged no match_ratio" + ) + elif float(blue["match_ratio"]) >= 1: + failures.append( + "the blue request matched the red one's routing key whole " + f"(match_ratio {blue['match_ratio']})" + ) + finish(result, failures) + + +if __name__ == "__main__": + run_check(main) diff --git a/tests/accept/atomesh_mm/checks/mmmu_pro.py b/tests/accept/atomesh_mm/checks/mmmu_pro.py new file mode 100644 index 00000000000..f444b847d14 --- /dev/null +++ b/tests/accept/atomesh_mm/checks/mmmu_pro.py @@ -0,0 +1,144 @@ +"""MMMU-Pro standard (10 options) and vision against the deployment under +test, with the recipe's sampling (temperature 1.0, top-p 0.95, up to 65,536 +new tokens), by lmms-eval. + +lmms-eval's vision task sends the image with an empty text; this check sends +MMMU-Pro's own vision prompt (direct setting) instead, which asks for a last +line "Answer: X". A vision answer is the letter of the last such line, or, +when there is none, the option letter lmms-eval's multiple-choice extractor +finds in the response; a standard answer is the extractor's letter. lmms-eval's +own vision scorer compares the whole response to the letter. +Passes when no request failed and each subset's score is within 2 x the +reference's standard error of the reference's score. On a topology with a +reference topology the reference is that topology's recorded run; otherwise +(direct) it is the model profile's recipe score (MMMU_PRO_REF_STANDARD, +MMMU_PRO_REF_VISION), with the standard error of that score over this run's +questions. +""" + +import json +import re +import shutil +from pathlib import Path + +from _common import ( + env, + failed_requests, + finish, + reference, + run_check, + run_lmms_eval, + stderr, + within, +) + +SUBSETS = { + "standard": "mmmu_pro_standard", + "vision": "mmmu_pro_vision_prompt", +} +LETTERS = list("ABCDEFGHIJ") + +# MMMU-Pro's vision prompt, direct setting (MMMU-Benchmark/MMMU, +# mmmu-pro/prompts.yaml). +VISION_PROMPT = ( + "Answer with the option letter from the given choices directly. The last " + "line of your response should be of the following format: 'Answer: $LETTER' " + "(without quotes) where LETTER is one of options." +) +# A whole line "Answer: X", markdown emphasis and parentheses allowed, so that +# "Answer: I think it is (C)" is not read as option I. +ANSWER_LINE = re.compile(r"^\W*Answer:\s*\(?([A-J])\)?\W*$", re.MULTILINE) + + +def vision_task_dir(): + """lmms-eval's mmmu_pro_vision, renamed, with MMMU-Pro's vision prompt as + its text.""" + import lmms_eval + + src = Path(lmms_eval.__file__).parent / "tasks" / "mmmu_pro" + dst = Path(env("RUN_DIR"), "tasks", "mmmu_pro_vision_prompt") + dst.mkdir(parents=True) + shutil.copy(src / "_default_template_yaml", dst) + utils = (src / "utils.py").read_text() + utils += ( + "\n\ndef vision_prompt(doc, lmms_eval_specific_kwargs=None):\n" + f" return {VISION_PROMPT!r}\n" + ) + (dst / "utils.py").write_text(utils) + task = (src / "mmmu_pro_vision.yaml").read_text() + task = re.sub(r"tag:\n( - .*\n)+", "", task) + task = task.replace('task: "mmmu_pro_vision"', 'task: "mmmu_pro_vision_prompt"') + task = task.replace("utils.mmmu_pro_doc_to_text", "utils.vision_prompt") + (dst / "mmmu_pro_vision_prompt.yaml").write_text(task) + return dst.parent + + +def extracted_letter(response): + from lmms_eval.tasks._task_utils.mcq_extract import extract_mcq_answer + + return extract_mcq_answer(response, LETTERS) + + +def answer_line_letter(response): + found = ANSWER_LINE.findall(response) + return found[-1] if found else extracted_letter(response) + + +def accuracy(lines, letter): + samples = [json.loads(line) for line in lines] + correct = 0 + for sample in samples: + response = sample["filtered_resps"] + if isinstance(response, list): + response = response[0] + correct += letter(response) == sample["target"] + return correct / len(samples) + + +SCORERS = {"standard": extracted_letter, "vision": answer_line_letter} + + +def subset_reference(ref, subset, n): + """The reference score and standard error for a subset: the reference + topology's recorded run when there is one, else the recipe's score.""" + if ref: + return ref[subset]["score"], ref[subset]["stderr"], ref["topology"] + score = float(env(f"MMMU_PRO_REF_{subset.upper()}")) + return score, stderr(score, n), "recipe" + + +def main(): + ref = reference() if env("REF_TOPOLOGY") else None + _, samples = run_lmms_eval( + "mmmu_pro", + list(SUBSETS.values()), + "temperature=1.0,max_new_tokens=65536", + 64, + vision_task_dir(), + extra={"top_p": 0.95}, + ) + result, failures = {}, [] + for subset, task in SUBSETS.items(): + n = len(samples[task]) + score = accuracy(samples[task], SCORERS[subset]) + ref_score, ref_stderr, source = subset_reference(ref, subset, n) + failed = failed_requests(samples[task]) + result[subset] = { + "score": score, + "stderr": stderr(score, n), + "n": n, + "failed_requests": failed, + "reference": {"source": source, "score": ref_score, "stderr": ref_stderr}, + } + if failed: + failures.append(f"{subset}: {failed} failed requests") + if not within(score, ref_score, ref_stderr): + failures.append( + f"{subset} {score:.4f} is not within {2 * ref_stderr:.4f} of " + f"{source}'s {ref_score:.4f}" + ) + finish(result, failures) + + +if __name__ == "__main__": + run_check(main) diff --git a/tests/accept/atomesh_mm/checks/mmstar.py b/tests/accept/atomesh_mm/checks/mmstar.py new file mode 100644 index 00000000000..3fe7b83e233 --- /dev/null +++ b/tests/accept/atomesh_mm/checks/mmstar.py @@ -0,0 +1,90 @@ +"""MMStar against the deployment under test, run by lmms-eval as +.github/scripts/atom_mmstar_ci.sh runs it. + +Passes when no request failed, the score is at least the model profile's +MMSTAR_THRESHOLD (as .github/scripts/atom_mmstar_ci.sh gates it), and, on a +topology with a reference topology, the score is within 2 x the reference's +standard error of the reference's score. The floor keeps a broken direct run +from passing and becoming the other topologies' reference; a LIMIT run, which +is never recorded as a reference and scores only MMStar's first questions, +skips it. Run by accept.sh in the client container. +""" + +import os +import shutil +from pathlib import Path + +from _common import ( + env, + failed_requests, + finish, + reference, + run_check, + run_lmms_eval, + stderr, + within, +) + + +def mmstar_task_dir(): + """lmms-eval's MMStar task, renamed, without its HF token requirement + (Lin-Chen/MMStar is public).""" + import lmms_eval + + src = Path(lmms_eval.__file__).parent / "tasks" / "mmstar" + dst = Path(env("RUN_DIR"), "tasks", "mmstar_notoken") + dst.mkdir(parents=True) + shutil.copy(src / "utils.py", dst) + template = (src / "_default_template_yaml").read_text() + (dst / "_default_template_yaml").write_text( + template.replace("token: True", "token: False") + ) + task = (src / "mmstar.yaml").read_text() + (dst / "mmstar.yaml").write_text( + task.replace('task: "mmstar"', 'task: "mmstar_notoken"') + ) + return dst.parent + + +def main(): + task = "mmstar_notoken" + threshold = float(env("MMSTAR_THRESHOLD")) + ref = reference() if env("REF_TOPOLOGY") else None + results, samples = run_lmms_eval( + "mmstar", + [task], + "temperature=0,max_new_tokens=16384", + 32, + mmstar_task_dir(), + ) + n = len(samples[task]) + score = results[task]["average,none"] + result = { + "score": score, + "stderr": stderr(score, n), + "n": n, + "failed_requests": failed_requests(samples[task]), + "threshold": threshold, + } + failures = [] + if result["failed_requests"]: + failures.append(f"{result['failed_requests']} failed requests") + if score < threshold and not os.environ.get("LIMIT"): + failures.append(f"score {score:.4f} is below the threshold {threshold:.4f}") + if ref: + tolerance = 2 * ref["stderr"] + result["reference"] = { + "topology": env("REF_TOPOLOGY"), + "score": ref["score"], + "stderr": ref["stderr"], + } + if not within(score, ref["score"], ref["stderr"]): + failures.append( + f"score {score:.4f} is not within {tolerance:.4f} of " + f"{env('REF_TOPOLOGY')}'s {ref['score']:.4f}" + ) + finish(result, failures) + + +if __name__ == "__main__": + run_check(main) diff --git a/tests/accept/atomesh_mm/lib.sh b/tests/accept/atomesh_mm/lib.sh new file mode 100644 index 00000000000..40eb52b9aa5 --- /dev/null +++ b/tests/accept/atomesh_mm/lib.sh @@ -0,0 +1,157 @@ +# Launch library for accept.sh: one container per role, on the node and GPUs +# the model profile names (_NODE, _GPUS), named +# epd---, so runs that share a node on +# different PORT_BASE never share a name, running ATOM and ATOMesh from the +# checkout at $ROOT. Every container this run created is removed at exit. +# Progress goes to stderr, logs to $RUN_DIR. + +CONTAINERS=() + +log() { echo "[accept] $*" >&2; } + +# on_node : run a shell command on a node, over ssh unless it +# is this host. +on_node() { + local node=$1 + shift + if [[ $node == "$(hostname -s)" || $node == "$(hostname -f)" ]]; then + bash -c "$*" + else + ssh -o BatchMode=yes "$node" "$*" + fi +} + +role_var() { # role_var + local name="${1^^}_$2" + echo "${!name:-}" +} + +cname() { echo "epd-${ACCEPT_ISSUE}-${PORT_BASE}-$1"; } + +cleanup_containers() { + local role + for role in "${CONTAINERS[@]}"; do + on_node "$(role_var "$role" NODE)" "docker rm -f $(cname "$role") >/dev/null 2>&1" || true + done +} + +# start_container : a detached container idling in the image, with the +# checkout, the profile's mounts and, when the role has GPUs, the GPU devices. +start_container() { + local role=$1 node gpus name + node=$(role_var "$role" NODE) + gpus=$(role_var "$role" GPUS) + name=$(cname "$role") + [[ -n $node ]] || { log "no ${role^^}_NODE in the model profile"; return 1; } + local args=(run -d --name "$name" --network host --ipc host --shm-size 64g + -e "HF_HOME=$HF_HOME" -e PYTHONUNBUFFERED=1 -w "$ROOT") + local m covered=0 + for m in "${MOUNTS[@]}"; do + args+=(-v "$m:$m") + [[ $ROOT/ == "$m"/* ]] && covered=1 + done + ((covered)) || args+=(-v "$ROOT:$ROOT") + if [[ -n $gpus ]]; then + args+=(--device /dev/kfd --device /dev/dri --group-add video -e "HIP_VISIBLE_DEVICES=$gpus") + fi + log "starting $name on $node${gpus:+ (GPUs $gpus)}" + # Only a container this run created is this run's to remove: when the name + # is taken, docker run fails and the other run's container stays. + on_node "$node" "$(printf '%q ' docker "${args[@]}" "$IMAGE" sleep infinity) >/dev/null" || + return 1 + CONTAINERS+=("$role") +} + +# in_role [docker exec options --] : run in the role's container. +in_role() { + local role=$1 + shift + local opts=() + if [[ " $* " == *" -- "* ]]; then + while [[ $1 != -- ]]; do + opts+=("$1") + shift + done + shift + fi + on_node "$(role_var "$role" NODE)" "$(printf '%q ' docker exec "${opts[@]}" "$(cname "$role")" "$@")" +} + +# wait_http : poll from inside the +# role's container until the url answers; fail early when the server died. +wait_http() { + local role=$1 url=$2 timeout=$3 pattern=$4 waited=0 + until in_role "$role" curl -sf -o /dev/null "$url"; do + if ! in_role "$role" pgrep -f "$pattern" >/dev/null; then + log "$role exited before $url answered" + return 1 + fi + if ((waited >= timeout)); then + log "$role: $url did not answer in ${timeout}s" + return 1 + fi + sleep 10 + waited=$((waited + 10)) + done +} + +role_url() { echo "http://$(role_var "$1" NODE):$2"; } + +# launch_atom [extra server args...]: +# ATOM's OpenAI server from the checkout, per the profile's ATOM_ENV/ATOM_ARGS. +launch_atom() { + local role=$1 port=$2 engine_port=$3 + shift 3 + start_container "$role" + # The image predates the jsonschema dependency in pyproject.toml. + in_role "$role" pip install -q "jsonschema>=4.25,<5" >&2 + local where + where=$(in_role "$role" python3 -c 'import atom, os; print(os.path.dirname(atom.__file__))') + if [[ $where != "$ROOT/atom" ]]; then + log "atom resolves to $where, not $ROOT/atom" + return 1 + fi + local env_opts=() e + for e in "${ATOM_ENV[@]}"; do env_opts+=(-e "$e"); done + local cmd + cmd=$(printf '%q ' python3 -m atom.entrypoints.openai_server "${ATOM_ARGS[@]}" \ + --server-port "$port" --port "$engine_port" "$@") + in_role "$role" -d "${env_opts[@]}" -- bash -c "$cmd > $RUN_DIR/$role.log 2>&1" + log "waiting for $role (log $RUN_DIR/$role.log)" + wait_http "$role" "http://127.0.0.1:$port/health" 3600 atom.entrypoints.openai_server +} + +# launch_mesh [atomesh launch args...]: build ATOMesh from the +# checkout and run it with the topology's arguments, then the check's +# MESH_ARGS (checks/.env), into a kept log. +launch_mesh() { + local role=$1 port=$2 + shift 2 + start_container "$role" + local target + target=$ACCEPT_DIR/cargo/$(echo -n "$ROOT" | md5sum | cut -c1-12) + log "building atomesh into $target (log $RUN_DIR/$role-build.log)" + if ! in_role "$role" -e "CARGO_TARGET_DIR=$target" -- bash -c \ + "cargo build --release --manifest-path $ROOT/atom/mesh/Cargo.toml > $RUN_DIR/$role-build.log 2>&1"; then + log "atomesh build failed" + return 1 + fi + local cmd + cmd=$(printf '%q ' "$target/release/atomesh" launch --host 0.0.0.0 --port "$port" \ + --prometheus-port "$MESH_METRICS_PORT" --model-path "$MODEL_PATH" "$@" ${MESH_ARGS[@]+"${MESH_ARGS[@]}"}) + in_role "$role" -d -e "RUST_LOG=mesh=info" -- \ + bash -c "$cmd > $RUN_DIR/$role.log 2>&1" + log "waiting for $role (log $RUN_DIR/$role.log)" + wait_http "$role" "http://127.0.0.1:$port/readiness" 600 "$target/release/atomesh" +} + +# start_client: the container the checks run in, with lmms-eval installed +# from the pinned source CI uses. +start_client() { + start_container client + log "installing lmms-eval (log $RUN_DIR/client-install.log)" + # The shared source tree belongs to another uid than the container's root. + in_role client -e "LMMS_EVAL_SRC_DIR=$ACCEPT_DIR/lmms-eval" -e GIT_CONFIG_COUNT=1 \ + -e GIT_CONFIG_KEY_0=safe.directory -e "GIT_CONFIG_VALUE_0=$ACCEPT_DIR/lmms-eval" -- bash -c \ + "bash $ROOT/.github/scripts/install_lmms_eval_no_deps.sh > $RUN_DIR/client-install.log 2>&1" +} diff --git a/tests/accept/atomesh_mm/models/m31.env b/tests/accept/atomesh_mm/models/m31.env new file mode 100644 index 00000000000..526a4cdc2c3 --- /dev/null +++ b/tests/accept/atomesh_mm/models/m31.env @@ -0,0 +1,60 @@ +# MiniMax-M3.1-Flash, Quark MXFP4 export, per recipes/MiniMax-M3.md +# ("MiniMax-M3.1-Flash on 4xMI355 GPUs"). Sourced by accept.sh. + +IMAGE=${IMAGE:-rocm/atom-dev:nightly_202611211511} +MODEL_PATH=${MODEL_PATH:-/share_nfs/models/amd/MiniMax-M3.1-Flash-Quark-MXFP4} +SERVED_MODEL=minimax-m3.1 + +# Shared storage every node mounts at the same path: the cache (lmms-eval +# source, the ATOMesh build), the results directory and the HF cache. +ACCEPT_DIR=${ACCEPT_DIR:-/share_nfs/junyan_tmp_r120/accept} +HF_HOME=${HF_HOME:-/share_nfs/junyan_tmp_r120/hf} +MOUNTS=(/share_nfs/junyan_tmp_r120 "$MODEL_PATH") + +# Roles: _NODE is the host the role's container runs on, _GPUS +# the GPUs its server sees. A role without GPUs gets no GPU devices. +ATOM_NODE=${ATOM_NODE:-pit2-p03-g07} +ATOM_GPUS=${ATOM_GPUS:-0,1,2,3} +MESH_NODE=${MESH_NODE:-pit2-p03-g07} +CLIENT_NODE=${CLIENT_NODE:-pit2-p03-g07} + +# Ports on the host network; set PORT_BASE to share a node with another run. +PORT_BASE=${PORT_BASE:-18600} +ATOM_PORT=$((PORT_BASE + 10)) +ATOM_ENGINE_PORT=$((PORT_BASE + 6)) +MESH_PORT=$((PORT_BASE + 0)) +MESH_METRICS_PORT=$((PORT_BASE + 29)) + +ATOM_ENV=( + AITER_LOG_LEVEL=WARNING + ATOM_FORCE_ATTN_TRITON=1 + AITER_QUICK_REDUCE_QUANTIZATION=INT4 + ATOM_FUSE_MXFP8_SHARED_INTO_MXFP4=1 +) +ATOM_ARGS=( + --model "$MODEL_PATH" + --served-model-name "$SERVED_MODEL" + --tensor-parallel-size 4 + --trust-remote-code + --default-chat-template-kwargs '{"thinking_mode": "enabled"}' + --gpu-memory-utilization 0.9 + --block-size 128 + --max-model-len 131072 + --max-num-seqs 128 + --max-num-batched-tokens 32768 + --kv_cache_dtype fp8 + --index-cache-dtype fp8 + --online_quant_config '{"global_quant_config": "ptpc_fp8", "exclude_layer": ["lm_head", "model.embed_tokens", "vision_tower", "multi_modal_projector", "patch_merge_mlp", "*block_sparse_moe"]}' + --no-enable_prefix_caching + --method dspark + --draft-model "$MODEL_PATH/dspark" + --num-speculative-tokens 7 +) + +# MMStar floor for every topology (checks/mmstar.py). Direct, single and +# 1P1D runs scored 0.7035-0.7227 (stderr 0.0117); 0.68 sits about three +# standard errors below them. +MMSTAR_THRESHOLD=${MMSTAR_THRESHOLD:-0.68} +# The recipe's MMMU-Pro standard (10 options) and vision scores. +MMMU_PRO_REF_STANDARD=0.791 +MMMU_PRO_REF_VISION=0.682 diff --git a/tests/accept/atomesh_mm/topologies/direct.sh b/tests/accept/atomesh_mm/topologies/direct.sh new file mode 100644 index 00000000000..dd86cd45327 --- /dev/null +++ b/tests/accept/atomesh_mm/topologies/direct.sh @@ -0,0 +1,7 @@ +# Direct: one ATOM server, no ATOMesh. The reference other topologies are +# checked against. + +topology_up() { + launch_atom atom "$ATOM_PORT" "$ATOM_ENGINE_PORT" + ENDPOINT=$(role_url atom "$ATOM_PORT") +} diff --git a/tests/accept/atomesh_mm/topologies/single.sh b/tests/accept/atomesh_mm/topologies/single.sh new file mode 100644 index 00000000000..3d5caedb8a6 --- /dev/null +++ b/tests/accept/atomesh_mm/topologies/single.sh @@ -0,0 +1,11 @@ +# Single: one ATOM server behind ATOMesh, cache_aware routing; checked +# against direct. + +REF_TOPOLOGY=direct + +topology_up() { + launch_atom atom "$ATOM_PORT" "$ATOM_ENGINE_PORT" + launch_mesh mesh "$MESH_PORT" --backend atom --policy cache_aware \ + --request-timeout-secs 14400 --worker-urls "$(role_url atom "$ATOM_PORT")" + ENDPOINT=$(role_url mesh "$MESH_PORT") +} diff --git a/tests/test_accept_atomesh_mm.py b/tests/test_accept_atomesh_mm.py new file mode 100644 index 00000000000..d9050b00ed1 --- /dev/null +++ b/tests/test_accept_atomesh_mm.py @@ -0,0 +1,256 @@ +"""The ATOMesh multimodal acceptance harness (tests/accept/atomesh_mm) on CPU: +its pure helpers, the MMStar and MMMU-Pro verdicts against fake lmms-eval +output, accept.sh refusing a check its topology cannot serve, and lib.sh's +container naming and cleanup list.""" + +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +HARNESS = Path(__file__).parent / "accept" / "atomesh_mm" +sys.path.insert(0, str(HARNESS / "checks")) +import _common +import distinct +import mmmu_pro +import mmstar + +FAILED = "[LMMS_EVAL_REQUEST_FAILED: timeout]" + + +def test_within_takes_its_tolerance_from_the_reference(): + assert _common.within(0.70, 0.72, 0.0117) + assert not _common.within(0.69, 0.72, 0.0117) + + +def test_failed_requests_counts_lmms_evals_failure_mark(): + assert _common.failed_requests(["ok", FAILED, "ok", FAILED]) == 2 + + +@pytest.mark.parametrize( + "response, letter", + [ + ("Reasoning.\nAnswer: C", "C"), + ("Answer: B\nOn second thought...\n**Answer: (D)**", "D"), + ("Answer: I think it is (C)\nAnswer: A", "A"), + ], +) +def test_answer_line_letter_reads_the_last_answer_line(response, letter): + assert mmmu_pro.answer_line_letter(response) == letter + + +def test_answer_line_letter_falls_back_to_the_extractor(monkeypatch): + monkeypatch.setattr(mmmu_pro, "extracted_letter", lambda response: "E") + assert mmmu_pro.answer_line_letter("The answer is option E.") == "E" + + +def test_accuracy_reads_the_first_filtered_response(): + lines = [ + json.dumps({"filtered_resps": ["Answer: A"], "target": "A"}), + json.dumps({"filtered_resps": "Answer: B", "target": "C"}), + ] + assert mmmu_pro.accuracy(lines, mmmu_pro.answer_line_letter) == 0.5 + + +def test_names_matches_whole_words_only(): + assert distinct.names("Red.", "red") + assert not distinct.names("Reddish", "red") + + +def test_decision_events_reads_the_selected_worker_fields(): + log = ( + "\x1b[2m2026-11-22\x1b[0m INFO http_request{uri=/v1/chat/completions}: " + 'mesh::route: Selected worker pool="regular" branch="affinity" ' + "match_ratio=1.0 media_count=1\n" + "INFO mesh: unrelated line\n" + ) + assert distinct.decision_events(log) == [ + { + "pool": "regular", + "branch": "affinity", + "match_ratio": "1.0", + "media_count": "1", + } + ] + + +@pytest.fixture +def check_env(tmp_path, monkeypatch): + """The environment accept.sh gives a check, with RESULTS_DIR in tmp_path.""" + values = { + "ACCEPT_MODEL": "m31", + "ACCEPT_TOPOLOGY": "direct", + "RUN_DIR": str(tmp_path / "run"), + "RESULTS_DIR": str(tmp_path / "results"), + "REF_TOPOLOGY": "", + "LIMIT": "", + "MMSTAR_THRESHOLD": "0.68", + "MMMU_PRO_REF_STANDARD": "0.791", + "MMMU_PRO_REF_VISION": "0.682", + } + for name, value in values.items(): + monkeypatch.setenv(name, value) + (tmp_path / "run").mkdir() + return tmp_path + + +def verdict(check, capsys): + """Run a check's main() and return its JSON line and exit status.""" + with pytest.raises(SystemExit) as exit_info: + check.main() + return json.loads(capsys.readouterr().out.splitlines()[0]), exit_info.value.code + + +def record(results_dir, topology, check, result): + path = results_dir / "m31" / topology + path.mkdir(parents=True, exist_ok=True) + (path / f"{check}.json").write_text(json.dumps({"passed": True, **result})) + + +def fake_mmstar(monkeypatch, score, n=1500, failed=0): + lines = [FAILED] * failed + ["{}"] * (n - failed) + results = {"mmstar_notoken": {"average,none": score}} + monkeypatch.setattr(mmstar, "mmstar_task_dir", lambda: None) + monkeypatch.setattr( + mmstar, "run_lmms_eval", lambda *a, **k: (results, {"mmstar_notoken": lines}) + ) + + +def test_a_zero_direct_mmstar_fails_and_is_no_reference(check_env, monkeypatch, capsys): + monkeypatch.setenv("ACCEPT_CHECK", "mmstar") + fake_mmstar(monkeypatch, 0.0) + line, status = verdict(mmstar, capsys) + assert status == 1 and not line["passed"] + assert "below the threshold 0.6800" in line["reason"] + recorded = json.loads((check_env / "results/m31/direct/mmstar.json").read_text()) + assert not recorded["passed"] + monkeypatch.setenv("ACCEPT_TOPOLOGY", "single") + monkeypatch.setenv("REF_TOPOLOGY", "direct") + with pytest.raises(RuntimeError, match="did not pass"): + _common.reference() + + +def test_a_limit_run_skips_the_floor(check_env, monkeypatch, capsys): + monkeypatch.setenv("ACCEPT_CHECK", "mmstar") + monkeypatch.setenv("LIMIT", "50") + fake_mmstar(monkeypatch, 0.42, n=50) + line, status = verdict(mmstar, capsys) + assert status == 0 and line["passed"] + assert not (check_env / "results/m31/direct/mmstar.json").exists() + + +def test_mmstar_without_a_threshold_fails(check_env, monkeypatch, capsys): + monkeypatch.setenv("ACCEPT_CHECK", "mmstar") + monkeypatch.delenv("MMSTAR_THRESHOLD") + fake_mmstar(monkeypatch, 0.72) + with pytest.raises(SystemExit): + _common.run_check(mmstar.main) + assert ( + "MMSTAR_THRESHOLD" + in json.loads(capsys.readouterr().out.splitlines()[-2])["reason"] + ) + + +def test_single_mmstar_is_held_to_directs_score(check_env, monkeypatch, capsys): + monkeypatch.setenv("ACCEPT_CHECK", "mmstar") + monkeypatch.setenv("ACCEPT_TOPOLOGY", "single") + monkeypatch.setenv("REF_TOPOLOGY", "direct") + record(check_env / "results", "direct", "mmstar", {"score": 0.72, "stderr": 0.0117}) + fake_mmstar(monkeypatch, 0.69) + line, status = verdict(mmstar, capsys) + assert status == 1 and "not within 0.0234 of direct's 0.7200" in line["reason"] + + +def fake_mmmu_pro(monkeypatch, correct, n=100, failed=0): + """Samples per subset: `correct` right answers out of n, the first + `failed` of them failed requests (answered with lmms-eval's mark).""" + lines = [] + for i in range(n): + if i < failed: + resp = FAILED + else: + resp = "Answer: A" if i < correct + failed else "Answer: B" + lines.append(json.dumps({"filtered_resps": [resp], "target": "A"})) + monkeypatch.setattr(mmmu_pro, "vision_task_dir", lambda: None) + monkeypatch.setattr(mmmu_pro, "extracted_letter", lambda response: None) + monkeypatch.setitem(mmmu_pro.SCORERS, "standard", mmmu_pro.answer_line_letter) + samples = {task: lines for task in mmmu_pro.SUBSETS.values()} + monkeypatch.setattr(mmmu_pro, "run_lmms_eval", lambda *a, **k: ({}, samples)) + + +def test_mmmu_pro_fails_on_failed_requests(check_env, monkeypatch, capsys): + monkeypatch.setenv("ACCEPT_CHECK", "mmmu-pro") + monkeypatch.setenv("MMMU_PRO_REF_STANDARD", "0.75") + monkeypatch.setenv("MMMU_PRO_REF_VISION", "0.75") + fake_mmmu_pro(monkeypatch, correct=75, failed=2) + line, status = verdict(mmmu_pro, capsys) + assert status == 1 + assert "standard: 2 failed requests" in line["reason"] + assert line["standard"]["reference"]["source"] == "recipe" + + +def test_mmmu_pro_on_single_is_held_to_direct_with_directs_stderr( + check_env, monkeypatch, capsys +): + monkeypatch.setenv("ACCEPT_CHECK", "mmmu-pro") + monkeypatch.setenv("ACCEPT_TOPOLOGY", "single") + monkeypatch.setenv("REF_TOPOLOGY", "direct") + subset = {"score": 0.80, "stderr": 0.01} + record( + check_env / "results", + "direct", + "mmmu-pro", + {"topology": "direct", "standard": subset, "vision": subset}, + ) + # 0.75 over 100 questions has a stderr of 0.043: a tolerance from the run + # under test would pass it; direct's 0.01 does not. + fake_mmmu_pro(monkeypatch, correct=75) + line, status = verdict(mmmu_pro, capsys) + assert status == 1 + assert "standard 0.7500 is not within 0.0200 of direct's 0.8000" in line["reason"] + assert line["vision"]["reference"] == {"source": "direct", **subset} + + +def bash(script, **env): + return subprocess.run( + ["bash", "-c", script], + check=False, + capture_output=True, + text=True, + env={"PATH": "/usr/bin:/bin", **env}, + ) + + +def test_accept_refuses_distinct_on_direct(tmp_path): + out = bash( + f"bash {HARNESS / 'accept.sh'} m31 direct distinct", + ACCEPT_DIR=str(tmp_path), + HOME=str(tmp_path), + ) + assert out.returncode == 1 + assert out.stdout.splitlines()[-1] == ( + "FAIL distinct needs ATOMesh, which topology direct does not run" + ) + assert not (tmp_path / "results").exists() + + +def test_container_names_carry_the_port_base(): + out = bash( + f"source {HARNESS / 'lib.sh'}; cname mesh", ACCEPT_ISSUE="7", PORT_BASE="18700" + ) + assert out.stdout.strip() == "epd-7-18700-mesh" + + +def test_a_container_that_failed_to_start_is_not_removed(): + script = f""" +source {HARNESS / 'lib.sh'} +on_node() {{ [[ $2 != docker\\ run* ]] || return 1; echo "$2" >> removed; }} +ATOM_NODE=n ATOM_GPUS=0 MOUNTS=() ROOT=/r +start_container atom 2>/dev/null || true +cleanup_containers +echo "tracked=${{#CONTAINERS[@]}}" +""" + out = bash(script, ACCEPT_ISSUE="7", PORT_BASE="18700") + assert out.stdout.strip() == "tracked=0"