Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 3 additions & 0 deletions docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions docs/e2e-qwen-image-codex.md
Original file line number Diff line number Diff line change
@@ -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='<Issue-指定的完整基线提交>'
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,可从这些文件复核结果。运行目录可能含私有机器路径和会话内容。
99 changes: 99 additions & 0 deletions e2e/qwen_image/measure.py
Original file line number Diff line number Diff line change
@@ -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),
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Dot, acting for @david6666666 under delegated PR review.

sample_sigmas here records the requested values from workload.json, not the grid the scheduler actually executed. A candidate can change how those values are handled and this receipt still matches the baseline. #479 requires the effective grid to be retained for the compared runs. Capture the effective timestep/sigma sequence and step count at the runtime boundary and reject a mismatch; add a regression that keeps the requested values unchanged while the effective grid differs.

(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)
1 change: 1 addition & 0 deletions e2e/qwen_image/request.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
请用 InferRSI 优化当前 vLLM-Omni 项目的 Qwen-Image-2.1-Turbo,在 Ascend A2 单卡上生成 1280×704 图片,保持出图质量,把单张生图耗时降到尽可能低。请完成 3 轮优化迭代,再复测这 3 轮中表现最好的方案,并交付补丁、优化前后的单张生图耗时和降幅。
Loading
Loading