Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions tests/accept/atomesh_mm/accept.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# Acceptance harness for ATOMesh multimodal requests.
#
# bash tests/accept/atomesh_mm/accept.sh <model> <topology> <check>
#
# Sources models/<model>.env (image, model, nodes and GPUs per role, server
# arguments) and then checks/<check>.env when the check has one (what the
# check needs changed in the profile), brings the deployment up with
# topologies/<topology>.sh, runs checks/<check>.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 <reason>; the
# JSON is also kept as $ACCEPT_DIR/results/<model>/<topology>/<check>.json,
# where later checks read their references, beside the run's logs.
set -euo pipefail

if (($# != 3)); then
echo "usage: $0 <model> <topology> <check>" >&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 <reason>: 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"

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 "MMMU_PRO_REF_STANDARD=${MMMU_PRO_REF_STANDARD:-}" -e "MMMU_PRO_REF_VISION=${MMMU_PRO_REF_VISION:-}" \
-- python3 "$CHECK_PY"
3 changes: 3 additions & 0 deletions tests/accept/atomesh_mm/checks/distinct.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# 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)
136 changes: 136 additions & 0 deletions tests/accept/atomesh_mm/checks/distinct.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
"""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 (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 routing decision event per request, the two
with different key hashes. With the text shared, only the images' media
digests can tell the two routing keys apart, and only the images' cache_seed
keeps the second request off the first one's cached KV.
"""

import json
import re
import struct
import time
import urllib.request
import zlib
from base64 import b64encode
from pathlib import Path

from mmstar 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 routing decision 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("routing decision")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ATOMesh logs 'Selected worker', not 'routing decision', and only with --route-log-sample-rate > 0 which launch_mesh never passes. so this always sees 0 events. no key_hash field exists either..

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no routing decision event and no key_hash at this head, so this can never pass.. land #3407 first and post one distinct run

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)
result[color] = {
"answer": answer,
"key_hash": events[0].get("key_hash") if len(events) == 1 else None,
"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)} routing decision events in {log} for the {color} request"
)
hashes = [result[color]["key_hash"] for color in COLORS]
if None not in hashes and hashes[0] == hashes[1]:
failures.append(f"both requests routed on key hash {hashes[0]}")
finish(result, failures)


if __name__ == "__main__":
run_check(main)
118 changes: 118 additions & 0 deletions tests/accept/atomesh_mm/checks/mmmu_pro.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""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 each subset's score is within 2 x its standard error of the
model profile's reference (MMMU_PRO_REF_STANDARD, MMMU_PRO_REF_VISION).
"""

import json
import re
import shutil
from pathlib import Path

from mmstar import env, failed_requests, finish, run_check, run_lmms_eval, stderr

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check module used as a library.. move helpers to _common.py and add cpu tests for the pure ones


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 main():
_, 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 = float(env(f"MMMU_PRO_REF_{subset.upper()}"))
tolerance = 2 * stderr(score, n)
result[subset] = {
"score": score,
"stderr": stderr(score, n),
"n": n,
"failed_requests": failed_requests(samples[task]),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

failed_requests never added to failures, unlike mmstar. with n~1730 a few failed requests still pass the 2*stderr. add it or say why tolerated?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

failed_requests never appended to failures, and tolerance from the run under test not the reference.. also REF_TOPOLOGY never read?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

failed_requests never added to failures, tolerance uses the run under test, and ref always reads the recipe ignoring REF_TOPOLOGY.. please fix all three

"reference": ref,
}
if abs(score - ref) > tolerance:
failures.append(
f"{subset} {score:.4f} is not within {tolerance:.4f} of {ref:.4f}"
)
finish(result, failures)


if __name__ == "__main__":
run_check(main)
Loading
Loading