diff --git a/docs/contributing.md b/docs/contributing.md index 624fc0687..cb604be69 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -28,6 +28,9 @@ Synthetic benchmark scripts belong in `tests/fixtures/`; historical validator snapshots in `tests/fixtures/legacy/` remain byte-for-byte frozen. Current runnable examples are the three Qwen scripts under `examples/`. +Run the [Codex Qwen-Image E2E case](e2e-qwen-image-codex.md) on a prepared +Ascend A2 host to optimize the model and independently measure the delivered patch. + Git treats recorded bundles under `evidence/` and `tests/fixtures/legacy/` as exact bytes (`-text`), so checkout and add do not normalize their line endings. The evidence README and reusable `_template/` remain ordinary LF text. This diff --git a/docs/e2e-qwen-image-codex.md b/docs/e2e-qwen-image-codex.md new file mode 100644 index 000000000..e476aac0c --- /dev/null +++ b/docs/e2e-qwen-image-codex.md @@ -0,0 +1,36 @@ +# 在 Ascend A2 上运行 Codex 图像优化 E2E + +本目录只有一个 pytest 用例。它在同一台 Ascend A2 机器上启动 Codex,等待优化结束,从固定基线应用最终补丁,然后独立测量单张图像的耗时与质量。[任务与基线版本](https://github.com/InferMatrixLab/InferRSI/issues/479) + +## 运行 + +在预配置的 Linux A2 环境中运行。该环境需要已登录的 Codex CLI、可用的 InferRSI、该基线所需的 vLLM-Omni 昇腾依赖和本地只读模型权重。给进程分配一张空闲的 Ascend 910B,使其仅能看到这张卡。环境变量可由机器的作业配置一次性设置。 + +```bash +export QWEN_E2E_REPO='<本地-vllm-omni-Git-仓库>' +export QWEN_E2E_REVISION='' +export QWEN_E2E_CHECKPOINT='<本地-Qwen-Image-2.1-Turbo-权重目录>' +export QWEN_E2E_RESULTS='<本次作业可写的私有结果父目录>' +python -m pytest -qs e2e/qwen_image/test_user_journey.py +``` + +前三个变量是必需项。省略 `QWEN_E2E_RESULTS` 时使用 pytest 临时目录。每次运行都会新建结果子目录。Codex 使用机器上已配置的模型,也可以通过 `QWEN_E2E_CODEX_MODEL` 指定。默认每次 Codex 调用或测量进程的超时为 7200 秒,可用 `QWEN_E2E_TIMEOUT_SECONDS` 调整。运行期间无人工问答、审批或手工提交补丁。 + +## 输入与执行 + +- 用户请求见 [request.txt](../e2e/qwen_image/request.txt)。用例附上本机模型、冻结测量程序和新建 campaign 的位置,要求 Codex 将选中的实现留在工作副本的 `vllm_omni/` 中。实际投递内容保存在结果目录的 `request.txt`。 +- [workload.json](../e2e/qwen_image/workload.json) 固定两个预热请求和六个测量请求(种子 42–47)。两侧均使用 1280×704、BF16、原生八步、CFG=1、单卡、单请求单图。计时从调用 `Omni.generate` 开始,到取得已解码的 RGBA 图像为止。模型加载、预热和 PNG 落盘分别处理。 +- 用例先在两个全新进程中复测基线,核对六张原图,记录两组中位耗时的相对差值作为本次噪声参考。此时将运行条件写入 `frozen.json`。若 Issue 另有最低降幅,开跑前用 `QWEN_E2E_MIN_GAIN_PCT` 指定百分数。 +- Codex 退出后,用例读取同一次运行中的最终回复和 InferRSI campaign,核对计划和实际执行都恰好是三轮优化,并检查完成状态和最终选中源码。随后从工作副本提取补丁,在第二个干净 Git 副本中应用,核对 `vllm_omni/` 的 Git 树。之后以 AB、BA、AB 的顺序交替测基线(A)与补丁(B),每组每侧启动一个新的推理进程。每个进程保存六个原始耗时与六张 PNG。 + +## 校验优化指标 + +`baseline_ms` 和 `candidate_ms` 分别为各自三个组中位数的中位数。用例输出节省的毫秒数、降幅 `100 × (baseline_ms − candidate_ms) / baseline_ms` 和加速比 `baseline_ms / candidate_ms`,逐种子比对所有候选图像的 RGBA 字节。 + +| 结果 | 条件 | +| --- | --- | +| `PASS` | 六组图像全部一致;耗时降幅为正、达到预设最低降幅,且超过测前基线 A/A 差值。 | +| `FAIL` | 已完成优化却没有交付源码改动、补丁与选中源码不符、候选图像变化,或实测未达到正向收益及设定的最低降幅。 | +| `INCONCLUSIVE` | 基线不稳定、环境或执行证据不完整,或正向收益仍处于 A/A 波动范围。pytest 返回非零。 | + +最终结果见 `result.json`。同目录保留 Codex 会话日志、回复、`candidate.patch`、各组原始耗时和 PNG,可从这些文件复核结果。运行目录可能含私有机器路径和会话内容。 diff --git a/e2e/qwen_image/measure.py b/e2e/qwen_image/measure.py new file mode 100644 index 000000000..85252f7ec --- /dev/null +++ b/e2e/qwen_image/measure.py @@ -0,0 +1,99 @@ +"""Measure one checkout on one Ascend A2 NPU in a fresh Python process.""" + +import argparse +import hashlib +import json +import os +import sys +import time +from pathlib import Path +from statistics import median + + +def measure(source, checkpoint, output): + workload_bytes = Path(__file__).with_name("workload.json").read_bytes() + workload = json.loads(workload_bytes) + model_bytes = (checkpoint / "model_index.json").read_bytes() + model = json.loads(model_bytes) + sigmas = workload["sample_sigmas"] + if (model.get("_class_name") != "QwenImage21Pipeline" + or len(sigmas) != 8 or model.get("sample_sigmas") != sigmas): + raise ValueError("The checkpoint must contain the frozen native Turbo sampling grid") + + # Spawned engine processes must resolve the same checkout as this process. + sys.path.insert(0, str(source)) + old_path = os.environ.get("PYTHONPATH") + os.environ["PYTHONPATH"] = str(source) + (os.pathsep + old_path if old_path else "") + os.environ["HF_HUB_OFFLINE"] = "1" + import torch + import vllm_omni + from vllm_omni.diffusion.utils.image_output import extract_images_from_outputs + from vllm_omni.entrypoints.omni import Omni + from vllm_omni.inputs.data import OmniDiffusionSamplingParams + from vllm_omni.platforms import current_omni_platform + + for module in (vllm_omni, sys.modules[Omni.__module__], + sys.modules[extract_images_from_outputs.__module__]): + if not Path(module.__file__).resolve().is_relative_to(source / "vllm_omni"): + raise RuntimeError("The measurement process imported a different vLLM-Omni checkout") + if current_omni_platform.device_type != "npu" or torch.npu.device_count() != 1: + raise RuntimeError("Expose exactly one Ascend A2 NPU to the measurement process") + device = current_omni_platform.get_device_name(0) + if "910B" not in device.upper(): + raise RuntimeError(f"Expected an Ascend A2 (910B) NPU, detected {device}") + + output.mkdir(parents=True, exist_ok=True) + if (output / "result.json").exists() or any(output.glob("seed-*.png")): + raise FileExistsError("Use a fresh output directory for every measurement") + warmup_ms, latencies_ms = [], [] + engine = Omni( + model=str(checkpoint), dtype="bfloat16", tensor_parallel_size=1, enforce_eager=True, + ) + try: + for group in ("warmups", "requests"): + for case in workload[group]: + params = OmniDiffusionSamplingParams( + width=workload["width"], height=workload["height"], seed=case["seed"], + true_cfg_scale=1.0, num_outputs_per_prompt=1, + sigmas=list(sigmas), + ) + prompt = {"prompt": case["prompt"], "modalities": ["image"]} + start = time.perf_counter_ns() + outputs = engine.generate(prompt, sampling_params_list=[params], use_tqdm=False) + images = extract_images_from_outputs(outputs) + if len(images) != 1: + raise ValueError("Expected exactly one decoded image") + image = images[0] + image.load() + elapsed = (time.perf_counter_ns() - start) / 1e6 + if image.size != (workload["width"], workload["height"]) or image.mode != "RGBA": + raise ValueError( + f"Unexpected image for seed {case['seed']}: {image.size}, {image.mode}" + ) + if group == "warmups": + warmup_ms.append(elapsed) + else: + latencies_ms.append(elapsed) + image.save(output / f"seed-{case['seed']}.png") + finally: + engine.close() + result = { + "device": device, "workload_sha256": hashlib.sha256(workload_bytes).hexdigest(), + "model_index_sha256": hashlib.sha256(model_bytes).hexdigest(), "sample_sigmas": sigmas, + "seeds": [case["seed"] for case in workload["requests"]], + "warmup_ms": warmup_ms, "latencies_ms": latencies_ms, "median_ms": median(latencies_ms), + } + (output / "result.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + for name in ("source", "checkpoint", "output"): + parser.add_argument(name, type=Path) + args = parser.parse_args() + measure(args.source.resolve(), args.checkpoint.resolve(), args.output.resolve()) + # The pinned Ascend runtime can abort during interpreter teardown after engine.close(). + # Only use this exit once all work, engine cleanup and file writes have succeeded. + sys.stdout.flush() + sys.stderr.flush() + os._exit(0) diff --git a/e2e/qwen_image/request.txt b/e2e/qwen_image/request.txt new file mode 100644 index 000000000..72ba5fa7d --- /dev/null +++ b/e2e/qwen_image/request.txt @@ -0,0 +1 @@ +请用 InferRSI 优化当前 vLLM-Omni 项目的 Qwen-Image-2.1-Turbo,在 Ascend A2 单卡上生成 1280×704 图片,保持出图质量,把单张生图耗时降到尽可能低。请完成 3 轮优化迭代,再复测这 3 轮中表现最好的方案,并交付补丁、优化前后的单张生图耗时和降幅。 diff --git a/e2e/qwen_image/test_user_journey.py b/e2e/qwen_image/test_user_journey.py new file mode 100644 index 000000000..914dd65f4 --- /dev/null +++ b/e2e/qwen_image/test_user_journey.py @@ -0,0 +1,217 @@ +"""One opt-in, unattended Codex optimization and independent Ascend A2 measurement.""" + +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import tempfile +from pathlib import Path +from statistics import median + +import pytest + +CASE = Path(__file__).resolve().parent +OPTIMIZATION_ROUNDS = 3 + + +def git(repo, *args): + return subprocess.run( + ["git", "-C", str(repo), *args], check=True, stdout=subprocess.PIPE, + stdin=subprocess.DEVNULL, + ).stdout + + +def checkout(repo, revision, destination): + subprocess.run(["git", "clone", "--quiet", "--no-local", "--no-checkout", + str(repo), str(destination)], check=True, stdin=subprocess.DEVNULL) + git(destination, "checkout", "--quiet", "--detach", revision) + if git(destination, "rev-parse", "HEAD").decode().strip() != revision: + raise ValueError("Use the full baseline commit from the acceptance issue") + + +def write_json(path, data): + path.write_text(json.dumps(data, indent=2, allow_nan=False) + "\n", encoding="utf-8") + + +def run_logged(argv, cwd, logfile, timeout, prompt=None): + # On the A2 host, stop this run's local process group if its deadline expires. + with logfile.open("wb") as log, subprocess.Popen( + argv, cwd=cwd, start_new_session=True, stdout=log, stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL if prompt is None else subprocess.PIPE, + ) as child: + try: + child.communicate(input=prompt, timeout=timeout) + except subprocess.TimeoutExpired: + os.killpg(child.pid, signal.SIGKILL) + child.wait() + raise + if child.returncode: + raise RuntimeError(f"{Path(argv[0]).name} exited {child.returncode}; see " + f"{logfile.name}") + + +def optimize(project, checkpoint, output, timeout): + from inferrsi.harness.candidates import identity + + agent_runs = output / "agent-runs" + agent_runs.mkdir() + campaign = agent_runs / "campaign" + prompt = (CASE / "request.txt").read_text(encoding="utf-8").strip() + prompt += ( + f"\n本机模型目录:{checkpoint}。冻结的测量程序:{CASE / 'measure.py'}," + "依次传入源码目录、模型目录、新输出目录。请自主使用本机 InferRSI 的 " + f"campaign start(--rounds {OPTIMIZATION_ROUNDS} --round-mode exact)、round、final " + f"完成三轮优化,campaign 目录使用 {campaign}。" + "将最终选中的生产代码留在当前项目的 vllm_omni/ 下,供独立复测。" + ) + (output / "request.txt").write_text(prompt + "\n", encoding="utf-8") + command = ["codex", "--ask-for-approval", "never", "exec", "--sandbox", "workspace-write", + "--add-dir", str(agent_runs), + "--json", "--output-last-message", str(output / "final-reply.txt")] + if model := os.environ.get("QWEN_E2E_CODEX_MODEL"): + command += ["--model", model] + run_logged([*command, "-"], project, output / "codex.jsonl", timeout, prompt.encode("utf-8")) + # The campaign and final reply must both belong to this fresh invocation. + plan = json.loads((campaign / "plan.json").read_bytes()) + state = json.loads((campaign / "state.json").read_bytes()) + completed_rounds = len(state["rounds"]) + if (plan["round_mode"] != "exact" or plan["round_limit"] != OPTIMIZATION_ROUNDS + or completed_rounds != OPTIMIZATION_ROUNDS): + raise ValueError( + f"Expected exactly {OPTIMIZATION_ROUNDS} planned and completed optimization rounds; " + f"found round_mode={plan['round_mode']!r}, round_limit={plan['round_limit']}, " + f"completed_rounds={completed_rounds}" + ) + if (not (output / "final-reply.txt").read_text(encoding="utf-8").strip() + or plan["task_source"] != "project" or Path(plan["working_candidate"]) != project + or state["state"] != "completed" + or identity(project, plan["candidate_includes"]) != state["final"]["candidate_sha256"]): + raise ValueError("The Codex run did not deliver the final source of this project campaign") + return completed_rounds + + +def measure(source, checkpoint, output, timeout): + output.mkdir() + run_logged([sys.executable, str(CASE / "measure.py"), str(source), str(checkpoint), + str(output)], source, output / "worker.log", timeout) + + +def sample(source, checkpoint, output, timeout, workload): + from PIL import Image + + measure(source, checkpoint, output, timeout) + receipt = json.loads((output / "result.json").read_bytes()) + times = receipt["latencies_ms"] + seeds = [row["seed"] for row in workload["requests"]] + if (receipt["seeds"] != seeds or len(times) != len(seeds) + or len(receipt["warmup_ms"]) != len(workload["warmups"]) + or any(not math.isfinite(t) or t <= 0 for t in [*times, *receipt["warmup_ms"]])): + raise ValueError("Missing or invalid raw timing samples") + pixels = {} + for seed in seeds: + with Image.open(output / f"seed-{seed}.png") as image: + if image.mode != "RGBA" or image.size != (workload["width"], workload["height"]): + raise ValueError("Unexpected decoded image format") + pixels[seed] = hashlib.sha256(image.tobytes()).hexdigest() + identity = {k: receipt[k] for k in ("device", "sample_sigmas", "workload_sha256", + "model_index_sha256")} + return median(times), pixels, identity + + +def verify_source(repo, expected_tree): + if (git(repo, "write-tree").decode().strip() != expected_tree + or git(repo, "diff", "--name-only", "--", "vllm_omni") + or git(repo, "ls-files", "--others", "--exclude-standard", "--", "vllm_omni")): + raise ValueError("The measured source changed after checkout or patch reconstruction") + + +def test_codex_optimizes_qwen_image_on_a2(tmp_path): + parent = Path(os.environ.get("QWEN_E2E_RESULTS", tmp_path)).resolve() + parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix="qwen-a2-", dir=parent)) + print(f"E2E results: {output}", flush=True) + report = {"verdict": "INCONCLUSIVE", "stage": "preflight", + "required_optimization_rounds": OPTIMIZATION_ROUNDS} + try: + repo = Path(os.environ["QWEN_E2E_REPO"]).resolve(strict=True) + checkpoint = Path(os.environ["QWEN_E2E_CHECKPOINT"]).resolve(strict=True) + revision = os.environ["QWEN_E2E_REVISION"] + timeout = int(os.environ.get("QWEN_E2E_TIMEOUT_SECONDS", "7200")) + minimum = float(os.environ.get("QWEN_E2E_MIN_GAIN_PCT", "0")) + if timeout <= 0 or not math.isfinite(minimum) or minimum < 0: + raise ValueError("Invalid timeout or minimum latency reduction") + workload = json.loads((CASE / "workload.json").read_bytes()) + baseline, project, candidate = (output / n for n in ("baseline", "optimize", "candidate")) + for tree in (baseline, project): + checkout(repo, revision, tree) + baseline_tree = git(baseline, "write-tree").decode().strip() + first, reference, identity = sample(baseline, checkpoint, output / "preflight-a", + timeout, workload) + second, pixels, other = sample(baseline, checkpoint, output / "preflight-b", + timeout, workload) + if (pixels != reference or identity != other + or identity["sample_sigmas"] != workload["sample_sigmas"] + or identity["workload_sha256"] != hashlib.sha256( + (CASE / "workload.json").read_bytes()).hexdigest()): + raise ValueError("Baseline A/A pixels or environment changed before optimization") + noise = 100 * abs(second - first) / first + report.update(baseline_revision=revision, environment=identity, aa_ms=[first, second], + noise_pct=noise, min_gain_pct=minimum) + write_json(output / "frozen.json", report) + report["stage"] = "codex" + report["completed_optimization_rounds"] = optimize(project, checkpoint, output, timeout) + + report["stage"] = "reconstruct" + git(project, "add", "-A", "--", "vllm_omni") + patch = git(project, "diff", "--cached", "--binary", "--full-index", revision, + "--", "vllm_omni") + if not patch: + report.update(verdict="FAIL", error="Codex finished without delivering a source change") + pytest.fail(report["error"]) + patchfile = output / "candidate.patch" + patchfile.write_bytes(patch) + checkout(repo, revision, candidate) + git(candidate, "apply", "--index", "--binary", str(patchfile)) + selected = git(project, "write-tree").decode().strip() + rebuilt = git(candidate, "write-tree").decode().strip() + if git(project, "rev-parse", selected + ":vllm_omni") != git( + candidate, "rev-parse", rebuilt + ":vllm_omni"): + report.update(verdict="FAIL", error="Patch does not reconstruct the selected source") + pytest.fail(report["error"]) + report.update(candidate_tree=rebuilt, patch_sha256=hashlib.sha256(patch).hexdigest()) + + report["stage"] = "independent_retest" + scores = {"baseline": [], "candidate": []} + failed_seeds = set() + for i, pair in enumerate(("AB", "BA", "AB"), 1): + for arm in pair: + name, tree = ("baseline", baseline) if arm == "A" else ("candidate", candidate) + expected_tree = baseline_tree if arm == "A" else rebuilt + verify_source(tree, expected_tree) + value, actual, runtime = sample(tree, checkpoint, output / f"{i:02}-{name}", + timeout, workload) + verify_source(tree, expected_tree) + if runtime != identity or (name == "baseline" and actual != reference): + raise ValueError("Independent baseline or measurement environment changed") + failed_seeds.update(seed for seed in reference if actual[seed] != reference[seed]) + scores[name].append(value) + before, after = (median(scores[name]) for name in ("baseline", "candidate")) + gain = 100 * (before - after) / before + report.update(stage="finished", group_medians_ms=scores, baseline_ms=before, + candidate_ms=after, reduction_ms=before - after, reduction_pct=gain, + speedup=before / after, quality_passed=len(reference) - len(failed_seeds), + quality_total=len(reference), failed_seeds=sorted(failed_seeds)) + if failed_seeds or gain <= 0 or gain < minimum: + report["verdict"] = "FAIL" + elif gain > noise: + report["verdict"] = "PASS" + assert report["verdict"] == "PASS", report + except Exception as error: + report["error"] = str(error) + raise + finally: + write_json(output / "result.json", report) + print(json.dumps(report, ensure_ascii=False), flush=True) diff --git a/e2e/qwen_image/workload.json b/e2e/qwen_image/workload.json new file mode 100644 index 000000000..3146a7ea8 --- /dev/null +++ b/e2e/qwen_image/workload.json @@ -0,0 +1,18 @@ +{ + "model": "Qwen/Qwen-Image-2.1-Turbo", + "width": 1280, + "height": 704, + "sample_sigmas": [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568], + "warmups": [ + {"seed": 30, "prompt": "A white lighthouse at the end of a rocky pier at dawn."}, + {"seed": 31, "prompt": "Three oranges in a blue bowl on a white kitchen counter."} + ], + "requests": [ + {"seed": 42, "prompt": "A red ceramic teapot on a wooden table, soft side lighting."}, + {"seed": 43, "prompt": "A snowy mountain village at dusk, warm lights in the windows."}, + {"seed": 44, "prompt": "A watercolor of a kingfisher above a stream lined with reeds."}, + {"seed": 45, "prompt": "A minimal yellow poster with the large title FRESH LEMONS and a lemon illustration."}, + {"seed": 46, "prompt": "A candid portrait of an elderly gardener in a greenhouse, natural morning light."}, + {"seed": 47, "prompt": "一只戴着红色围巾的小狐狸站在雪地里,远处是安静的松林。"} + ] +}