← Back to Pull requests

feat: bootstrap CLI experiment workbench and diffusion knowledge #2

Open
david6666666 opened this pull request with 13186 lines diff across 146 files
View on GitHub
david6666666 david6666666 commented on Oct 09, 2026 10:26 UTC
Author

Current history: twenty commits over main 1eae6e73c8a08c29b91eea4a3b0f2167554fc29b. The original eleven commits through 7ca4829f91a9e7d4a8e6cec829ffded2e0db4e5d remain unchanged and in order. david6666666/OmniRSI#1 is merged at 884ea897c768c8e75d94d4ddd2a26ba08aa21c78, preserving both commits by amy-why-3459 (ed3b50b, then 94c89a4) and their DCO sign-offs. The integration merge carries Co-authored-by: amy-why-3459 <wuhaiyan17@huawei.com> and a contributor DCO sign-off. No squash or history rewrite. Four ordered DCO-signed modularization/documentation commits (3f1d72f, 5542bca, da842f5, ab343f9) are appended after the NPU merge; all previous commits retain their identity and order. Documentation/example cleanup is appended in 168c81f with DCO. Knowledge consolidation is appended in 3e1eb20 with DCO; all earlier commits remain unchanged.

Problem and resulting behavior

Refs ThinkFlowLab/OmniRSI#1 and acceptance issue #3. This PR adds a CLI experiment/knowledge workbench that runs real baseline, candidate and independent validation commands, records source/environment identities and alternating repeated trials, preserves PASS/FAIL/INCONCLUSIVE, and emits an HTML report. The control package has no inference runtime dependency.

Included

  • Installable Python 3.10+ CLI: doctor, plan/dry-run, run, status/report, knowledge search/show and cited context.

  • Source drift, finite metrics, quality/gain gates, timeout/cancellation and owned-process cleanup.

  • Repository/backend-scoped source-grounded diffusion knowledge and the upstream four CI lanes (draft / ready / merge / nightly).

  • One canonical omnirsi package with concrete Harness, Model and Infra modules, executable RunSpec, portable snapshots and claim/evidence paths; root imports and contracts retain compatibility entrypoints.

  • Review fixes: tracked-source integrity even under an output root, exclusive per-trial output ownership, and durable failed manifests when finalization probes fail.

  • Active Qwen-Image-2.1-Turbo / B300×4 campaign: fixed public model/main revisions, 720p-class native eight-step RGBA PNG workload, profile-first TP/SP qualification and layered RSI, independent RGB/alpha validation and target patch.

  • Maintained model guides cover Qwen-Image-2.1-Turbo on B300 and Ascend. Obsolete LTX plans are removed; byte-for-byte legacy validation snapshots remain as regression fixtures.

  • Imported Ascend 910B1 Qwen-Image measurements, rejected iterations, and an image-generation knowledge entry; README results and a separate Ascend context command. Source attribution and locally_verified=false remain explicit.

  • English README and five consolidated guides: quickstart, architecture, contributing, Qwen B300 and Qwen Ascend. The README now displays two diagrams of the implemented module structure and directory map; the previous English/Chinese design diagrams are preserved unchanged.
  • Documentation and example cleanup

    docs/ is reduced from 26 Markdown files / 1,880 lines to 5 files / 705 lines. B300 reproduction, profiling, the H1–H19 ledger, quality rules and evidence links live in one B300 guide; the Ascend guide preserves author attribution, measured/rejected rounds and the unverified import scope. Quickstart, architecture and a consolidated contribution guide cover the framework.

    examples/ now contains only the Qwen B300 runner, quality validator and historical v4 directory adapter. Synthetic scripts and frozen legacy dependencies move to test fixtures; the final historical patch moves unchanged to its evidence tree. Duplicate patches, old plans, prompts and scaffolding stubs are removed. README/agent/skill/CI links are updated. Historical evidence records and previous commits are unchanged.

    Knowledge organization

    At 3e1eb20, knowledge uses 12 canonical named JSON records and one pack README instead of 12 JSON/README pairs plus a separate index. Each record lives at repo_packs/<repo>/knowledge/<backend>/<component>/<entry>.json; the README explains ownership, retrieval, maintenance and navigation without duplicating findings.

    Repository/backend/component remain the directory hierarchy. Scenario, model, hardware/software prerequisites and tags remain record fields. Backend queries include repository-local common guidance plus that backend's records; they do not inherit another backend's qualification. Path/ID/scope mismatches now fail before retrieval.

    PR/review-thread URLs are removed from every knowledge record and exported context. Repository/revision/date attribution and known authors remain; repository links are explicitly attribution, not raw measurement evidence. open_pr is replaced by upstream_reported as an evidence level, while historical merge status remains source metadata. All records remain imported and locally unverified. IDs, CLI arguments and JSON output field names are preserved.

    Knowledge hierarchy and maintenance guide. Review lessons also now cover independently reviewed/frozen benchmarks and avoiding module tests that duplicate successful E2E coverage. Historical campaign artifacts and measurements are unchanged.

    Implemented modular extension boundary

    The local experiment path now separates shared source/device/process/HTTP infrastructure, Harness scheduling/scenarios/evaluation/reporting, and Model request/metric protocols and image validators. The Qwen runner delegates lifecycle, requests and sample collection to these modules. New scenario, target and hardware adapters reuse the common AB/BA loop, process cleanup and performance adjudication.

    Architecture and extension guide · Module diagram · Directory map · Refactor regression evidence

    Pre-cleanup quality validators and their LTX helper are preserved byte-for-byte under tests/fixtures/legacy/. The current Qwen quality entrypoint now imports the shared artifact utilities directly; its numerical/manifest logic is unchanged and its outputs are regression-tested against the snapshot. New campaigns use fresh helper hashes and frozen references; this refactor does not reinterpret old campaign manifests. The default control installation remains standard-library-only; omnirsi[image] adds optional PNG quality dependencies.

    Measured local Qwen result

    Original-source baseline 384.16 → 266.60 ms E2E: 30.60% reduction, formal PASS for the new 30% target. Against the earliest historical 385.07 ms baseline: 30.76%. Five alternating AB/BA groups, three complete requests per trial, BF16, 1280×704, CFG1, native eight sigmas, TP1/U4/Ring1/VAE1 and full native RGBA PNG/base64 HTTP response. Startup/warmup/profile remain separate. Warm repeated prompts use new seeds; final images and sampled latents are never replayed.

    All 30 timed + 10 first-request images, plus 4 unseen-prompt/seed images including first request, passed the unchanged frozen v4 numerical validator with identical decoded RGB/alpha pixels (SSIM1, PSNR infinity). The final candidate adds exact pointwise/norm/RoPE fusion, an exact VAE norm epilogue, combined byte-preserving QKV exchange and once-per-step native block contract checks. Quantization, approximate cache/attention, resolution and step reductions are not used.

    The first phase2 formal cohort on GPUs 2/5/6/7 achieved 29.81% against its fresh original-source baseline and remains FAIL. A foreign GPU 5 job interrupted follow-up; both sides of the separately qualified successful cohort use GPUs 2/4/6/7 (same NV18/NUMA0). Original baseline source remains f69b1f2b; it is not reset to the phase1 candidate. NVML observed no foreign process on the successful cohort's selected cards. No outside task was terminated.

    Candidate trial means were [264.8543,268.7395,266.6048,261.8247,294.6473] ms; the slower fifth trial remains included. Medians/ranges are descriptive, without a statistical-significance or production-tail claim. Historical comparisons across card cohorts are reported separately.

    Full results and raw means · Active plan with pinned KDA skills · Profile-derived tasks · Complete DCO target patch

    Historical phase1 remains 385.07 → 335.42 ms (12.89%, 20% goal FAIL). Rejected fusions/graphs/broadcast/copy-removal attempts, resource interruptions and both formal cohort verdicts are preserved. The directory adapter corrects only the old v4 aggregate CLI's run-root environment and requires all 40 comparisons; numerical formulas/thresholds and original records are unchanged. Profile-stop API timeouts remain recorded despite exported valid four-rank traces.

    Imported Ascend NPU results

    The Ascend report records amy-why-3459's single-card 910B1 measurements for Qwen-Image-2.1-Turbo, BF16, 1280×704, native eight steps, eager:

    | Author-reported stack | Mean vs 3111.5 ms baseline | Reported quality |
    | --- | ---: | --- |
    | Conditioning reuse + interleaved NPU RoPE | 2459.6 ms (21.0% lower) | Pixel-identical RGBA |
    | Above + opt-in VAE fastpath | 2425.5 ms (22.0% lower) | Quality gate passed; not pixel-identical |

    The 30% target is not met. These three-request means after two warmups are separate from the B300 five-group HTTP campaign. Raw timings, image outputs and a frozen validator are not included in the import, so this is source-reported evidence: status=imported, locally_verified=false, OmniRSI acceptance INCONCLUSIVE. No NPU inference was rerun for this integration. The independent upstream 910B3 report is linked with its own hardware and protocol scope.

    Merge attribution, exact commands, and integration validation.

    How to use

    python -m pip install .
    python -m omnirsi --help
    python -m omnirsi context --repo-type vllm_omni --backend cuda \
      --scenario diffusion.image_generation --output diffusion-context.md
    

    Follow the active plan in a prepared target environment. Freeze new guards/assets/reference before a new campaign, configure exactly four available B300 devices, and run the full schedule for acceptance. Diagnostic profiles can override sigmas to two steps, but have no acceptance metric. Warm repeated-prompt gains do not certify universal cold-prompt speed or production tails.

    Validation

  • Knowledge consolidation 3e1eb20: 135 tests and 60 subtests passed; Ruff, changed-file formatting and whitespace checks pass. All 12 stable IDs and backend/scenario boundaries are retained. A clean noneditable wheel contains exactly 12 knowledge JSON files and one README; search/show/context, synthetic CLI AB/BA, status and report pass without inference dependencies. Context checks return Ascend image=4, CUDA image=3, CUDA video=9 and ROCm video=3 records with no PR links. Stale local build output was removed before the final wheel and its resources match the source tree byte-for-byte. No GPU/NPU measurement was rerun for this catalog-only change.

  • Cleanup 168c81f: 126 passed, 60 subtests, Ruff and changed-range whitespace checks pass. All maintained local Markdown links/anchors resolve and the three Qwen CLI entrypoints load. New full-resolution synthetic RGBA comparisons prove current/frozen validators agree for exact pixels, RGB regressions and alpha regressions; the numerical/manifest AST is unchanged. The two LTX fixtures, frozen Qwen validator and final historical patch preserve their original bytes. This cleanup does not rerun GPU/NPU inference or change historical performance claims.

  • Modular refactor at da842f5 (documentation/evidence head ab343f9): 123 passed, 60 subtests, lint/format and changed-range whitespace checks pass. An independent noneditable wheel includes all 40 Python modules and passes a real external-process CLI AB/BA run, quality-command wiring, source checks, status/report and Ascend context export without inference/image dependencies. Synthetic fixture metrics are not a performance measurement.

  • Fresh 4× B300 functional E2E: pre-refactor 884ea89 and modular da842f5 runners each completed six warmups plus three full native eight-step Qwen requests at 1280×704 on unchanged engine 6550e3f6. Four corresponding native RGBA pairs, including the first response, are pixel-identical. All source/model/helper/dependency checks and owned-process cleanup passed. One-run means were 276.1044 / 276.4625 ms; no new performance claim is made. Result and output-hash summary.

  • Earlier NPU-import control CPU suite at 884ea89: 110 passed, 60 subtests on Python 3.13.12. Ruff and changed-file formatting pass. A noneditable wheel installed into a separate clean environment passes resource checks: 12 knowledge records, with the new Ascend JSON and README included. Installed Ascend image context exports four records; backend/scenario isolation and unverified provenance are covered. Full integration validation. No inference runtime is imported by the control package.

  • Earlier review-fixed vLLM-Omni E2E: pinned base 233f0842 vs head 8310b74b, 60 formal plus 16 smoke/held-out output files identical in corresponding native RGBA checks. Default-base to opt-in PR: 383.2439 → 266.1680 ms (30.5487%); explicit symmem on both sides: 374.1702 → 266.1680 ms (28.8645%). These comparisons remain separate from the frozen historical result above.

  • Review response and accuracy/performance images. Historical downloadable evidence and exact-source bundle, with checksum manifest and an independently executed CPU recomputation.

  • The following target checks describe the original campaign; current upstream validation is linked above.

  • Target CPU checks: 127 passed /14 skips /24 accelerator cases deselected in the broad initial invocation; after H19, 109 relevant model CPU checks passed. Accelerator cases were separately exercised.

  • Exact operator/VAE/FakeTensor checks: 19 passed; after H19, 10 pointwise/shared-modulation checks passed, including its verified path. Four-rank batched QKV exchange was exact for batches 1/2 and local sequences 16/32/880/913.

  • Relevant pre-commit passed: Ruff, mypy3.10, test marks, SPDX, forbidden-import/CUDA and whitespace checks. DCO sign-offs included.

  • The full target patch applies cleanly to frozen source f69b1f2b. Candidate 330d411d2dd567bc061cb3124f4e39d195a4be45 is clean and committed.

  • Five-group source-integrity checks and all 44 final/held-out image comparisons passed. Formal run 20261010T092145Z-61055bbc49: 30.6009% gain, PASS.
  • This PR does not implement automatic Agent invocation, SSH allocation, crash resume or production activation. Git/source/knowledge records keep their actual verification scope.

    Review lessons are in skills/rsi-evidence/SKILL.md, docs/contributing.md and the Qwen B300 guide, and the source-pinned upstream-review-gates knowledge record. Imported guidance remains locally_verified=false; actual GPU measurements are scoped to their evidence records. Main integration removes the obsolete test workflow and retains all four upstream lanes. Both PRs are open for review.

    Diff: 13186 lines (+12457 / -729) across 146 files Reviewer: hsliuustc0106 Review duration: 5891m
    All Vouch review confidence checks passed
    Residual risk 0.09 = Change Risk (0.72) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 13186 lines diff across 146 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.82 · 5 substantive comment(s)
    0.82
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    87%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    40 items
    david6666666 david6666666 commented on Oct 10, 2026 03:49 UTC
    Author

    已按本次要求更新 campaign:720p 档位(默认 1280×704,two-stage 的 64 对齐)/ 20% E2E latency 下降目标。profile 默认用可调的 2+1 steps;正式性能和精度验收保持 8+3 steps、121 帧、24 FPS、BF16、完整 48kHz stereo 音视频和原质量门槛。

    本次 RSI 进度图(绿色是实际完成的准备,橙色是实际阻塞,灰色是尚未执行的优化工作):

    flowchart TD
        A[读取 Issue 1 / PR 2 / Test plan / AGENTS] --> B[本地 4 x B300 + NV18 拓扑确认]
        B --> C[固定 baseline / candidate SHA + 独立 venv]
        C --> D[720p / 20% 协议 + 短 step profile 控制]
        D --> E[CPU 78 / 78 + pre-commit + dry-run 通过]
        E --> F[固定模型 revision 下载: HTTP 401]
        F --> G[待有效 HF 授权或完整本地 snapshot]
        G -.-> H[Canonical reference + 独立重复性]
        H -.-> I[9 cells x 3 trials + A/V quality -> 四卡 winner]
        I -.-> J[先 profile: 相同形状 / 短 steps]
        J -.-> K[按证据分层: 阶段 / 通信布局 / 算子]
        K -.-> L[完整 8+3 A/V trial + 质量检查]
        L -.-> M[5 组 AB/BA + 所有 trial 精度验收]
        M -.->|失败:记录并迭代| J
        M -.->|全部门禁通过:L1/L0 ≤ 0.80| N[接受 20% E2E 收益并沉淀证据]
        classDef done fill:#e6f4ea,stroke:#238636,color:#1f2328
        classDef blocked fill:#fff1dc,stroke:#bf8700,color:#1f2328
        classDef pending fill:#f6f8fa,stroke:#8c959f,color:#57606a
        class A,B,C,D,E done
        class F,G blocked
        class H,I,J,K,L,M,N pending
    

    实际完成:四张 B300 / 275040 MiB / driver 610.43.02 / NV18,固定 source 2f289bb179d85671c116c10208b5c84b5c53f18f,独立 Python 环境和目标源码导入探测;78 项 CPU 测试全部通过且无跳过,包括 FFmpeg A/V 和 Linux 清理回归。修改带 DCO sign-off。

    实际阻塞:Lightricks/LTX-2.5-Diffusers 的 revision a6de4b5354f078db24d9cf4778c14846788aea3d 的 model_index.json 请求返回 401 / GatedRepoError;当前继承的 HF credential 也未通过账号验证。需要在本机恢复有权限的 HF 登录或提供同 revision 完整 cache,才能开始 reference 和 GPU profile。请勿在 PR 或聊天里发布 token。

    当前裁决:INCONCLUSIVE。 尚未进行 GPU profile、性能代码优化、并行 winner 搜索或 E2E 精度验收;baseline/candidate latency 和收益都未知,不能宣称达到 20%。短诊断不会输出性能 metrics,也不能通过正式质量/搜索门禁。原 per-frame SSIM ≥0.99、PSNR ≥35 dB、双声道 NRMSE ≤0.01 和完整输出要求保留。

    更新后的可执行 test plan · 本地状态与证据说明

    本机原始记录目录:/home/zjy/code/david/tmp/ltx25-b300-rsi-20261010/artifacts,含 environment/model-access/status、RSI events、CPU log、版本/设备/拓扑与 dry-run。它是本地证据目录,不是 GitHub 可下载附件。

    david6666666 david6666666 commented on Oct 10, 2026 06:53 UTC
    Author

    Qwen-Image-2.1-Turbo 的本地四卡 RSI 实测已完成:E2E 385.07 → 335.42 ms,降低 12.89%;20% 目标未达到。 最终 5 组 AB/BA,不用短-step profile、单次幸运样本或旧卡组数字作为收益分母。

    flowchart TD
        A["Main f69b1f2 + 固定公开 Turbo snapshot"] --> B["完整 8 steps / 1280×704 / BF16 / CFG1 / RGBA PNG"]
        B --> C["Canonical + repeatability:像素一致"]
        C --> D["先 profile:all-to-all、复制及静态工作热点"]
        D --> E["三种四卡 TP/SP 配置复测 + RGB/alpha 门禁"]
        E --> F["TP1/U4 合格;TP2/U2 与 TP4/U1 精度失败排除"]
        F --> H1["H1 QKV 打包:无收益,回退"]
        F --> H2["H2 conditioning cache:保留"]
        H2 --> H3["H3 norm/RoPE fusion:完整图像失败,回退"]
        H2 --> H4["H4 shared scale/gate:保留"]
        H4 --> H5["H5 symmetric-memory 通信:保留,字节一致"]
        H5 --> H6["H6/H7 compute graphs:收益不足,移除"]
        H5 --> H8["H8 request-local geometry:保留"]
        H8 --> I["最终 5×AB/BA:385.07 → 335.42 ms"]
        I --> J["40 张最终图 + held-out:SSIM1 / PSNR∞"]
        J --> K["12.89% E2E;20% 门禁 FAIL"]
        classDef keep fill:#e6f4ea,stroke:#238636,color:#1f2328
        classDef reject fill:#fff1dc,stroke:#bf8700,color:#1f2328
        classDef unmet fill:#ffebe9,stroke:#cf222e,color:#1f2328
        class A,B,C,D,E,F,H2,H4,H5,H8,I,J keep
        class H1,H3,H6 reject
        class K unmet
    

    | 验收 | 结果 |
    | --- | --- |
    | 硬件 / 配置 | 同一组 B300 2,5,6,7,TP1/U4/Ring1/VAE1,NV18;250ms GPU 进程监控无重叠 |
    | Baseline 5 次 trial mean | 403.3866 / 379.9109 / 385.0696 / 385.1251 / 382.5984 ms |
    | Candidate 5 次 trial mean | 338.9145 / 334.5113 / 335.4234 / 339.3807 / 333.7038 ms |
    | 质量 | 30 张计时图 + 10 张首请求图 全过;RGB/alpha 解码像素一致 |
    | Held-out | 三个未见 prompt、seeds142–144 加首请求:像素一致 |
    | 校验 | Control 85/85;target CPU42 passed /4 明确 GPU-only skips;四卡 CUDA collective 字节等价通过;完整 pre-commit + DCO |

    精度失败的融合版本即使更快也没有保留;没有减 steps/分辨率、量化、改 sigma/CFG、缓存最终图像或放宽 SSIM/PSNR。最终保留的是精确的静态工作复用和通信重排。初始 GPU0–3 与尝试 GPU4–7 的取消/重叠记录保留,最终数值全部来自重新资格验证的2,5,6,7卡组。

    基础设施记录也保留:默认 compile 启动遇到 s28 错误,正式 B/C 固定 eager;profile 停止接口在四 rank 导出 trace 后超时,诊断不算验收。首次聚合 validation 的 run-root 路径解析失败,冻结 FAIL 记录未改写;随后用同一个未修改的 v4 validator对十个完整 manifest 逐一补验,覆盖40张图。仓库为后续运行修复了该路径和预建目录处理,并加 CPU 回归。最终性能裁决仍为 FAIL,因为12.89%低于20%。

    实测报告与失败迭代 · 新版四卡 plan · 可应用的 target patch

    本机完整证据目录:/home/zjy/code/david/tmp/qwen21-turbo-b300-rsi-20261010。含全部原始请求、模型/源码/guard hashes、4-rank profile、逐轮 patch、GPU 监控、最终报告及独立 quality audit;这些是本地路径,不是 GitHub 下载附件。图为 GitHub 原生 Mermaid 渲染,未提交生成图片。

    david6666666 david6666666 commented on Oct 10, 2026 07:37 UTC
    Author

    Qwen-Image-2.1-Turbo 第一阶段按独立优化假设计数,共 8 轮,最终保留 H2、H4、H5、H8。同一轮的修正版本、重测和资源冲突后的重跑没有另计。

    优化前先做同分辨率 2-step profile,再测试 TP/Ulysses=1/4、2/2、4/1 三种四卡配置。最终选择精度通过的 TP1/Ulysses4;正式 E2E 和精度验收使用原生 8 steps。

    | 顺序 | 优化内容 | 结果与最终处理 |
    | --- | --- | --- |
    | H1:通信合并 | 将 Q/K/V 打包,通过一次 5D all-to-all 交换,减少通信调用次数。 | 精度通过,但打包和拆包开销抵消收益,回退。 |
    | H2:文本条件复用 | 为重复 prompt 缓存确定性的文本 embeddings 和 mask;更换 seed 时重新采样,不缓存图像或 latent。LRU 限制为 16 条、16 MiB。 | 探索阶段约 369.54 ms,像素一致,保留。 |
    | H3:算子融合 | Triton 融合 Q/K RMSNorm 与 RoPE;修正归约顺序、BF16 舍入和复数运算。 | 速度提升,但完整 8-step 图像精度失败,所有版本回退。 |
    | H4:共享 modulation | 将各 Transformer block 重复执行的 token selection、scale 和 gate tanh,提前到每个 denoise step 计算一次。 | 约 360 ms,像素一致,保留。 |
    | H5:通信实现优化 | Blackwell symmetric-memory Ulysses,减少通信启动和布局转换开销;修复 CUDA 扩展头文件冲突。 | 约 347 ms,四卡通信逐元素验证通过,像素一致,保留。 |
    | H6:QKV 局部 CUDA Graph | 捕获 QKV projection、norm、RoPE,通信留在 graph 外。 | 精度通过,但 E2E 收益很小,移除。 |
    | H7:后半段 CUDA Graph | 捕获 attention 后的 residual、norm、modulation 和 FFN。 | 精度通过,但复制和 replay 开销导致变慢,约 352 ms,移除。 |
    | H8:请求内静态几何复用 | 单次生成内复用位置、RoPE、padding mask 和 KV 布局元数据,减少重复构造及 CPU/GPU 同步。 | 探索阶段约 340 ms,像素一致,保留。 |

    探索值来自不同阶段的累积候选,不能直接相加计算收益。第一阶段最终五组 AB/BA:385.07 → 335.42 ms,E2E 延迟降低 12.89%,未达到当时的 20% 目标。最终 40 张图像和额外 4 张未见 prompt/seed 图像,解码 RGB/alpha 像素一致(SSIM=1、PSNR=∞)。适用工作负载为四卡 B300、1280×704、BF16、8 steps、暖机后的重复 prompt 请求。

    按用户的新要求继续第二阶段:重新 profile 当前候选,检查更深的框架/流水线开销,再提取算子融合/Triton 任务,并参考 NVlabs/KDA 与 MiniMax-H3/Sol Engine 的算子优化。新目标为相对最早冻结源码 baseline 降低 30% E2E 延迟,不重置为第一阶段候选。按历史 baseline 385.0696 ms 对应约 269.55 ms;最终仍须同条件新鲜 AB/BA 与完整精度验证。

    第一阶段完整结果

    david6666666 david6666666 commented on Oct 10, 2026 09:36 UTC
    Author

    Qwen-Image-2.1-Turbo 第二阶段的 30% E2E latency 目标已通过。

  • 对最早历史 baseline:385.07 -> 266.60 ms,降低30.76%。

  • 对本次新鲜原始源码 baseline:384.16 -> 266.60 ms,降低30.60%,正式 PASS。

  • 五组完整 AB/BA;四卡 B300,1280x704,BF16,CFG1,原生8个sigma steps,完整原生RGBA PNG/base64 HTTP响应。暖机后重复 prompt、更换 seed;未复用最终图像或采样 latent。

  • 30张测量图 + 10张首请求图 + 4张未见 prompt/seed 图,解码RGB/alpha像素全部一致:SSIM=1、PSNR=infinity。v4数值验证器和0.99/35 dB门槛未修改。
  • 此前H1-H8表格已保留。下面按顺序列出本阶段:10轮代码假设,加1项启动API探查;连同第一阶段累计18轮代码假设。修正版本、重测、资源冲突重跑不另计。

    | 顺序 | 优化内容 | 探索结果 / 处理 |
    | --- | --- | --- |
    | H9 | Triton融合 residual gate乘法/加法、SiLU/乘法,保留BF16中间舍入 | 331.45 ms,像素一致,保留 |
    | H10 | 单独融合RoPE,核对并匹配CUDA复数乘法的FMA顺序 | 327.15 ms,像素一致,保留为fallback路径 |
    | H11 | 保留ATen mean归约,融合Q/K cast/square及normalization/RoPE后处理 | 300.94 ms,像素一致,后被H13替代 |
    | H12 | 在Qwen VAE中复用现有无损vector-norm/Triton epilogue | 280.25 ms,像素一致,保留;卷积/tiling未改 |
    | H13 | 完整融合head128的Q/K norm/RoPE,复现ATen归约树、两次BF16舍入及FMA顺序 | 独立窗口277.44 ms,像素一致,保留;早期失败/慢测记录保留 |
    | H14 | Decode阶段的scale/gate按通道广播 | 283.61 ms,精度通过但无性能收益,回退 |
    | H15 | Q/K/V直接strided staging,一次symmetric-memory交换,再直接拆包 | 去掉H14后265.19 ms;四rank逐元素验证及图像精度通过,保留 |
    | H16 | 跳过空joint query的拼接复制 | 271.52 ms,精度通过但无收益,回退 |
    | H17 | 重排逐元素条件检查,减少重复属性读取 | 359.88 ms,精度通过但未证明收益,回退;同期主机CPU负载峰值108,未将回归归因于单一原因 |
    | H18 | 调研直接复用CompiledKernel启动函数 | 孤立host enqueue6.41 -> 3.95 us,新指针验证通过;没有进入生产候选或E2E收益声明 |
    | H19 | 将原生、未量化、无LoRA/offload的BF16模块条件检查提前到每个denoise step一次 | 新四卡组探索266.47 ms,像素一致;最终五组中位数266.60 ms,保留 |

    探索值属于累积候选,且H19使用单独重新验证的四卡组,不能相加或作为每轮独立增益。

    先重新profile H8,再提取任务。最终同形状、3请求x2-step的profile显示:通信kernel 768 -> 384次;cudaLaunchKernel 10,581 -> 4,173次;H19的逐元素条件检查 576 -> 6次。Profile包含同步和诊断开销,不作为E2E latency。Stop-profile API仍超时,但四rank有效trace已完整导出;诊断FAIL记录保留。

    flowchart TD
        P["H8重新profile:同形状2 steps"] --> A["H9逐元素融合:331.45 ms"]
        A --> B["H10精确RoPE:327.15 ms"]
        B --> C["H11保留ATen归约:300.94 ms"]
        C --> D["H12无损VAE norm:280.25 ms"]
        D --> E["H13完整精确norm/RoPE:277.44 ms"]
        E --> F["H14广播:无收益,回退"]
        F --> G["H15合并QKV:去掉H14后265.19 ms"]
        G --> H["H16空query复制:无收益,回退"]
        H --> I["第一次五组正式验收:29.81%,FAIL保留"]
        I --> J["H17检查重排:未证明收益,回退"]
        J --> K["H18启动API探查:不进入E2E候选"]
        K --> L["H19每step检查一次:新四卡组重新验证"]
        L --> M["第二次五组:384.16至266.60 ms,30.60%,PASS"]
        M --> N["40张正式图与4张新prompt图:像素一致"]
        classDef kept fill:#d9f4df,stroke:#39834a;
        classDef rejected fill:#ffe4dc,stroke:#aa5134;
        classDef probe fill:#eeeeee,stroke:#777777;
        class A,B,D,E,G,L,M,N kept;
        class F,H,I,J rejected;
        class C,K probe;
    

    第一次正式cohort(GPUs2/5/6/7,candidate e873b3d)为382.92 -> 268.77 ms,29.81%,FAIL;40张图精度通过,未改原记录。GPU5后续被外部任务占用,H19尝试被监控取消,然后重新验证 GPUs2/4/6/7(同NV18、NUMA0);本次baseline/candidate固定使用这同一组四卡。原始源码baseline始终是f69b1f2b,没有改成第一阶段候选。

    新五组baseline均值:[384.1617,382.9615,377.6383,386.3696,399.7588] ms;candidate:[264.8543,268.7395,266.6048,261.8247,294.6473] ms。较慢的第五组294.65 ms保留并参与聚合。中位数/范围是描述性统计,未声明统计显著性或生产尾延迟。NVML监控没有发现成功cohort选定卡上的外部计算进程。

    KDA已以固定版本链接进仓库计划,包括KernelWiki与ncu-report SKILL.md。参考了MiniMax-H3/Sol Engine的算子融合方向,优化是否保留由本地profile、完整E2E与精度结果决定。

    完整结果、限制与失败记录 · 按profile提取的任务 · 完整DCO目标补丁

    候选源码:330d411d2dd567bc061cb3124f4e39d195a4be45;正式run:20261010T092145Z-61055bbc49。相关CPU/CUDA检查和pre-commit通过;control CPU套件87 passed。Generated image artifacts没有提交,原始图片/trace/NCU报告保留在本机campaign目录中。

    hsliuustc0106 hsliuustc0106 commented on code on Oct 11, 2026 01:05 UTC
    Code Review
    src/omnirsi/execution.py:1
    @@ -0,0 +1,280 @@
    +"""Local external-command runner for a prepared accelerator machine."""
    +
    +from datetime import datetime, timezone
    +import hashlib
    +import json
    +import os
    +from pathlib import Path
    +import signal
    +import subprocess
    +import time
    +import uuid
    +
    +from .contracts import RunSpec
    +from .evaluation import evaluate, read_metric
    +from .reporting import write_report
    +
    +
    +def _write_json(path: Path, value: object) -> None:
    +    temporary = path.with_suffix(path.suffix + ".tmp")
    +    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
    +    temporary.replace(path)
    +
    +
    +def repository_identity(repo: str | Path, exclude: Path | None = None) -> dict:
    +    """Fingerprint Git revision, tracked diff and nonignored untracked files."""
    +    repo = Path(repo).resolve()
    +    identity = {"path": str(repo), "available": False}
    +    def git(*args: str) -> bytes:
    +        result = subprocess.run(["git", "-C", str(repo), *args], stdout=subprocess.PIPE,
    +                                stderr=subprocess.PIPE, timeout=15, check=False)
    +        if result.returncode:
    +            raise ValueError(result.stderr.decode("utf-8", errors="replace").strip())
    +        return result.stdout
    +    try:
    +        git_root = Path(os.fsdecode(git("rev-parse", "--show-toplevel")).strip()).resolve()
    +        if git_root != repo:
    +            raise ValueError("repo must be the root of its Git checkout")
    +        paths = ["."]
    +        if exclude and Path(exclude).resolve().is_relative_to(git_root):
    +            relative = Path(exclude).resolve().relative_to(git_root).as_posix()
    +            paths.append(f":(top,exclude,literal){relative}")

    [P2] Keep tracked source files in the fingerprint when output_dir overlaps source

    The exclusion removes the entire output directory from the tracked diff, but RunSpec allows an existing source subdirectory as output_dir. I reproduced a run with output_dir=<repo>/src where the candidate changed a tracked src/implementation.py during its trial: the evaluator returned PASS and source_integrity.verified=true despite the source modification. Exclude generated run artifacts while continuing to fingerprint tracked files, or reject output directories that would hide tracked source.

    hsliuustc0106 hsliuustc0106 commented on code on Oct 11, 2026 01:05 UTC
    Code Review
    examples/qwen21_turbo_quality.py:1
    @@ -0,0 +1,112 @@
    +"""Independent PNG accuracy and frozen-protocol gate for Qwen Turbo trials."""
    +import argparse
    +import json
    +import math
    +import os
    +from pathlib import Path
    +import sys
    +
    +import ltx25_b300 as lifecycle
    +
    +
    +def load(path):
    +    value=json.loads(Path(path).read_text())
    +    if value.get('status')!='completed' or value.get('diagnostic') or not value.get('source_integrity',{}).get('verified'):
    +        raise ValueError('Completed non-diagnostic source-stable trial required')
    +    if lifecycle.digest(value['protocol'])!=value['protocol_sha256']:
    +        raise ValueError('Invalid protocol digest')
    +    return value
    +
    +
    +def validate(reference_path,candidate_path,expected_parallel=None):
    +    from PIL import Image
    +    import numpy as np
    +    from skimage.metrics import structural_similarity
    +    ref,cand=load(reference_path),load(candidate_path)
    +    for name in ['protocol','protocol_sha256','protected_sources','guard_hashes','dependency_versions','model_assets_sha256']:
    +        if ref[name]!=cand[name]:raise ValueError(f'Frozen {name} mismatch')
    +    if expected_parallel and (cand['parallel']['tp'],cand['parallel']['ulysses'])!=expected_parallel:
    +        raise ValueError('Frozen winner parallel mismatch')
    +    refs={item['id']:item for item in ref['artifacts'] if item['group']==1}
    +    expected={item['id'] for item in ref['protocol']['prompts']}
    +    if set(refs)!=expected or len(ref['artifacts'])!=3 or len(ref['groups_ms'])!=1:
    +        raise ValueError('Canonical reference coverage mismatch')
    +    groups={item['group'] for item in cand['artifacts']}
    +    if groups!=set(range(1,len(cand['groups_ms'])+1)):raise ValueError('Missing candidate group')
    +    if len(cand['artifacts'])!=len(groups)*len(expected):raise ValueError('Wrong artifact count')
    +    results=[]
    +    seen=set()
    +    pairs = [(item, refs.get(item['id'])) for item in cand['artifacts']]
    +    if cand.get('first_request',{}).get('seed') != ref.get('first_request',{}).get('seed'):
    +        raise ValueError('First-request seed mismatch')
    +    pairs.append(({'group':0,'id':'first-request',**cand['first_request']},ref['first_request']))
    +    for item,other in pairs:
    +        identifier=(item['group'],item['id'])
    +        if identifier in seen or other is None:raise ValueError('Duplicate or unexpected output')

    [P2] Reject reused reference and cross-trial artifact paths

    The seen set checks only group/ID pairs, so distinct identifiers may point to the same image paths, including canonical reference paths. I constructed a two-group candidate manifest pointing entirely to the three reference images and the reference first-request image; validate(reference, candidate, (1,4)) returned PASS for all seven comparisons with zero candidate images. In aggregate mode this permits repeated manifests to stand in for independently generated trial outputs. Require resolved artifacts within their trial directories and reject paths reused across trials or from the reference, including first-request artifacts.

    hsliuustc0106 hsliuustc0106 commented on code on Oct 11, 2026 01:05 UTC
    Code Review
    examples/qwen21_turbo_b300.py:1
    @@ -0,0 +1,262 @@
    +"""Frozen 720p-class Qwen-Image-2.1-Turbo online B300 campaign.
    +
    +Uses only stdlib; the sibling LTX helper supplies generic source/device/process
    +ownership utilities, never LTX requests or model settings.
    +"""
    +import argparse
    +import ast
    +import base64
    +import importlib.metadata
    +import json
    +import os
    +from pathlib import Path
    +import socket
    +from statistics import mean
    +import subprocess
    +import sys
    +import time
    +import urllib.request
    +
    +import ltx25_b300 as lifecycle
    +
    +MODEL = "Qwen/Qwen-Image-2.1-Turbo"
    +REVISION = "d65dbc9a7e8f6b5479e33dee6030eaab2a906509"
    +SIGMAS = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
    +PROMPTS = [
    +    'A photorealistic red fox standing in a snowy forest at dawn, detailed fur, soft sunlight, a wide landscape composition.',
    +    'A clean product photograph of a blue ceramic teapot and two white cups on a wooden table, natural window lighting.',
    +    'A colorful travel poster of a rocky ocean coast at sunset with the exact headline "OCEAN JOURNEY", readable typography.',
    +]
    +HELD_OUT_PROMPTS = [
    +    'A watercolor painting of a yellow bicycle beside a purple flower shop, with three hanging baskets.',
    +    'A studio photograph of a transparent glass vase with five orange tulips on a dark green background.',
    +    'A minimalist book cover reading "NIGHT GARDEN", with silver moonlight and delicate blue flowers.',
    +]
    +PROTECTED_FILES = [
    +    'vllm_omni/model_extras/qwen_image_21.py',
    +    'vllm_omni/entrypoints/openai/diffusion.py',
    +    'vllm_omni/entrypoints/openai/api_server.py',
    +    'vllm_omni/entrypoints/openai/image_api_utils.py',
    +    'vllm_omni/diffusion/distributed/autoencoders/autoencoder_kl_qwenimage21.py',
    +]
    +PROTECTED_METHODS = {'__init__', 'prepare_timesteps', 'prepare_latents', '_pack_latents', '_unpack_latents'}
    +
    +
    +def protocol(diagnostic=False, profile_steps=2, held_out=False):
    +    if not 1 <= profile_steps <= 8:
    +        raise ValueError('Profile steps must be 1..8')
    +    sigmas = [SIGMAS[i * 7 // max(1, profile_steps - 1)] for i in range(profile_steps)] if diagnostic else SIGMAS
    +    return {'model': MODEL, 'model_revision': REVISION, 'width': 1280, 'height': 704,
    +            'dtype': 'bfloat16', 'true_cfg_scale': 1.0, 'sigmas': sigmas,
    +            'attention_backend': 'FLASH_ATTN', 'prefix_kv_cache': 'checkpoint_default_native',
    +            'compile_policy': 'enforce_eager',
    +            'codec': 'PNG', 'response_format': 'b64_json', 'concurrency': 1,
    +            'pixel_mode': 'RGBA', 'output_compression': 100,
    +            'prompts': [{'id': f'prompt-{i:03d}-seed-{(142 if held_out else 42)+i}', 'prompt': p,
    +                         'seed': (142 if held_out else 42)+i} for i,p in enumerate(HELD_OUT_PROMPTS if held_out else PROMPTS)],
    +            'warmup_seeds': [[10042,10043,10044],[11042,11043,11044]],
    +            'timing': 'POST until complete HTTP JSON response downloaded; PNG decode/write outside timer',
    +            'conditioning_scope': 'Repeated prompts with new seeds; deterministic conditioning reuse allowed; final-image reuse forbidden'}
    +
    +
    +def protected_sources(source):
    +    result = {p: lifecycle.sha256(source / p) for p in PROTECTED_FILES}
    +    relative = 'vllm_omni/diffusion/models/qwen_image_21/pipeline_qwen_image_21.py'
    +    tree = ast.parse((source / relative).read_text())
    +    for node in tree.body:
    +        if isinstance(node, ast.FunctionDef) and node.name in {'get_qwen_image_21_pre_process_func', 'get_qwen_image_21_post_process_func'}:
    +            result[relative + ':' + node.name] = lifecycle.digest(ast.dump(node, include_attributes=False))
    +    for node in tree.body:
    +        if isinstance(node, ast.ClassDef) and node.name == 'QwenImage21Pipeline':
    +            found = set()
    +            for method in node.body:
    +                if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)) and method.name in PROTECTED_METHODS:
    +                    result[relative + ':' + method.name] = lifecycle.digest(ast.dump(method, include_attributes=False))
    +                    found.add(method.name)
    +            if found != PROTECTED_METHODS:
    +                raise ValueError('Protected pipeline method missing')
    +            break
    +    else:
    +        raise ValueError('Protected pipeline class missing')
    +    return result
    +
    +
    +def dependencies():
    +    versions = lifecycle.semantic_dependency_versions(lifecycle.dependency_versions())
    +    for name in ['Pillow', 'numpy', 'scikit-image', 'flash-attn-4', 'nvidia-cutlass-dsl', 'kernels']:
    +        versions[name] = importlib.metadata.version(name)
    +    return versions
    +
    +
    +def model_assets(model, cache):
    +    manifest = cache.parent/'artifacts/model-assets.json'
    +    assets = json.loads(manifest.read_text())
    +    if Path(assets['model']).resolve() != model or assets['revision'] != REVISION:
    +        raise ValueError('Model asset manifest does not match the pinned snapshot')
    +    actual = {str(p.relative_to(model)) for p in model.rglob('*') if p.is_file()}
    +    if actual != {item['path'] for item in assets['files']}:
    +        raise ValueError('Model file coverage changed')
    +    for item in assets['files']:
    +        stat = (model/item['path']).stat()
    +        if (stat.st_size, stat.st_mtime_ns) != (item['bytes'], item['mtime_ns']):
    +            raise ValueError('Model asset changed after SHA256 freeze')
    +    return lifecycle.sha256(manifest)
    +
    +
    +def guards():
    +    return {p.name: lifecycle.sha256(p) for p in [Path(__file__), Path(lifecycle.__file__), Path(__file__).with_name('qwen21_turbo_quality.py')]}
    +
    +
    +def image_request(port, item, destination, settings, timeout=900):
    +    body = json.dumps({'model': MODEL, 'prompt': item['prompt'], 'seed': item['seed'], 'n': 1,
    +                       'size': '1280x704', 'response_format': 'b64_json', 'true_cfg_scale': 1.0,
    +                       'sigmas': settings['sigmas'], 'output_format':'png', 'output_compression':100}).encode()
    +    request = urllib.request.Request(f'http://127.0.0.1:{port}/v1/images/generations', body,
    +                                     {'Content-Type': 'application/json'})
    +    start = time.perf_counter()
    +    with urllib.request.urlopen(request, timeout=timeout) as response:
    +        if response.status != 200:
    +            raise ValueError('Image endpoint failed')
    +        data = response.read()
    +    elapsed = 1000 * (time.perf_counter() - start)
    +    images = json.loads(data)['data']
    +    if len(images) != 1:
    +        raise ValueError('Expected exactly one completed image')
    +    png = base64.b64decode(images[0]['b64_json'], validate=True)
    +    if not png.startswith(b'\x89PNG\r\n\x1a\n'):
    +        raise ValueError('Expected lossless PNG')
    +    Path(destination).write_bytes(png)
    +    return elapsed
    +
    +
    +def run(args):
    +    source, output, cache = Path(args.source_repo).resolve(), Path(args.output).resolve(), Path(args.cache_root).resolve()
    +    if output.exists() or output.is_relative_to(source) or cache.is_relative_to(source):
    +        raise ValueError('Use new output and cache paths outside source')
    +    if args.tp * args.ulysses != (1 if args.single_reference else 4) or args.single_reference and (args.tp,args.ulysses)!=(1,1):
    +        raise ValueError('Four workers required, except explicit canonical reference')
    +    model = Path(args.model_path).resolve()
    +    if model.name != REVISION or json.loads((model/'model_index.json').read_text())['sample_sigmas'] != SIGMAS:
    +        raise ValueError('Exact pinned snapshot and Turbo schedule required')
    +    output.parent.mkdir(parents=True, exist_ok=True)
    +    media = output.parent/'media'
    +    media.mkdir()
    +    settings = protocol(args.diagnostic, args.profile_steps, args.held_out)
    +    before = lifecycle.source_snapshot(source)
    +    frozen = protected_sources(source)
    +    frozen_guards = guards()
    +    versions = dependencies()
    +    asset_hash = model_assets(model, cache)
    +    argv = [str(Path(sys.executable).parent/'vllm'), 'serve', str(model), '--served-model-name', MODEL,
    +            '--omni', '--enforce-eager', '--dtype', 'bfloat16', '--num-gpus', str(args.tp*args.ulysses),
    +            '--tensor-parallel-size', str(args.tp), '--usp', str(args.ulysses), '--ring', '1',
    +            '--cfg-parallel-size', '1', '--vae-patch-parallel-size', '1', '--max-num-seqs', '1',
    +            '--diffusion-attention-backend', 'FLASH_ATTN', '--host', '127.0.0.1', '--port', str(args.port),
    +            '--stage-init-timeout', str(args.startup_timeout)]
    +    if args.diagnostic:
    +        argv += ['--profiler-config', json.dumps({'profiler':'torch','torch_profiler_dir':str(output.parent/'torch-profile'),
    +                  'torch_profiler_record_shapes':True,'torch_profiler_with_stack':True}),
    +                 '--enable-diffusion-pipeline-profiler']
    +    record = {'status':'running','protocol':settings,'protocol_sha256':lifecycle.digest(settings),
    +              'diagnostic':args.diagnostic,'parallel':{'tp':args.tp,'ulysses':args.ulysses,'vae':1,'cfg':1,'ring':1},
    +              'source_before':before,'protected_sources':frozen,'guard_hashes':frozen_guards,
    +              'dependency_versions':versions,'model_assets_sha256':asset_hash,
    +              'server_argv':argv,'samples_ms':[],'artifacts':[],'groups_ms':[],'warmup_samples_ms':[]}
    +    process = ownership = None
    +    try:
    +        record['devices'] = lifecycle.preflight()
    +        with socket.socket() as probe:
    +            if probe.connect_ex(('127.0.0.1',args.port)) == 0:
    +                raise ValueError('Port already occupied')
    +        env = os.environ.copy()
    +        env.pop('HF_TOKEN',None)
    +        env['PYTHONPATH'] = str(source)
    +        env['PYTHONDONTWRITEBYTECODE'] = '1'
    +        env['HF_HUB_OFFLINE'] = '1'
    +        env['HF_HOME'] = str(cache/'huggingface')
    +        env['HF_MODULES_CACHE'] = str(cache/'huggingface/modules')
    +        for key, folder in [('TORCHINDUCTOR_CACHE_DIR','inductor'),('TRITON_CACHE_DIR','triton'),('VLLM_CACHE_ROOT','vllm'),('CUDA_CACHE_PATH','cuda')]:
    +            env[key] = str(cache/folder)
    +        preparation_start = time.monotonic()
    +        with (output.parent/'server.log').open('wb') as log:
    +            process, ownership = lifecycle.launch_server(argv,source,env,log)
    +            record['server_process'] = ownership
    +            deadline = time.monotonic()+args.startup_timeout
    +            while True:
    +                if process.poll() is not None:
    +                    raise ValueError('Server exited before readiness; see server.log')
    +                try:
    +                    with urllib.request.urlopen(f'http://127.0.0.1:{args.port}/health',timeout=2) as response:
    +                        if response.status == 200: break
    +                except (OSError,TimeoutError): pass
    +                if time.monotonic()>deadline: raise TimeoutError('Server readiness timeout')
    +                time.sleep(1)
    +            record['process_to_ready_s'] = time.monotonic()-preparation_start
    +            for seeds in settings['warmup_seeds']:
    +                for item,seed in zip(settings['prompts'],seeds):
    +                    path=media/'warmup.png'
    +                    latency = image_request(args.port,{**item,'seed':seed},path,settings)
    +                    record['warmup_samples_ms'].append({'prompt':item['prompt'],'seed':seed,'latency_ms':latency})
    +                    if 'first_request' not in record:
    +                        first = media/'first-request.png'
    +                        path.rename(first)
    +                        record['first_request']={'path':str(first),'sha256':lifecycle.sha256(first),'seed':seed,'latency_ms':latency}
    +                        continue
    +                    path.unlink()
    +            if args.diagnostic:
    +                urllib.request.urlopen(urllib.request.Request(f'http://127.0.0.1:{args.port}/start_profile',data=b''),timeout=60).close()
    +            for group in range(args.repetitions):
    +                values=[]
    +                for item in settings['prompts']:
    +                    path=media/f"group-{group+1:03d}-{item['id']}.png"
    +                    latency=image_request(args.port,item,path,settings)
    +                    values.append(latency)
    +                    record['samples_ms'].append({'group':group+1,'id':item['id'],'latency_ms':latency})
    +                    record['artifacts'].append({'group':group+1,'id':item['id'],'path':str(path),'sha256':lifecycle.sha256(path)})
    +                    print(json.dumps({'group':group+1,'id':item['id'],'latency_ms':latency}),flush=True)
    +                record['groups_ms'].append(mean(values))
    +            if args.diagnostic:
    +                urllib.request.urlopen(urllib.request.Request(f'http://127.0.0.1:{args.port}/stop_profile',data=b''),timeout=120).close()
    +            else: record['metrics']={'latency_ms':mean(record['groups_ms'])}
    +            record['status']='completed'
    +    except KeyboardInterrupt:
    +        record.update(status='cancelled',error='interrupted')
    +    except Exception as error:
    +        record.update(status='failed',error=str(error))
    +    finally:
    +        if process is not None:
    +            record['server_cleanup']=lifecycle.stop_server(process,ownership,20)
    +            if record['server_cleanup']['remaining_pids']:
    +                record.update(status='failed',error='Owned processes remain')
    +        after=lifecycle.source_snapshot(source)

    [P2] Preserve the trial manifest when final integrity checks fail

    Cleanup and source/guard/dependency/model checks run in finally without their own exception handling. If source_snapshot becomes unavailable, a protected file disappears, a dependency is removed, or model_assets raises on drift, execution exits before write_json(output, record). I reproduced source_snapshot raising on its final call and observed no result.json. Capture cleanup/integrity exceptions as failed evidence and ensure the final manifest write still runs, as the LTX helper already does.

    hsliuustc0106 hsliuustc0106 requested changes on Oct 11, 2026 01:05 UTC
    Changes Requested Reviewer

    Reviewed commit c1bcf5d. Three correctness issues need fixes before merging; each is described inline with a CPU reproduction.

    Validation: all 87 CPU tests passed, and the wheel built successfully. All three findings were reproduced with temporary CPU fixtures. GPU kernels and the reported 30.60% improvement remain independently unverified in this review: the raw experiment artifacts are on the author's machine.

    hsliuustc0106 hsliuustc0106 commented on Oct 11, 2026 15:49 UTC
    Contributor

    Thanks for this work. To get it onto main and let anyone reproduce the #3 verdict, could you:
    1. Rebase onto current main, keep omnirsi as the package, and fold rsi_scaffold's runspec, claim and evidence_paths into it. Your test.yml gives way to the four CI lanes.
    2. Change "Closes #1" to "Refs #1", since #1 is the roadmap.
    3. Share the campaign evidence tarball (attach it or link it): the 44 images plus the raw baseline and candidate trial metrics, so 30.60% can be recomputed. A maintainer will publish it as the release asset and commit the SHA-256 manifest.

    Dong1017 Dong1017 commented on Oct 12, 2026 05:03 UTC
    Contributor

    I ran an independent four-H200 check of the campaign patch. Both baseline and candidate completed full image generation, but the candidate failed the quality gates.

    Tested source: baseline f69b1f2b19cece03f6736c7da093ea25de0e24fd plus the complete phase-2 patch shipped in OmniRSI c1bcf5d. I could not fetch the declared candidate commit 330d411d, so this result is bound to the shipped patch.

    Both sides used the same four H200s, model revision d65dbc9a7e8f6b5479e33dee6030eaab2a906509, TP1/Ulysses4/Ring1/VAE1, BF16, 1280×704, CFG1, native eight sigmas, eager execution, and complete RGBA PNG/base64 HTTP responses. Runtime: PyTorch 2.13.0+cu130, vLLM 0.31.0, Triton 3.7.1, FA3. Validation used the unchanged numerical validator checked into c1bcf5d; the historical frozen v4 validator was unavailable.

    | Check | Result |
    |---|---|
    | Four-card baseline reference and independent repeat | Pixel-identical RGB/alpha |
    | First AB pair: three timed requests per side after six warmups | Baseline 721.95 ms; candidate 562.68 ms |
    | Candidate vs baseline pixels | Not identical |
    | Teapot RGB SSIM | 0.988293 < 0.99 |
    | First-request RGB SSIM / PSNR | 0.986242 < 0.99; 32.806 dB < 35 dB |

    The first pair showed a descriptive 22.06% latency reduction, but quality failed. I stopped before the remaining five-group schedule and held-out checks; this is not an accepted performance result. Source integrity checks passed, and owned server processes exited cleanly.

    For vllm-project/vllm-omni#8739 at 443b3e97, pointwise.py is byte-identical to the tested patch, and qk_norm.py differs only in type annotations. However, that PR is ported onto a newer base, and its current head has not been directly tested here.

    Please investigate the candidate’s Hopper numerical behavior. The original B300 #3 verdict remains independently unverified; please also provide the requested campaign evidence bundle, including raw baseline/candidate metrics, all output and canonical/reference images, manifests, and frozen validators, so the 30.60% and 44/44 claims can be checked independently.

    david6666666 david6666666 commented on Oct 12, 2026 06:46 UTC
    Author

    Review fixes, scaffold integration, and upstream feedback

    Addressed the three reproduced harness findings in 497f30bfce7c894030669666b55f7e290ccdf38d, with the review/evidence follow-up in c05f0e1c8664d17bf91a60a3c66ed9e18fb86a07. The branch integrates main 1eae6e73c8a08c29b91eea4a3b0f2167554fc29b; conflicts are resolved and both histories are retained. Refs #1 and the frozen acceptance issue #3; this work does not close the full roadmap.

    | Review finding | Correction | Regression evidence |
    | --- | --- | --- |
    | An output root under source hid tracked mutations | Always fingerprint tracked files; exclude only untracked generated files under the active run directory | The old candidate incorrectly passed; the same source-mutation case now becomes INCONCLUSIVE with failed source integrity |
    | Reference aliases or reused image paths could stand in for independent outputs | Resolve images within their owning trial; reject reference aliases, repeated paths and cross-trial reuse, including first-request images | The old aliases passed; negative ownership regressions now reject them before numerical validation |
    | Final cleanup/integrity exceptions erased the trial manifest | Capture each finalizer/probe failure, mark unavailable integrity evidence, and still write the failed result | The old final-probe exception lost result.json; regression now preserves the failed manifest and error |

    Main's portable scaffold is integrated into the single omnirsi package: canonical RunSpec with executable argv and revision/backend/device/model/scenario snapshots, claim enum, evidence paths, and SIAS seams. The former contracts import remains a compatibility alias; no duplicate rsi_scaffold package remains. The draft / ready / merge / nightly workflows remain, and the obsolete test.yml is removed. Campaign pins stay in evidence, not shared skill/workflow defaults.

    Local validation: 109 pytest tests passed with 58 subtests; separate unittest discovery passed 93 tests (overlapping scopes). Ruff/format passed, wheel build and a fresh noneditable install passed, and all 11 source-grounded knowledge records ship in the wheel. Control imports do not load torch/vLLM/vLLM-Omni. The whitespace check excludes unchanged frozen format-patch artifacts because their context/signature spaces are patch data. These are scaffold checks, not GPU campaign acceptance.

    Lessons fed back from vLLM-Omni #8739

    The upstream review response, fresh E2E matrix, and three accuracy/performance figures document the fixes at 8310b74b:

  • Keep optional compiler/NCCL/symmetric-memory requirements explicitly opt-in; never fall back independently on ranks after collective communication starts.

  • Tie geometry/KV lifetime to each request; exercise success, error, interruption and dropped step requests, without discarding reusable graph buffers.

  • Put reusable exact Triton/math helpers in shared layers; validate every consumer after a move, retaining model-specific policy in adapters.

  • Check in a model-neutral benchmark client; publish native outputs and raw timings with checksums, and normalize private storage paths only in publication copies.

  • Keep historical claims separate from a newly measured base/head, and report configuration changes separately from a same-configuration code comparison.
  • These lessons are incorporated in skills/rsi-evidence/SKILL.md, docs/upstream-review-response.md, and the source-pinned upstream-review-gates knowledge record. The imported record remains locally_verified=false; it is guidance supported by review sources, not a universal performance claim.

    Downloadable historical evidence

    The staging release now provides:

  • Evidence archive: 11,699,006 bytes, SHA-256 22c654050def3535dab8b73541856419e4a606dd98d01004229953d873e07531.

  • Exact candidate Git bundle, restoring frozen 330d411d from prerequisite f69b1f2b.

  • Asset checksum manifest.
  • The archive includes all 44 tested PNGs and eight canonical reference paths, raw per-request baseline/candidate timings, source/execution records, frozen validators and full patch. Tar hardlinks deduplicate identical PNG payloads for packaging only. Public downloads were checksum-verified. python recompute.py was executed successfully after extraction: 384.1617233507956 → 266.6048333436872 ms, 30.600885736802542% reduction, 44 identical native-image checks. Original records, frozen numerical thresholds and the earlier failed cohort's verdict remain unchanged. Storage paths are normalized in publication copies. Full profiler traces are not claimed as included.

    evidence/qwen21-turbo-b300-20261010/results/archive-manifest.json records the URLs/checksums and source-bundle prerequisite. Assets are staged in the fork for the maintainer's requested upstream-release mirror; no upstream mirror is claimed to exist yet.

    Separate review-fixed E2E result

    Pinned vLLM-Omni base 233f0842, head 8310b74b, B300×4, BF16, 1280×704 native eight steps, CFG1, TP1/U4/Ring1/VAE1, eager, full JSON/base64 PNG response, concurrency1. Each arm has five fresh-server trials, six full warmups and three timed requests per trial; all samples are retained.

    | Comparison | Median E2E | Reduction |
    | --- | ---: | ---: |
    | Pinned main default → PR explicit symmem recipe |383.2439 →266.1680 ms |30.5487% |
    | Explicit symmem on both sides; code-only |374.1702 →266.1680 ms |28.8645% |

    All60 formal output files plus16 additional smoke/held-out files are identical in their corresponding full native RGB/alpha checks. These are output-file counts, not independent pair counts. The first comparison includes an explicit communication-setting change; neither comparison establishes statistical significance or tail-latency gains. Raw per-request values and scope are committed in evidence/qwen21-turbo-b300-review-20261012/results/summary.json. This matrix is separate from issue3's frozen historical acceptance result.

    AI assistance: Codex prepared the fixes, executed the checks and measurements, and drafted this response. Both PRs remain drafts for human review; no completed human approval or upstream GPU CI pass is claimed.

    david6666666 david6666666 commented on code on Oct 12, 2026 06:47 UTC
    Code Review
    src/omnirsi/execution.py:1
    @@ -0,0 +1,280 @@
    +"""Local external-command runner for a prepared accelerator machine."""
    +
    +from datetime import datetime, timezone
    +import hashlib
    +import json
    +import os
    +from pathlib import Path
    +import signal
    +import subprocess
    +import time
    +import uuid
    +
    +from .contracts import RunSpec
    +from .evaluation import evaluate, read_metric
    +from .reporting import write_report
    +
    +
    +def _write_json(path: Path, value: object) -> None:
    +    temporary = path.with_suffix(path.suffix + ".tmp")
    +    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
    +    temporary.replace(path)
    +
    +
    +def repository_identity(repo: str | Path, exclude: Path | None = None) -> dict:
    +    """Fingerprint Git revision, tracked diff and nonignored untracked files."""
    +    repo = Path(repo).resolve()
    +    identity = {"path": str(repo), "available": False}
    +    def git(*args: str) -> bytes:
    +        result = subprocess.run(["git", "-C", str(repo), *args], stdout=subprocess.PIPE,
    +                                stderr=subprocess.PIPE, timeout=15, check=False)
    +        if result.returncode:
    +            raise ValueError(result.stderr.decode("utf-8", errors="replace").strip())
    +        return result.stdout
    +    try:
    +        git_root = Path(os.fsdecode(git("rev-parse", "--show-toplevel")).strip()).resolve()
    +        if git_root != repo:
    +            raise ValueError("repo must be the root of its Git checkout")
    +        paths = ["."]
    +        if exclude and Path(exclude).resolve().is_relative_to(git_root):
    +            relative = Path(exclude).resolve().relative_to(git_root).as_posix()
    +            paths.append(f":(top,exclude,literal){relative}")

    Fixed in 497f30b. repository_identity always fingerprints tracked changes, even if output_dir is under source. Only generated untracked artifacts under the active run directory are excluded. The reproduced source-mutation case changed from a false PASS to INCONCLUSIVE with failed source integrity, matching the existing evaluator contract. Regression and complete current test scope: https://github.com/ThinkFlowLab/OmniRSI/pull/2#issuecomment-6119202731.

    david6666666 david6666666 commented on code on Oct 12, 2026 06:47 UTC
    Code Review
    examples/qwen21_turbo_quality.py:1
    @@ -0,0 +1,112 @@
    +"""Independent PNG accuracy and frozen-protocol gate for Qwen Turbo trials."""
    +import argparse
    +import json
    +import math
    +import os
    +from pathlib import Path
    +import sys
    +
    +import ltx25_b300 as lifecycle
    +
    +
    +def load(path):
    +    value=json.loads(Path(path).read_text())
    +    if value.get('status')!='completed' or value.get('diagnostic') or not value.get('source_integrity',{}).get('verified'):
    +        raise ValueError('Completed non-diagnostic source-stable trial required')
    +    if lifecycle.digest(value['protocol'])!=value['protocol_sha256']:
    +        raise ValueError('Invalid protocol digest')
    +    return value
    +
    +
    +def validate(reference_path,candidate_path,expected_parallel=None):
    +    from PIL import Image
    +    import numpy as np
    +    from skimage.metrics import structural_similarity
    +    ref,cand=load(reference_path),load(candidate_path)
    +    for name in ['protocol','protocol_sha256','protected_sources','guard_hashes','dependency_versions','model_assets_sha256']:
    +        if ref[name]!=cand[name]:raise ValueError(f'Frozen {name} mismatch')
    +    if expected_parallel and (cand['parallel']['tp'],cand['parallel']['ulysses'])!=expected_parallel:
    +        raise ValueError('Frozen winner parallel mismatch')
    +    refs={item['id']:item for item in ref['artifacts'] if item['group']==1}
    +    expected={item['id'] for item in ref['protocol']['prompts']}
    +    if set(refs)!=expected or len(ref['artifacts'])!=3 or len(ref['groups_ms'])!=1:
    +        raise ValueError('Canonical reference coverage mismatch')
    +    groups={item['group'] for item in cand['artifacts']}
    +    if groups!=set(range(1,len(cand['groups_ms'])+1)):raise ValueError('Missing candidate group')
    +    if len(cand['artifacts'])!=len(groups)*len(expected):raise ValueError('Wrong artifact count')
    +    results=[]
    +    seen=set()
    +    pairs = [(item, refs.get(item['id'])) for item in cand['artifacts']]
    +    if cand.get('first_request',{}).get('seed') != ref.get('first_request',{}).get('seed'):
    +        raise ValueError('First-request seed mismatch')
    +    pairs.append(({'group':0,'id':'first-request',**cand['first_request']},ref['first_request']))
    +    for item,other in pairs:
    +        identifier=(item['group'],item['id'])
    +        if identifier in seen or other is None:raise ValueError('Duplicate or unexpected output')

    Fixed in 497f30b. Resolved image paths must belong to their own trial and be unique within and across trials; canonical-reference aliases and reused first-request images are rejected. Ownership checks run before numerical comparison. Added negative regressions for the reproduced alias/reuse cases; the frozen numeric thresholds remain unchanged. Details: https://github.com/ThinkFlowLab/OmniRSI/pull/2#issuecomment-6119202731.

    david6666666 david6666666 commented on code on Oct 12, 2026 06:47 UTC
    Code Review
    examples/qwen21_turbo_b300.py:1
    @@ -0,0 +1,262 @@
    +"""Frozen 720p-class Qwen-Image-2.1-Turbo online B300 campaign.
    +
    +Uses only stdlib; the sibling LTX helper supplies generic source/device/process
    +ownership utilities, never LTX requests or model settings.
    +"""
    +import argparse
    +import ast
    +import base64
    +import importlib.metadata
    +import json
    +import os
    +from pathlib import Path
    +import socket
    +from statistics import mean
    +import subprocess
    +import sys
    +import time
    +import urllib.request
    +
    +import ltx25_b300 as lifecycle
    +
    +MODEL = "Qwen/Qwen-Image-2.1-Turbo"
    +REVISION = "d65dbc9a7e8f6b5479e33dee6030eaab2a906509"
    +SIGMAS = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
    +PROMPTS = [
    +    'A photorealistic red fox standing in a snowy forest at dawn, detailed fur, soft sunlight, a wide landscape composition.',
    +    'A clean product photograph of a blue ceramic teapot and two white cups on a wooden table, natural window lighting.',
    +    'A colorful travel poster of a rocky ocean coast at sunset with the exact headline "OCEAN JOURNEY", readable typography.',
    +]
    +HELD_OUT_PROMPTS = [
    +    'A watercolor painting of a yellow bicycle beside a purple flower shop, with three hanging baskets.',
    +    'A studio photograph of a transparent glass vase with five orange tulips on a dark green background.',
    +    'A minimalist book cover reading "NIGHT GARDEN", with silver moonlight and delicate blue flowers.',
    +]
    +PROTECTED_FILES = [
    +    'vllm_omni/model_extras/qwen_image_21.py',
    +    'vllm_omni/entrypoints/openai/diffusion.py',
    +    'vllm_omni/entrypoints/openai/api_server.py',
    +    'vllm_omni/entrypoints/openai/image_api_utils.py',
    +    'vllm_omni/diffusion/distributed/autoencoders/autoencoder_kl_qwenimage21.py',
    +]
    +PROTECTED_METHODS = {'__init__', 'prepare_timesteps', 'prepare_latents', '_pack_latents', '_unpack_latents'}
    +
    +
    +def protocol(diagnostic=False, profile_steps=2, held_out=False):
    +    if not 1 <= profile_steps <= 8:
    +        raise ValueError('Profile steps must be 1..8')
    +    sigmas = [SIGMAS[i * 7 // max(1, profile_steps - 1)] for i in range(profile_steps)] if diagnostic else SIGMAS
    +    return {'model': MODEL, 'model_revision': REVISION, 'width': 1280, 'height': 704,
    +            'dtype': 'bfloat16', 'true_cfg_scale': 1.0, 'sigmas': sigmas,
    +            'attention_backend': 'FLASH_ATTN', 'prefix_kv_cache': 'checkpoint_default_native',
    +            'compile_policy': 'enforce_eager',
    +            'codec': 'PNG', 'response_format': 'b64_json', 'concurrency': 1,
    +            'pixel_mode': 'RGBA', 'output_compression': 100,
    +            'prompts': [{'id': f'prompt-{i:03d}-seed-{(142 if held_out else 42)+i}', 'prompt': p,
    +                         'seed': (142 if held_out else 42)+i} for i,p in enumerate(HELD_OUT_PROMPTS if held_out else PROMPTS)],
    +            'warmup_seeds': [[10042,10043,10044],[11042,11043,11044]],
    +            'timing': 'POST until complete HTTP JSON response downloaded; PNG decode/write outside timer',
    +            'conditioning_scope': 'Repeated prompts with new seeds; deterministic conditioning reuse allowed; final-image reuse forbidden'}
    +
    +
    +def protected_sources(source):
    +    result = {p: lifecycle.sha256(source / p) for p in PROTECTED_FILES}
    +    relative = 'vllm_omni/diffusion/models/qwen_image_21/pipeline_qwen_image_21.py'
    +    tree = ast.parse((source / relative).read_text())
    +    for node in tree.body:
    +        if isinstance(node, ast.FunctionDef) and node.name in {'get_qwen_image_21_pre_process_func', 'get_qwen_image_21_post_process_func'}:
    +            result[relative + ':' + node.name] = lifecycle.digest(ast.dump(node, include_attributes=False))
    +    for node in tree.body:
    +        if isinstance(node, ast.ClassDef) and node.name == 'QwenImage21Pipeline':
    +            found = set()
    +            for method in node.body:
    +                if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)) and method.name in PROTECTED_METHODS:
    +                    result[relative + ':' + method.name] = lifecycle.digest(ast.dump(method, include_attributes=False))
    +                    found.add(method.name)
    +            if found != PROTECTED_METHODS:
    +                raise ValueError('Protected pipeline method missing')
    +            break
    +    else:
    +        raise ValueError('Protected pipeline class missing')
    +    return result
    +
    +
    +def dependencies():
    +    versions = lifecycle.semantic_dependency_versions(lifecycle.dependency_versions())
    +    for name in ['Pillow', 'numpy', 'scikit-image', 'flash-attn-4', 'nvidia-cutlass-dsl', 'kernels']:
    +        versions[name] = importlib.metadata.version(name)
    +    return versions
    +
    +
    +def model_assets(model, cache):
    +    manifest = cache.parent/'artifacts/model-assets.json'
    +    assets = json.loads(manifest.read_text())
    +    if Path(assets['model']).resolve() != model or assets['revision'] != REVISION:
    +        raise ValueError('Model asset manifest does not match the pinned snapshot')
    +    actual = {str(p.relative_to(model)) for p in model.rglob('*') if p.is_file()}
    +    if actual != {item['path'] for item in assets['files']}:
    +        raise ValueError('Model file coverage changed')
    +    for item in assets['files']:
    +        stat = (model/item['path']).stat()
    +        if (stat.st_size, stat.st_mtime_ns) != (item['bytes'], item['mtime_ns']):
    +            raise ValueError('Model asset changed after SHA256 freeze')
    +    return lifecycle.sha256(manifest)
    +
    +
    +def guards():
    +    return {p.name: lifecycle.sha256(p) for p in [Path(__file__), Path(lifecycle.__file__), Path(__file__).with_name('qwen21_turbo_quality.py')]}
    +
    +
    +def image_request(port, item, destination, settings, timeout=900):
    +    body = json.dumps({'model': MODEL, 'prompt': item['prompt'], 'seed': item['seed'], 'n': 1,
    +                       'size': '1280x704', 'response_format': 'b64_json', 'true_cfg_scale': 1.0,
    +                       'sigmas': settings['sigmas'], 'output_format':'png', 'output_compression':100}).encode()
    +    request = urllib.request.Request(f'http://127.0.0.1:{port}/v1/images/generations', body,
    +                                     {'Content-Type': 'application/json'})
    +    start = time.perf_counter()
    +    with urllib.request.urlopen(request, timeout=timeout) as response:
    +        if response.status != 200:
    +            raise ValueError('Image endpoint failed')
    +        data = response.read()
    +    elapsed = 1000 * (time.perf_counter() - start)
    +    images = json.loads(data)['data']
    +    if len(images) != 1:
    +        raise ValueError('Expected exactly one completed image')
    +    png = base64.b64decode(images[0]['b64_json'], validate=True)
    +    if not png.startswith(b'\x89PNG\r\n\x1a\n'):
    +        raise ValueError('Expected lossless PNG')
    +    Path(destination).write_bytes(png)
    +    return elapsed
    +
    +
    +def run(args):
    +    source, output, cache = Path(args.source_repo).resolve(), Path(args.output).resolve(), Path(args.cache_root).resolve()
    +    if output.exists() or output.is_relative_to(source) or cache.is_relative_to(source):
    +        raise ValueError('Use new output and cache paths outside source')
    +    if args.tp * args.ulysses != (1 if args.single_reference else 4) or args.single_reference and (args.tp,args.ulysses)!=(1,1):
    +        raise ValueError('Four workers required, except explicit canonical reference')
    +    model = Path(args.model_path).resolve()
    +    if model.name != REVISION or json.loads((model/'model_index.json').read_text())['sample_sigmas'] != SIGMAS:
    +        raise ValueError('Exact pinned snapshot and Turbo schedule required')
    +    output.parent.mkdir(parents=True, exist_ok=True)
    +    media = output.parent/'media'
    +    media.mkdir()
    +    settings = protocol(args.diagnostic, args.profile_steps, args.held_out)
    +    before = lifecycle.source_snapshot(source)
    +    frozen = protected_sources(source)
    +    frozen_guards = guards()
    +    versions = dependencies()
    +    asset_hash = model_assets(model, cache)
    +    argv = [str(Path(sys.executable).parent/'vllm'), 'serve', str(model), '--served-model-name', MODEL,
    +            '--omni', '--enforce-eager', '--dtype', 'bfloat16', '--num-gpus', str(args.tp*args.ulysses),
    +            '--tensor-parallel-size', str(args.tp), '--usp', str(args.ulysses), '--ring', '1',
    +            '--cfg-parallel-size', '1', '--vae-patch-parallel-size', '1', '--max-num-seqs', '1',
    +            '--diffusion-attention-backend', 'FLASH_ATTN', '--host', '127.0.0.1', '--port', str(args.port),
    +            '--stage-init-timeout', str(args.startup_timeout)]
    +    if args.diagnostic:
    +        argv += ['--profiler-config', json.dumps({'profiler':'torch','torch_profiler_dir':str(output.parent/'torch-profile'),
    +                  'torch_profiler_record_shapes':True,'torch_profiler_with_stack':True}),
    +                 '--enable-diffusion-pipeline-profiler']
    +    record = {'status':'running','protocol':settings,'protocol_sha256':lifecycle.digest(settings),
    +              'diagnostic':args.diagnostic,'parallel':{'tp':args.tp,'ulysses':args.ulysses,'vae':1,'cfg':1,'ring':1},
    +              'source_before':before,'protected_sources':frozen,'guard_hashes':frozen_guards,
    +              'dependency_versions':versions,'model_assets_sha256':asset_hash,
    +              'server_argv':argv,'samples_ms':[],'artifacts':[],'groups_ms':[],'warmup_samples_ms':[]}
    +    process = ownership = None
    +    try:
    +        record['devices'] = lifecycle.preflight()
    +        with socket.socket() as probe:
    +            if probe.connect_ex(('127.0.0.1',args.port)) == 0:
    +                raise ValueError('Port already occupied')
    +        env = os.environ.copy()
    +        env.pop('HF_TOKEN',None)
    +        env['PYTHONPATH'] = str(source)
    +        env['PYTHONDONTWRITEBYTECODE'] = '1'
    +        env['HF_HUB_OFFLINE'] = '1'
    +        env['HF_HOME'] = str(cache/'huggingface')
    +        env['HF_MODULES_CACHE'] = str(cache/'huggingface/modules')
    +        for key, folder in [('TORCHINDUCTOR_CACHE_DIR','inductor'),('TRITON_CACHE_DIR','triton'),('VLLM_CACHE_ROOT','vllm'),('CUDA_CACHE_PATH','cuda')]:
    +            env[key] = str(cache/folder)
    +        preparation_start = time.monotonic()
    +        with (output.parent/'server.log').open('wb') as log:
    +            process, ownership = lifecycle.launch_server(argv,source,env,log)
    +            record['server_process'] = ownership
    +            deadline = time.monotonic()+args.startup_timeout
    +            while True:
    +                if process.poll() is not None:
    +                    raise ValueError('Server exited before readiness; see server.log')
    +                try:
    +                    with urllib.request.urlopen(f'http://127.0.0.1:{args.port}/health',timeout=2) as response:
    +                        if response.status == 200: break
    +                except (OSError,TimeoutError): pass
    +                if time.monotonic()>deadline: raise TimeoutError('Server readiness timeout')
    +                time.sleep(1)
    +            record['process_to_ready_s'] = time.monotonic()-preparation_start
    +            for seeds in settings['warmup_seeds']:
    +                for item,seed in zip(settings['prompts'],seeds):
    +                    path=media/'warmup.png'
    +                    latency = image_request(args.port,{**item,'seed':seed},path,settings)
    +                    record['warmup_samples_ms'].append({'prompt':item['prompt'],'seed':seed,'latency_ms':latency})
    +                    if 'first_request' not in record:
    +                        first = media/'first-request.png'
    +                        path.rename(first)
    +                        record['first_request']={'path':str(first),'sha256':lifecycle.sha256(first),'seed':seed,'latency_ms':latency}
    +                        continue
    +                    path.unlink()
    +            if args.diagnostic:
    +                urllib.request.urlopen(urllib.request.Request(f'http://127.0.0.1:{args.port}/start_profile',data=b''),timeout=60).close()
    +            for group in range(args.repetitions):
    +                values=[]
    +                for item in settings['prompts']:
    +                    path=media/f"group-{group+1:03d}-{item['id']}.png"
    +                    latency=image_request(args.port,item,path,settings)
    +                    values.append(latency)
    +                    record['samples_ms'].append({'group':group+1,'id':item['id'],'latency_ms':latency})
    +                    record['artifacts'].append({'group':group+1,'id':item['id'],'path':str(path),'sha256':lifecycle.sha256(path)})
    +                    print(json.dumps({'group':group+1,'id':item['id'],'latency_ms':latency}),flush=True)
    +                record['groups_ms'].append(mean(values))
    +            if args.diagnostic:
    +                urllib.request.urlopen(urllib.request.Request(f'http://127.0.0.1:{args.port}/stop_profile',data=b''),timeout=120).close()
    +            else: record['metrics']={'latency_ms':mean(record['groups_ms'])}
    +            record['status']='completed'
    +    except KeyboardInterrupt:
    +        record.update(status='cancelled',error='interrupted')
    +    except Exception as error:
    +        record.update(status='failed',error=str(error))
    +    finally:
    +        if process is not None:
    +            record['server_cleanup']=lifecycle.stop_server(process,ownership,20)
    +            if record['server_cleanup']['remaining_pids']:
    +                record.update(status='failed',error='Owned processes remain')
    +        after=lifecycle.source_snapshot(source)

    Fixed in 497f30b. Cleanup, source/protected-file/guard/dependency/model checks each capture their failures into the record; unavailable checks remain unverified and the final failed manifest is still written. The reproduced final source_snapshot exception lost its manifest before the fix and now leaves durable failed evidence. Details: https://github.com/ThinkFlowLab/OmniRSI/pull/2#issuecomment-6119202731.

    david6666666 david6666666 commented on Oct 12, 2026 07:30 UTC
    Author

    Rebased while preserving the original commit sequence

    Rebased onto current main 1eae6e73c8a08c29b91eea4a3b0f2167554fc29b. The current tip is 1157c67b415b4fdff58e34a4241b1fdada05aed2. GitHub now reports exactly 8 contributor commits, in their original order; no squash was performed and no upstream main commits are listed as PR changes.

    | Order | Previous commit | Rebased commit | Change |
    | --- | --- | --- | --- |
    | 1 | 7318797d | 2322d9b1 | feat: bootstrap CLI experiment workbench and diffusion knowledge |
    | 2 | 0aa792ff | 0cbb868e | test: add B300 LTX-2.5 parallel search and Codex acceptance campaign |
    | 3 | 631f294f | 3187d0f4 | test: prepare 720p B300 campaign with 20% E2E target and short profiles |
    | 4 | 913992fe | d318d919 | test: add profile-first Qwen Turbo B300 performance campaign |
    | 5 | 9ccafb54 | a3c3c3b2 | perf: record Qwen Turbo B300 RSI results and exact image validation |
    | 6 | c1bcf5d7 | 2d76acb0 | perf: record passing 30 percent Qwen B300 RSI campaign and KDA tasks |
    | 7 | 497f30bf | 7ec56dcc | fix: integrate scaffold and enforce review evidence ownership |
    | 8 | c05f0e1c | 1157c67b | docs: record review lessons and scoped current-base E2E validation |

    Original authors, author dates, subjects and matching DCO sign-offs are preserved. The previous review-fix merge is retained as the seventh, ordinary linear commit. Conflicts in the initial bootstrap were resolved against current main; the review integration and evidence follow-up remain separate, in their original positions.

    The final Git tree is exactly unchanged from former tip c05f0e1: 81d4e94b6b9cb4fd7a2054b31f69bcb2d05bf791. Therefore all code, review fixes, frozen patches, knowledge records, CI lanes and evidence files are retained. This is a history-only update. The CPU suite was also rerun from the new worktree: all109 tests passed. Prior wheel validation remains attributed to its actual tested revision, with byte-identical final content here. The rebase itself makes no new GPU or numerical claim.

    The previous tip has a local backup. The PR branch was updated using an explicit --force-with-lease against c05f0e1, and GitHub reports no merge conflict. Refs #1; the full roadmap remains open.

    The current vLLM-Omni A/B serve, request and benchmark commands are now included in PR8739's English test-plan comment.

    Separate current-head B300 E2E validation

    The ongoing vLLM-Omni validation has completed at base d78d8b13 and candidate d57480f5. No target code was changed during this campaign.

    | Comparison | Median E2E, ms | Reduction | At least30% |
    | --- | ---: | ---: | --- |
    | Default main → default PR |381.9051 →279.8266 |26.7288% |No |
    | Symmem on both sides |374.6460 →264.1940 |29.4817% |No |
    | Default main → explicit-symmem PR recipe |381.9051 →264.1940 |30.8221% |Yes |

    All80 formal output files plus8 held-out files have identical corresponding native1280×704 RGB/alpha. The recipe result includes the explicit communication flag change; it is not a same-configuration code-only gain. All samples remain included, and historical issue3 evidence/verdicts remain unchanged.

    Full English report and images · Complete A/B serve/request/benchmark commands · Downloadable current-head evidence. The public archive SHA256 is 86dac9ce41e4b4442f1a4f3044164395ad6008abe337f5538a196c6c9c1dc5d0; download and CPU recomputation both passed.

    The H200/Hopper quality report remains unresolved. This B300 campaign does not verify or repair Hopper numerical behavior. Publishing a complete evidence bundle addresses availability for independent checking, not an H200 accuracy failure.

    david6666666 david6666666 commented on Oct 12, 2026 08:01 UTC
    Author

    两条人工检视意见均已核对并落实,vllm-omni 修复提交为 b4d22ba511197f96f969dec73776acf877468c03。完整英文修复与验证报告。

    本 PR 新增独立 DCO commit 16393ae4932e80794d110468269cd489c7db7c71,保留之前 8 个 commit 的顺序和内容,目前共 9 个,未 squash。

    沉淀了两条可复用守则:

    1. 框架保持模型无关。 使用已有公共配置,避免在框架 factory 和测试中累积模型名、硬件名、版本号的专用条件链;模型策略和 backend 前置条件归各自组件所有。本次删除冗余 Qwen 自动选择入口,统一使用 --ulysses-a2a-permute。
    2. 共享组件改动必须验证其他消费者。 先列出直接及间接调用者,再将数值、布局、dtype、bias、hooks、梯度和回退契约映射到测试;目标模型的 E2E 成功不能代替其他模型的验证。

    守则已写入 RSI evidence 技能、验收清单、可检索的 upstream-review-gates 经验库和 review-response 文档。OmniRSI 109 项 CPU 测试及 lint 通过。

    上游验证:228 项 CPU 回归通过;Wan CUDA 与 Qwen 套件 1161 通过、2 失败,新增的 36 项 Wan bias/回退测试包含在通过项中。两项 FP16 channels-last encoder norm/cache 失败在未修改的 main 上同样出现,且 main 与候选各自的 fused/unfused 输出字节哈希分别一致,因此没有观察到本 PR 新增的数值偏差。保留这些失败,不修改阈值或标成全套通过。

    修复后四卡 B300 的默认通信及显式 symmem 服务各验证 4 张原生八步图像,共 8 张与 main 基准逐像素一致,源代码/设备独占/清理检查通过。本轮是精度回归,不重新声明性能提升;此前 30.8221% 仍对应 d57480f5 且包含通信配置变化。H200 和预训练 Wan 视频 E2E 不在此次验证范围。

    结构化测试证据与消费者覆盖表包含完整日志、失败归因、原生 PNG 证据包的下载链接及 SHA256。

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 12, 2026 08:47 UTC
    Bot

    <!-- codex-pull-request-review-summary -->

    Codex Review Summary

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-10-12T08:56:46.313624Z">2026-10-12T08:56:46.313624Z</relative-time> | 16393ae | Draft marked ready |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 12, 2026 08:56 UTC
    Code Review
    src/omnirsi/evaluation.py:1
    @@ -0,0 +1,109 @@
    +"""Evidence gates, independent from command execution and Agent assertions."""
    +
    +import math
    +
    +from .claim import Verdict
    +from .runspec import RunSpec
    +
    +
    +def read_metric(result: dict, key: str) -> float:
    +    value = result
    +    for part in key.split("."):
    +        if not isinstance(value, dict) or part not in value:
    +            raise ValueError(f"missing metric: {key}")
    +        value = value[part]
    +    if isinstance(value, bool) or not isinstance(value, (int, float)):
    +        raise ValueError(f"metric {key} must be a number")
    +    if not math.isfinite(value) or value <= 0:
    +        raise ValueError(f"metric {key} must be finite and positive")
    +    return float(value)
    +
    +
    +def _summary(trials: list[dict]) -> dict | None:
    +    values = [trial["metric"] for trial in trials if trial.get("metric") is not None]
    +    if not values:
    +        return None
    +    ordered = sorted(values)
    +    midpoint = len(ordered) // 2
    +    middle = (
    +        ordered[midpoint]
    +        if len(ordered) % 2
    +        else ordered[midpoint - 1] + (ordered[midpoint] - ordered[midpoint - 1]) / 2
    +    )
    +    spread = (max(values) - min(values)) / middle * 100
    +    return {
    +        "values": values,
    +        "median": middle,
    +        "min": min(values),
    +        "max": max(values),
    +        "range_pct_of_median": spread if math.isfinite(spread) else None,
    +    }
    +
    +
    +def evaluate(
    +    spec: RunSpec,
    +    baseline: list[dict],
    +    candidate: list[dict],
    +    validation: dict | None,
    +    integrity: dict | None = None,
    +) -> dict:
    +    failed, incomplete = [], []
    +    for label, trials in (("baseline", baseline), ("candidate", candidate)):
    +        if len(trials) != spec.repetitions:
    +            incomplete.append(
    +                f"{label}: expected {spec.repetitions} trials, recorded {len(trials)}"
    +            )
    +        for index, trial in enumerate(trials, 1):
    +            if trial.get("status") in {"failed", "timeout", "error"}:
    +                failed.append(f"{label} trial {index}: {trial.get('status')}")
    +            elif trial.get("status") != "completed":
    +                incomplete.append(f"{label} trial {index}: {trial.get('status')}")
    +            if trial.get("metric") is None:
    +                incomplete.append(
    +                    f"{label} trial {index}: {trial.get('metric_error') or 'metric missing'}"
    +                )
    +    if validation is None:
    +        incomplete.append("quality validation command was not supplied")
    +    elif validation.get("status") in {"failed", "timeout", "error"}:
    +        failed.append(f"quality validation: {validation.get('status')}")
    +    elif validation.get("status") != "completed":
    +        incomplete.append(f"quality validation: {validation.get('status')}")
    +    if integrity is None or not integrity.get("verified"):
    +        incomplete.append((integrity or {}).get("reason", "source integrity was not verified"))
    +
    +    before, after = _summary(baseline), _summary(candidate)
    +    improvement = None
    +    all_metrics = len(baseline) == len(candidate) == spec.repetitions and all(
    +        t.get("status") == "completed" and t.get("metric") is not None for t in baseline + candidate
    +    )
    +    if all_metrics:
    +        improvement = (after["median"] - before["median"]) / before["median"] * 100
    +        if spec.direction == "minimize":
    +            improvement *= -1
    +        if not math.isfinite(improvement):
    +            improvement = None
    +            incomplete.append("derived improvement is not finite; check metric scale and units")
    +        elif improvement <= 0 or improvement < spec.min_improvement_pct:
    +            failed.append(
    +                f"measured gain {improvement:.6g}% must be positive and meet "
    +                f"{spec.min_improvement_pct:.6g}% threshold"
    +            )
    +    verdict = Verdict.FAIL if failed else Verdict.INCONCLUSIVE if incomplete else Verdict.PASS

    <sub><sub>!P1 Badge</sub></sub> Mark partial executions INCONCLUSIVE

    When a measurement returns failed or timeout, run_experiment stops scheduling the remaining repetitions, so evaluate contains both a failed entry and an incomplete trial-count entry; this precedence nevertheless emits FAIL, meaning (for example) a timeout in trial 1 of 5 becomes a campaign failure even though no comparison completed. Incomplete evidence must take precedence here, while a fully observed gate miss can remain FAIL.

    AGENTS.md reference: AGENTS.md:L44-L44

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 12, 2026 08:56 UTC
    Code Review
    tests/fixtures/legacy/ltx25_quality.py:1
    @@ -0,0 +1,511 @@
    +"""Fail-closed LTX-2.5 artifact guard using stdlib, ffprobe and ffmpeg.
    +
    +Thresholds are this experiment's declared policy, not an official LTX standard.
    +The primary mode compares every baseline/candidate trial to one frozen manifest.
    +"""
    +
    +import argparse
    +from array import array
    +from fractions import Fraction
    +import hashlib
    +import json
    +import math
    +import os
    +from pathlib import Path
    +import re
    +import subprocess
    +import sys
    +import uuid
    +
    +
    +class QualityError(ValueError):
    +    pass
    +
    +
    +def sha256_file(path):
    +    hasher = hashlib.sha256()
    +    with Path(path).open("rb") as stream:
    +        for block in iter(lambda: stream.read(1024 * 1024), b""):
    +            hasher.update(block)
    +    return hasher.hexdigest()
    +
    +
    +def protocol_digest(protocol):
    +    return hashlib.sha256(json.dumps(protocol, sort_keys=True, separators=(",", ":"),
    +                                    ensure_ascii=False, allow_nan=False).encode("utf-8")).hexdigest()
    +
    +
    +def _json(path):
    +    value = json.loads(Path(path).read_text(encoding="utf-8"))
    +    if not isinstance(value, dict):
    +        raise QualityError(f"JSON object required: {path}")
    +    return value
    +
    +
    +def load_manifest(path, expected_artifacts=3):
    +    path = Path(path).resolve()
    +    manifest = _json(path)
    +    if manifest.get("status") != "completed" or manifest.get("diagnostic", False):
    +        raise QualityError(f"completed non-diagnostic trial required: {path}")
    +    helper_hash = manifest.get("helper_sha256")
    +    semantic_hashes = manifest.get("semantic_sources_hashes")
    +    if not isinstance(helper_hash, str) or not re.fullmatch(r"[0-9a-f]{64}", helper_hash):
    +        raise QualityError(f"frozen helper SHA-256 required: {path}")
    +    if not isinstance(semantic_hashes, dict) or not semantic_hashes or any(
    +            not isinstance(name, str) or not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value)
    +            for name, value in semantic_hashes.items()):
    +        raise QualityError(f"frozen semantic source hashes required: {path}")
    +    digest = manifest.get("protocol_sha256")
    +    protocol = manifest.get("protocol")
    +    if not isinstance(protocol, dict) or not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
    +        raise QualityError(f"protocol and protocol_sha256 are required: {path}")
    +    if protocol_digest(protocol) != digest:
    +        raise QualityError(f"protocol digest mismatch: {path}")
    +    for field in ("width", "height", "num_frames", "audio_sample_rate", "audio_channels"):
    +        _number(protocol.get(field), f"protocol {field}", integer=True)
    +    try:
    +        fps = Fraction(str(protocol["fps"]))
    +    except (KeyError, ValueError, ZeroDivisionError) as error:
    +        raise QualityError("protocol fps must be positive") from error
    +    if fps <= 0 or protocol["audio_sample_rate"] != 48000 or protocol["audio_channels"] != 2:
    +        raise QualityError("protocol must declare positive fps and 48kHz stereo audio")
    +    entries = manifest.get("artifacts")
    +    if not isinstance(entries, list) or len(entries) != expected_artifacts:
    +        raise QualityError(f"expected exactly {expected_artifacts} artifacts: {path}")
    +    artifacts, seen_paths = {}, set()
    +    for entry in entries:
    +        if not isinstance(entry, dict):
    +            raise QualityError(f"artifact object required: {path}")
    +        identifier, filename, recorded_hash = entry.get("id"), entry.get("path"), entry.get("sha256")
    +        if not isinstance(identifier, str) or not identifier or identifier in artifacts:
    +            raise QualityError(f"missing or duplicate artifact ID: {path}")
    +        if not isinstance(filename, str) or not filename:
    +            raise QualityError(f"artifact path required: {identifier}")
    +        artifact = Path(filename)
    +        artifact = (path.parent / artifact).resolve() if not artifact.is_absolute() else artifact.resolve()
    +        if not artifact.is_file() or artifact.suffix.lower() != ".mp4":
    +            raise QualityError(f"MP4 artifact missing: {artifact}")
    +        if artifact in seen_paths:
    +            raise QualityError(f"duplicate artifact path: {artifact}")
    +        if not isinstance(recorded_hash, str) or not re.fullmatch(r"[0-9a-f]{64}", recorded_hash):
    +            raise QualityError(f"artifact SHA-256 required: {identifier}")
    +        if sha256_file(artifact) != recorded_hash:
    +            raise QualityError(f"artifact SHA-256 mismatch: {artifact}")
    +        artifacts[identifier] = {"path": artifact, "sha256": recorded_hash}
    +        seen_paths.add(artifact)
    +    return {"source": str(path), "protocol_sha256": digest, "protocol": protocol, "artifacts": artifacts,
    +            "helper_sha256": helper_hash, "semantic_sources_hashes": semantic_hashes,
    +            "dependency_versions": manifest.get("dependency_versions", {})}
    +
    +
    +def load_directory(directory, expected_artifacts=3):
    +    """Convenience mode: recursive MP4 discovery rejects duplicate basenames."""
    +    root = Path(directory).resolve()
    +    if not root.is_dir():
    +        raise QualityError(f"artifact directory missing: {root}")
    +    if (root / "result.json").is_file():
    +        return load_manifest(root / "result.json", expected_artifacts)
    +    artifacts = {}
    +    for path in sorted(root.rglob("*.mp4")):
    +        if path.stem in artifacts:
    +            raise QualityError(f"duplicate artifact basename under {root}: {path.stem}")
    +        artifacts[path.stem] = {"path": path.resolve(), "sha256": sha256_file(path)}
    +    if len(artifacts) != expected_artifacts:
    +        raise QualityError(f"expected exactly {expected_artifacts} MP4 files under {root}")
    +    return {"source": str(root), "protocol_sha256": None, "protocol": None, "artifacts": artifacts}
    +
    +
    +def run_manifests(root):
    +    """Select exact trial directories; never merge repeated basename maps."""
    +    root = Path(root).resolve()
    +    repetitions = _json(root / "run.lock.json").get("repetitions")
    +    if isinstance(repetitions, bool) or not isinstance(repetitions, int) or repetitions < 1:
    +        raise QualityError("run.lock.json must declare positive repetitions")
    +    expected = {f"trial-{index:03d}" for index in range(1, repetitions + 1)}
    +    manifests = []
    +    for side in ("baseline", "candidate"):
    +        directory = root / side
    +        found = {path.name for path in directory.glob("trial-*") if path.is_dir()}
    +        if found != expected:
    +            raise QualityError(f"{side} trial coverage mismatch: expected {sorted(expected)}, found {sorted(found)}")
    +        for name in sorted(expected):
    +            trial = directory / name
    +            record = _json(trial / "execution.json")
    +            if record.get("status") != "completed" or record.get("returncode") != 0:
    +                raise QualityError(f"trial execution did not complete successfully: {trial}")
    +            result = trial / "result.json"
    +            if not result.is_file():
    +                raise QualityError(f"trial result manifest missing: {result}")
    +            manifests.append((f"{side}/{name}", result))
    +    return manifests
    +
    +
    +def _run(argv, evidence, label, timeout):
    +    (evidence / f"{label}.argv.json").write_text(json.dumps(argv, ensure_ascii=False, indent=2), encoding="utf-8")
    +    try:
    +        result = subprocess.run(argv, cwd=evidence, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    +                                timeout=timeout, check=False, shell=False)
    +    except subprocess.TimeoutExpired as error:
    +        (evidence / f"{label}.stderr.log").write_bytes(error.stderr or b"")
    +        raise QualityError(f"tool timed out after {timeout}s: {argv[0]}") from error
    +    (evidence / f"{label}.stdout.log").write_bytes(result.stdout)
    +    (evidence / f"{label}.stderr.log").write_bytes(result.stderr)
    +    if result.returncode:
    +        message = result.stderr.decode("utf-8", errors="replace")[-2000:]
    +        raise QualityError(f"{argv[0]} exited {result.returncode}: {message}")
    +    return result
    +
    +
    +def _number(value, label, integer=False):
    +    if integer and (isinstance(value, bool) or not isinstance(value, (str, int)) or
    +                    not re.fullmatch(r"[0-9]+", str(value))):
    +        raise QualityError(f"{label} must be an integer")
    +    try:
    +        converted = int(value) if integer else float(value)
    +    except (TypeError, ValueError, OverflowError) as error:
    +        raise QualityError(f"invalid {label}: {value}") from error
    +    if isinstance(value, bool) or not math.isfinite(converted) or converted <= 0:
    +        raise QualityError(f"{label} must be finite and positive")
    +    return converted
    +
    +
    +def parse_probe(value):
    +    if not isinstance(value, dict):
    +        raise QualityError("ffprobe JSON object required")
    +    streams = value.get("streams")
    +    if not isinstance(streams, list) or any(not isinstance(stream, dict) for stream in streams):
    +        raise QualityError("ffprobe streams missing")
    +    videos = [stream for stream in streams if stream.get("codec_type") == "video"]
    +    audios = [stream for stream in streams if stream.get("codec_type") == "audio"]
    +    if len(videos) != 1 or len(audios) != 1 or len(streams) != 2:
    +        raise QualityError("exactly one video and one audio stream required")
    +    video, audio = videos[0], audios[0]
    +    try:
    +        fps = Fraction(video["avg_frame_rate"])
    +        nominal_fps = Fraction(video["r_frame_rate"])
    +    except (KeyError, ValueError, ZeroDivisionError) as error:
    +        raise QualityError("invalid video frame rate") from error
    +    if fps <= 0 or nominal_fps <= 0:
    +        raise QualityError("video frame rate must be positive")
    +    parsed = {"width": _number(video.get("width"), "width", True),
    +              "height": _number(video.get("height"), "height", True),
    +              "frames": _number(video.get("nb_read_frames"), "counted video frames", True),
    +              "fps": str(fps), "nominal_fps": str(nominal_fps),
    +              "video_duration": _number(video.get("duration"), "video duration"),
    +              "audio_duration": _number(audio.get("duration"), "audio duration"),
    +              "sample_rate": _number(audio.get("sample_rate"), "sample rate", True),
    +              "channels": _number(audio.get("channels"), "channels", True)}
    +    for name, stream, field in (("video_codec", video, "codec_name"), ("pixel_format", video, "pix_fmt"),
    +                                ("audio_codec", audio, "codec_name"), ("channel_layout", audio, "channel_layout")):
    +        if not isinstance(stream.get(field), str) or not stream[field]:
    +            raise QualityError(f"ffprobe field missing: {field}")
    +        parsed[name] = stream[field]
    +    for name, stream in (("video_start", video), ("audio_start", audio)):
    +        try:
    +            parsed[name] = float(stream["start_time"])
    +        except (KeyError, TypeError, ValueError) as error:
    +            raise QualityError(f"ffprobe field missing/invalid: {name}") from error
    +        if not math.isfinite(parsed[name]):
    +            raise QualityError(f"nonfinite {name}")
    +    return parsed
    +
    +
    +def _probe(path, args, evidence, label):
    +    result = _run([args.ffprobe, "-v", "error", "-count_frames", "-show_streams", "-show_format",
    +                   "-of", "json", str(path)], evidence, label, args.tool_timeout)
    +    if result.stderr.strip():
    +        raise QualityError("ffprobe reported decode errors even though its exit status was zero")
    +    return parse_probe(json.loads(result.stdout))
    +
    +
    +def compare_metadata(reference, candidate):
    +    for key in reference:
    +        if key.endswith("duration") or key.endswith("start"):
    +            matched = math.isclose(reference[key], candidate[key], rel_tol=0, abs_tol=0.001)
    +        else:
    +            matched = reference[key] == candidate[key]
    +        if not matched:
    +            raise QualityError(f"media metadata mismatch for {key}: {reference[key]} vs {candidate[key]}")
    +
    +
    +def check_protocol_metadata(metadata, protocol):
    +    if protocol is None:
    +        return
    +    expected = {"width": int(protocol["width"]), "height": int(protocol["height"]),
    +                "frames": int(protocol["num_frames"]), "fps": str(Fraction(str(protocol["fps"]))),
    +                "nominal_fps": str(Fraction(str(protocol["fps"]))),
    +                "sample_rate": int(protocol["audio_sample_rate"]), "channels": int(protocol["audio_channels"])}
    +    for key, value in expected.items():
    +        if metadata[key] != value:
    +            raise QualityError(f"decoded {key} does not match frozen protocol: {metadata[key]} vs {value}")
    +    expected_duration = expected["frames"] / float(Fraction(expected["fps"]))
    +    # Two video frames or two AAC frames cover latent-grid/codec padding only.
    +    tolerance = max(2 / float(Fraction(expected["fps"])), 2048 / expected["sample_rate"])
    +    for kind in ("video", "audio"):
    +        if abs(metadata[kind + "_duration"] - expected_duration) > tolerance:
    +            raise QualityError(f"{kind} duration does not match frozen protocol: {metadata[kind + '_duration']} vs {expected_duration}")
    +        if abs(metadata[kind + "_start"]) > tolerance:
    +            raise QualityError(f"{kind} start offset violates frozen protocol")
    +    if abs(metadata["video_start"] - metadata["audio_start"]) > tolerance:
    +        raise QualityError("A/V start synchronization violates frozen protocol")
    +
    +
    +def check_pcm_duration(samples, protocol):
    +    if protocol is None:
    +        return
    +    fps = float(Fraction(str(protocol["fps"])))
    +    expected = int(protocol["num_frames"]) / fps
    +    actual = len(samples) / (int(protocol["audio_channels"]) * int(protocol["audio_sample_rate"]))
    +    tolerance = max(2 / fps, 2048 / int(protocol["audio_sample_rate"]))
    +    if abs(actual - expected) > tolerance:
    +        raise QualityError(f"decoded audio duration does not match frozen protocol: {actual} vs {expected}")
    +
    +
    +def video_stats(path, key, frames, allow_infinity=False):
    +    values = []
    +    for index, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
    +        fields = dict(re.findall(r"([A-Za-z_]+):([^\s]+)", line))
    +        if fields.get("n") != str(index) or key not in fields:
    +            raise QualityError(f"missing or unordered per-frame {key} evidence")
    +        try:
    +            value = float(fields[key])
    +        except ValueError as error:
    +            raise QualityError(f"malformed {key} evidence") from error
    +        if (not math.isfinite(value) and not (allow_infinity and value == math.inf)) or value < 0:
    +            raise QualityError(f"invalid per-frame {key}: {value}")
    +        if key == "All" and value > 1:
    +            raise QualityError(f"invalid per-frame SSIM: {value}")
    +        values.append(value)
    +    if len(values) != frames:
    +        raise QualityError(f"per-frame {key} count mismatch: expected {frames}, found {len(values)}")
    +    return values
    +
    +
    +def audio_nrmse(reference, candidate):
    +    if not reference or len(reference) != len(candidate) or len(reference) % 2:
    +        raise QualityError("decoded 48kHz stereo PCM length mismatch or empty output")
    +    if any(not math.isfinite(sample) for sample in reference) or any(not math.isfinite(sample) for sample in candidate):
    +        raise QualityError("nonfinite decoded PCM sample")
    +    channels = []
    +    for index in range(2):
    +        before, after = reference[index::2], candidate[index::2]
    +        reference_energy = math.fsum(sample * sample for sample in before)
    +        error_energy = math.fsum((right - left) ** 2 for left, right in zip(before, after))
    +        reference_rms = math.sqrt(reference_energy / len(before))
    +        silent = reference_rms < 1e-8
    +        if silent and error_energy != 0:
    +            raise QualityError(f"silent or near-silent reference channel {index} requires exactly matching PCM")
    +        nrmse = 0.0 if silent else math.sqrt(error_energy / reference_energy)
    +        if not math.isfinite(nrmse):
    +            raise QualityError("nonfinite audio NRMSE")
    +        channels.append({"channel": index, "nrmse": nrmse, "reference_rms": reference_rms,
    +                         "silent_reference": silent, "samples": len(before)})
    +    return {"nrmse": max(channel["nrmse"] for channel in channels),
    +            "aggregation": "maximum channel NRMSE", "channels": channels, "samples": len(reference)}
    +
    +
    +def _pcm(path, destination, args, evidence, label):
    +    _run([args.ffmpeg, "-v", "error", "-nostdin", "-y", "-xerror", "-err_detect", "explode",
    +          "-i", str(path), "-map", "0:a:0", "-vn", "-ar", "48000", "-ac", "2",
    +          "-c:a", "pcm_f32le", "-f", "f32le", str(destination)], evidence, label, args.tool_timeout)
    +    raw = destination.read_bytes()
    +    if len(raw) % 4:
    +        raise QualityError("malformed float32 PCM output")
    +    samples = array("f")
    +    samples.frombytes(raw)
    +    if sys.byteorder != "little":
    +        samples.byteswap()
    +    return samples
    +
    +
    +def compare_pair(reference, candidate, args, evidence, protocol=None):
    +    evidence.mkdir(parents=True, exist_ok=False)
    +    ref_path, cand_path = reference["path"], candidate["path"]
    +    for item in (reference, candidate):
    +        if sha256_file(item["path"]) != item["sha256"]:
    +            raise QualityError(f"artifact changed after manifest load: {item['path']}")
    +    before = _probe(ref_path, args, evidence, "reference-probe")
    +    after = _probe(cand_path, args, evidence, "candidate-probe")
    +    check_protocol_metadata(before, protocol)
    +    check_protocol_metadata(after, protocol)
    +    compare_metadata(before, after)
    +    fps = Fraction(before["fps"])
    +    ordinal_pts = f"N*{fps.denominator}/{fps.numerator}/TB"
    +    graph = (f"[0:v:0]settb=AVTB,setpts={ordinal_pts},split[r0][r1];"
    +             f"[1:v:0]settb=AVTB,setpts={ordinal_pts},split[c0][c1];"
    +             "[r0][c0]ssim=stats_file=ssim.log:shortest=1:repeatlast=0[s];"
    +             "[r1][c1]psnr=stats_file=psnr.log:shortest=1:repeatlast=0[p]")
    +    _run([args.ffmpeg, "-v", "error", "-nostdin", "-xerror", "-err_detect", "explode", "-i", str(ref_path),
    +          "-err_detect", "explode", "-i", str(cand_path), "-filter_complex", graph,
    +          "-map", "[s]", "-map", "[p]", "-an", "-f", "null", "-"], evidence, "video-compare", args.tool_timeout)
    +    ssim = video_stats(evidence / "ssim.log", "All", before["frames"])
    +    psnr = video_stats(evidence / "psnr.log", "psnr_avg", before["frames"], allow_infinity=True)
    +    pcm_before = _pcm(ref_path, evidence / "reference.f32", args, evidence, "reference-audio")
    +    pcm_after = _pcm(cand_path, evidence / "candidate.f32", args, evidence, "candidate-audio")
    +    check_pcm_duration(pcm_before, protocol)
    +    check_pcm_duration(pcm_after, protocol)
    +    audio = audio_nrmse(pcm_before, pcm_after)
    +    minimum_ssim, minimum_psnr = min(ssim), min(psnr)
    +    failures = []
    +    if minimum_ssim < args.min_ssim:
    +        failures.append(f"minimum frame SSIM {minimum_ssim} < {args.min_ssim}")
    +    if minimum_psnr < args.min_psnr:
    +        failures.append(f"minimum frame PSNR {minimum_psnr} < {args.min_psnr} dB")
    +    if audio["nrmse"] > args.max_audio_nrmse:
    +        failures.append(f"audio NRMSE {audio['nrmse']} > {args.max_audio_nrmse}")
    +    for item in (reference, candidate):
    +        if sha256_file(item["path"]) != item["sha256"]:
    +            failures.append(f"artifact changed during comparison: {item['path']}")
    +    return {"verdict": "FAIL" if failures else "PASS", "failures": failures,
    +            "reference_path": str(ref_path), "candidate_path": str(cand_path),
    +            "reference_sha256": reference["sha256"], "candidate_sha256": candidate["sha256"],
    +            "metadata": before, "min_frame_ssim": minimum_ssim, "mean_frame_ssim": math.fsum(ssim) / len(ssim),
    +            "min_frame_psnr_db": "inf" if minimum_psnr == math.inf else minimum_psnr,
    +            "all_frames_identical_by_psnr": all(value == math.inf for value in psnr),
    +            "audio": audio, "evidence_dir": str(evidence)}
    +
    +
    +def parser():
    +    result = argparse.ArgumentParser(description=__doc__)
    +    reference = result.add_mutually_exclusive_group(required=True)
    +    reference.add_argument("--reference-manifest", type=Path)
    +    reference.add_argument("--reference-dir", type=Path)
    +    candidate = result.add_mutually_exclusive_group(required=True)
    +    candidate.add_argument("--candidate-manifest", type=Path)
    +    candidate.add_argument("--candidate-dir", type=Path)
    +    candidate.add_argument("--candidate-root", type=Path)
    +    candidate.add_argument("--omnirsi-run", action="store_true", help="Derive run root from the validation job result path")
    +    result.add_argument("--output", type=Path, required=True)
    +    result.add_argument("--min-ssim", type=float, default=0.99)
    +    result.add_argument("--min-psnr", type=float, default=35.0)
    +    result.add_argument("--max-audio-nrmse", type=float, default=0.01)
    +    result.add_argument("--expected-artifacts", type=int, default=3)
    +    result.add_argument("--tool-timeout", type=float, default=300)
    +    result.add_argument("--ffprobe", default="ffprobe")
    +    result.add_argument("--ffmpeg", default="ffmpeg")
    +    result.add_argument("--expected-validator-sha", help="Freeze this guard before Codex changes candidate code")
    +    result.add_argument("--expected-parallel", help="Frozen TP,Ulysses,VAE tuple for final baseline/candidate trials")
    +    return result
    +
    +
    +def main(argv=None):
    +    args = parser().parse_args(argv)
    +    report = {"schema_version": 1, "verdict": "FAIL", "errors": [], "comparisons": [],
    +              "validator_sha256": sha256_file(__file__),
    +              "thresholds": {"min_frame_ssim": args.min_ssim, "min_frame_psnr_db": args.min_psnr,
    +                             "max_audio_nrmse": args.max_audio_nrmse,
    +                             "policy": "Experiment-declared thresholds; not an official LTX-2.5 standard."}}
    +    exit_code = 1
    +    output_is_input = False
    +
    +    def protect_output(paths):
    +        nonlocal output_is_input
    +        if args.output.resolve() in {Path(path).resolve() for path in paths}:
    +            output_is_input = True
    +            raise QualityError("quality output must not overwrite an input manifest or media artifact")
    +
    +    try:
    +        expected_parallel = None
    +        if args.expected_parallel:
    +            values = args.expected_parallel.split(",")
    +            if len(values) != 3 or any(not value.isdigit() for value in values):
    +                raise QualityError("--expected-parallel requires TP,Ulysses,VAE integers")
    +            tp, ulysses, vae = map(int, values)
    +            if tp * ulysses != 4 or vae not in (1, 2, 4):
    +                raise QualityError("--expected-parallel must describe the frozen four-worker winner")
    +            expected_parallel = {"tp": tp, "ulysses": ulysses, "vae": vae, "cfg": 1, "ring": 1}
    +        if args.expected_validator_sha and args.expected_validator_sha != report["validator_sha256"]:
    +            raise QualityError("validator changed after policy freeze")
    +        if args.omnirsi_run:
    +            result_path = Path(os.environ.get("OMNIRSI_RESULT_PATH", "")).resolve()
    +            if result_path.name != "result.json" or result_path.parent.name != "validation":
    +                raise QualityError("--omnirsi-run requires the OmniRSI validation job result path")
    +            args.candidate_root = result_path.parent.parent
    +        for name in ("min_ssim", "min_psnr", "max_audio_nrmse", "tool_timeout"):
    +            if not math.isfinite(getattr(args, name)):
    +                raise QualityError(f"{name} must be finite")
    +        if not 0 <= args.min_ssim <= 1 or args.min_psnr < 0 or args.max_audio_nrmse < 0:
    +            raise QualityError("invalid quality threshold range")
    +        if args.tool_timeout <= 0 or args.expected_artifacts < 1:
    +            raise QualityError("tool timeout and expected artifact count must be positive")
    +        reference = (load_manifest(args.reference_manifest, args.expected_artifacts) if args.reference_manifest else
    +                     load_directory(args.reference_dir, args.expected_artifacts))
    +        protect_output([reference["source"], *(artifact["path"] for artifact in reference["artifacts"].values())])
    +        report["reference"] = {"source": reference["source"], "protocol_sha256": reference["protocol_sha256"]}
    +        if args.candidate_root:
    +            if reference["protocol_sha256"] is None:
    +                raise QualityError("candidate-root mode requires a frozen reference manifest with protocol digest")
    +            candidates = run_manifests(args.candidate_root)
    +            protect_output([args.candidate_root / "run.lock.json"])
    +        else:
    +            candidates = [("direct", args.candidate_manifest)] if args.candidate_manifest else [("directory", None)]
    +        protect_output([manifest for _, manifest in candidates if manifest is not None])
    +        evidence_root = args.output.resolve().parent / (args.output.stem + "-evidence-" + uuid.uuid4().hex[:8])
    +        evidence_root.mkdir(parents=True)
    +        report["evidence_dir"] = str(evidence_root)
    +        seen_paths = set()

    <sub><sub>!P1 Badge</sub></sub> Reject reference artifacts from candidate inputs

    In --candidate-manifest or --candidate-dir mode, passing the reference itself (or a candidate manifest whose MP4 paths alias the reference MP4s) is accepted because this set starts empty and only tracks candidate-to-candidate reuse. Each file is then compared with itself, producing perfect SSIM/PSNR/audio metrics and a false quality PASS; initialize the ownership set with all reference paths or explicitly reject the intersection.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 12, 2026 08:56 UTC
    Code Review
    examples/qwen21_turbo_b300.py:1
    @@ -0,0 +1,292 @@
    +"""Frozen 720p-class Qwen-Image-2.1-Turbo online B300 campaign.
    +
    +Uses only stdlib; the sibling LTX helper supplies generic source/device/process
    +ownership utilities, never LTX requests or model settings.
    +"""
    +import argparse
    +import ast
    +import base64
    +import importlib.metadata
    +import json
    +import os
    +from pathlib import Path
    +import socket
    +from statistics import mean
    +import subprocess
    +import sys
    +import time
    +import urllib.request
    +
    +import ltx25_b300 as lifecycle
    +
    +MODEL = "Qwen/Qwen-Image-2.1-Turbo"
    +REVISION = "d65dbc9a7e8f6b5479e33dee6030eaab2a906509"
    +SIGMAS = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
    +PROMPTS = [
    +    'A photorealistic red fox standing in a snowy forest at dawn, detailed fur, soft sunlight, a wide landscape composition.',
    +    'A clean product photograph of a blue ceramic teapot and two white cups on a wooden table, natural window lighting.',
    +    'A colorful travel poster of a rocky ocean coast at sunset with the exact headline "OCEAN JOURNEY", readable typography.',
    +]
    +HELD_OUT_PROMPTS = [
    +    'A watercolor painting of a yellow bicycle beside a purple flower shop, with three hanging baskets.',
    +    'A studio photograph of a transparent glass vase with five orange tulips on a dark green background.',
    +    'A minimalist book cover reading "NIGHT GARDEN", with silver moonlight and delicate blue flowers.',
    +]
    +PROTECTED_FILES = [
    +    'vllm_omni/model_extras/qwen_image_21.py',
    +    'vllm_omni/entrypoints/openai/diffusion.py',
    +    'vllm_omni/entrypoints/openai/api_server.py',
    +    'vllm_omni/entrypoints/openai/image_api_utils.py',
    +    'vllm_omni/diffusion/distributed/autoencoders/autoencoder_kl_qwenimage21.py',
    +]
    +PROTECTED_METHODS = {'__init__', 'prepare_timesteps', 'prepare_latents', '_pack_latents', '_unpack_latents'}
    +
    +
    +def protocol(diagnostic=False, profile_steps=2, held_out=False):
    +    if not 1 <= profile_steps <= 8:
    +        raise ValueError('Profile steps must be 1..8')
    +    sigmas = [SIGMAS[i * 7 // max(1, profile_steps - 1)] for i in range(profile_steps)] if diagnostic else SIGMAS
    +    return {'model': MODEL, 'model_revision': REVISION, 'width': 1280, 'height': 704,
    +            'dtype': 'bfloat16', 'true_cfg_scale': 1.0, 'sigmas': sigmas,
    +            'attention_backend': 'FLASH_ATTN', 'prefix_kv_cache': 'checkpoint_default_native',
    +            'compile_policy': 'enforce_eager',
    +            'codec': 'PNG', 'response_format': 'b64_json', 'concurrency': 1,
    +            'pixel_mode': 'RGBA', 'output_compression': 100,
    +            'prompts': [{'id': f'prompt-{i:03d}-seed-{(142 if held_out else 42)+i}', 'prompt': p,
    +                         'seed': (142 if held_out else 42)+i} for i,p in enumerate(HELD_OUT_PROMPTS if held_out else PROMPTS)],
    +            'warmup_seeds': [[10042,10043,10044],[11042,11043,11044]],
    +            'timing': 'POST until complete HTTP JSON response downloaded; PNG decode/write outside timer',
    +            'conditioning_scope': 'Repeated prompts with new seeds; deterministic conditioning reuse allowed; final-image reuse forbidden'}
    +
    +
    +def protected_sources(source):
    +    result = {p: lifecycle.sha256(source / p) for p in PROTECTED_FILES}
    +    relative = 'vllm_omni/diffusion/models/qwen_image_21/pipeline_qwen_image_21.py'
    +    tree = ast.parse((source / relative).read_text())
    +    for node in tree.body:
    +        if isinstance(node, ast.FunctionDef) and node.name in {'get_qwen_image_21_pre_process_func', 'get_qwen_image_21_post_process_func'}:
    +            result[relative + ':' + node.name] = lifecycle.digest(ast.dump(node, include_attributes=False))
    +    for node in tree.body:
    +        if isinstance(node, ast.ClassDef) and node.name == 'QwenImage21Pipeline':
    +            found = set()
    +            for method in node.body:
    +                if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)) and method.name in PROTECTED_METHODS:
    +                    result[relative + ':' + method.name] = lifecycle.digest(ast.dump(method, include_attributes=False))
    +                    found.add(method.name)
    +            if found != PROTECTED_METHODS:
    +                raise ValueError('Protected pipeline method missing')
    +            break
    +    else:
    +        raise ValueError('Protected pipeline class missing')
    +    return result
    +
    +
    +def dependencies():
    +    versions = lifecycle.semantic_dependency_versions(lifecycle.dependency_versions())
    +    for name in ['Pillow', 'numpy', 'scikit-image', 'flash-attn-4', 'nvidia-cutlass-dsl', 'kernels']:
    +        versions[name] = importlib.metadata.version(name)
    +    return versions
    +
    +
    +def model_assets(model, cache):
    +    manifest = cache.parent/'artifacts/model-assets.json'
    +    assets = json.loads(manifest.read_text())
    +    if Path(assets['model']).resolve() != model or assets['revision'] != REVISION:
    +        raise ValueError('Model asset manifest does not match the pinned snapshot')
    +    actual = {str(p.relative_to(model)) for p in model.rglob('*') if p.is_file()}
    +    if actual != {item['path'] for item in assets['files']}:
    +        raise ValueError('Model file coverage changed')
    +    for item in assets['files']:
    +        stat = (model/item['path']).stat()
    +        if (stat.st_size, stat.st_mtime_ns) != (item['bytes'], item['mtime_ns']):
    +            raise ValueError('Model asset changed after SHA256 freeze')

    <sub><sub>!P1 Badge</sub></sub> Verify model files against their recorded SHA-256

    If model bytes are replaced with same-length content while the original mtime is preserved (as can happen with timestamp-preserving copy/deployment tooling), these coverage/stat checks pass because the manifest's per-file sha256 field is never read. The helper then records the unchanged manifest hash and can attribute outputs to the pinned model revision despite running different weights, so each actual file hash must be compared with the recorded digest.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 12, 2026 08:56 UTC
    Code Review
    docs/qwen21-turbo-b300-phase2-results.md:1
    @@ -0,0 +1,99 @@
    +# Qwen Turbo / B300 x4 phase 2 results
    +
    +**The 30% target passed: fresh original-source baseline 384.16 -> 266.60 ms E2E, a 30.60% reduction. Against the earliest historical baseline of385.07 ms, the reduction is30.76%.** All40 formal image checks passed with identical decoded RGB/alpha pixels. The source baseline remains original main `f69b1f2b`; it was not reset to phase 1's optimized candidate.

    <sub><sub>!P1 Badge</sub></sub> Publish all evidence segments before declaring PASS

    This publishes a passing 30.60% E2E claim, but a repo-wide search of evidence/qwen21-turbo-b300-20261010/ finds only results/README.md and results/archive-manifest.json; plan/, patch/, and validator/ are absent, and the archive/source bundle/recompute helper are referenced rather than present in that evidence tree. The claim should remain unverified/INCONCLUSIVE until the complete frozen evidence is published.

    AGENTS.md reference: AGENTS.md:L79-L85

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 12, 2026 08:56 UTC
    Code Review
    tests/fixtures/legacy/ltx25_b300.py:1
    @@ -0,0 +1,640 @@
    +"""B300 LTX-2.5 campaign helper: fresh servers, full-shape warmup, sync A/V.
    +
    +No inference library is imported. Run with the prepared Omni interpreter.
    +All input settings are CLI args; JSON is derived evidence, never a task file.
    +"""
    +
    +import argparse
    +import csv
    +import hashlib
    +import io
    +import json
    +import math
    +import os
    +from pathlib import Path
    +import re
    +import signal
    +import socket
    +from statistics import mean, median
    +import subprocess
    +import sys
    +import time
    +import urllib.error
    +import urllib.request
    +import uuid
    +
    +MODEL_ID = "Lightricks/LTX-2.5-Diffusers"
    +MODEL_REVISION = "a6de4b5354f078db24d9cf4778c14846788aea3d"
    +PIPELINE = "LTX2DistilledTwoStagePipeline"
    +PROMPTS = (
    +    "A cinematic shot of a red fox walking through a snowy forest at dawn, the camera tracking alongside, snow crunching underfoot.",
    +    "A close shot of a robot playing a piano, its fingers pressing individual keys while the camera remains fixed, with synchronized piano sounds.",
    +    "A fixed wide shot of ocean waves rolling onto a rocky coast at sunset, with natural surf sounds and steady motion.",
    +)
    +
    +# Whole-file hashes freeze the recipe, sigma/guidance and decoder defaults.
    +SEMANTIC_SOURCE_PATHS = tuple("vllm_omni/diffusion/models/ltx2/" + name for name in (
    +    "ltx2_recipes.py", "ltx2_guidance.py", "ltx2_request.py", "ltx2_components.py",
    +    "ltx2_denoise.py", "ltx2_latents.py", "ltx2_diffusion_decoder.py", "ltx2_diffusion_decoder_distributed.py",
    +    "ltx2_runtime.py", "ltx2_phase_adapter.py", "pipeline_ltx2.py", "pipeline_ltx2_two_stage.py", "ltx2_adapter_parser.py",
    +)) + ("vllm_omni/model_extras/ltx2.py", "vllm_omni/entrypoints/openai/serving_video.py",
    +      "vllm_omni/diffusion/utils/media_utils.py")
    +STAGE_1_SIGMAS = (1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875, 0.0)
    +STAGE_2_SIGMAS = (0.909375, 0.725, 0.421875, 0.0)
    +VIDEO_CODEC_OPTIONS = {"preset": "ultrafast", "threads": "0", "crf": "18"}
    +
    +
    +def protocol(args=None):
    +    width, height = getattr(args, "width", 1280), getattr(args, "height", 704)
    +    if any(isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value % 64
    +           for value in (width, height)):
    +        raise ValueError("Two-stage width and height must be positive multiples of 64")
    +    stage_1, stage_2 = STAGE_1_SIGMAS, STAGE_2_SIGMAS
    +    if getattr(args, "diagnostic", False):
    +        schedules = []
    +        for sigmas, steps in ((stage_1, args.profile_stage1_steps), (stage_2, args.profile_stage2_steps)):
    +            if not 1 <= steps < len(sigmas):
    +                raise ValueError("Diagnostic steps must be within the fixed stage schedule")
    +            schedules.append(tuple(sigmas[i * (len(sigmas) - 1) // steps] for i in range(steps + 1)))
    +        stage_1, stage_2 = schedules
    +    return {"model_id": MODEL_ID, "model_revision": MODEL_REVISION, "pipeline": PIPELINE,
    +            "task": "t2v", "width": width, "height": height, "num_frames": 121, "fps": 24,
    +            "num_inference_steps": len(stage_1) - 1, "refine_steps": len(stage_2) - 1, "dtype": "bfloat16",
    +            "decoder": "native_diffvae", "audio_sample_rate": 48000, "audio_channels": 2,
    +            "stage_1_sigmas": list(stage_1), "stage_2_sigmas": list(stage_2),
    +            "guidance": "positive_only", "ltx2_use_conv_vae": False,
    +            "video_codec_options": dict(VIDEO_CODEC_OPTIONS),
    +            "prompts": [{"id": f"prompt-{i:03d}-seed-{42+i}", "prompt": prompt, "seed": 42+i}
    +                        for i, prompt in enumerate(PROMPTS)], "warmup_rounds": 2,
    +            "warmup_seeds": [[42+i+10000+warmup*1000 for i in range(len(PROMPTS))] for warmup in range(2)],
    +            "request_scope": "New synchronous requests; distinct warmup seeds; static conditioning reuse is allowed."}
    +
    +
    +def digest(value):
    +    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
    +                                    ensure_ascii=False, allow_nan=False).encode()).hexdigest()
    +
    +
    +def sha256(path):
    +    hasher = hashlib.sha256()
    +    with Path(path).open("rb") as stream:
    +        for block in iter(lambda: stream.read(1024 * 1024), b""):
    +            hasher.update(block)
    +    return hasher.hexdigest()
    +
    +
    +def write_json(path, value):
    +    Path(path).parent.mkdir(parents=True, exist_ok=True)
    +    Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
    +
    +
    +def validate_parallel(tp, ulysses, vae, single_reference=False):
    +    if any(isinstance(value, bool) or not isinstance(value, int) or value < 1 for value in (tp, ulysses, vae)):
    +        raise ValueError("Parallel degrees must be positive integers")
    +    if (tp, ulysses, vae) != (1, 1, 1) and single_reference:
    +        raise ValueError("The single-worker reference requires TP1 / Ulysses1 / VAE1")
    +    if not single_reference and ((tp, ulysses) not in ((1, 4), (2, 2), (4, 1)) or vae not in (1, 2, 4)):
    +        raise ValueError("Four-worker trials permit TP1/U4, TP2/U2 or TP4/U1 with VAE1,2,4; CFG/Ring stay one")
    +    world = tp * ulysses
    +    if world != (1 if single_reference else 4):
    +        raise ValueError("TP * Ulysses must equal four; only the explicit reference lane uses one")
    +    if vae > world or world % vae:
    +        raise ValueError("VAE degree must divide and reuse the existing worker WORLD")
    +    return world
    +
    +
    +def storage_locations(args, output_root, require_source=True):
    +    source = Path(args.source_repo).resolve()
    +    cache = Path(args.cache_root).resolve()
    +    output_root = Path(output_root).resolve()
    +    if require_source and not source.is_dir():
    +        raise ValueError("source-repo must be an existing checkout")
    +    if cache.is_relative_to(source) or output_root.is_relative_to(source):
    +        raise ValueError("Cache and campaign output must be outside the source checkout")
    +    for key in ("HF_HOME", "HF_HUB_CACHE", "HUGGINGFACE_HUB_CACHE", "TRANSFORMERS_CACHE"):
    +        if os.environ.get(key) and Path(os.environ[key]).resolve().is_relative_to(source):
    +            raise ValueError(f"{key} must be outside the source checkout")
    +    return source, cache, output_root
    +
    +
    +def source_snapshot(source):
    +    from omnirsi.execution import repository_identity
    +    identity = repository_identity(source)
    +    if not identity.get("available"):
    +        raise ValueError(f"Source identity unavailable: {identity.get('error')}")
    +    return identity
    +
    +
    +def semantic_sources(source):
    +    source = Path(source).resolve()
    +    if not SEMANTIC_SOURCE_PATHS:
    +        raise ValueError("No reviewed semantic source paths were declared; campaign is unqualified")
    +    hashes = {}
    +    for relative in SEMANTIC_SOURCE_PATHS:
    +        path = (source / relative).resolve()
    +        if not path.is_relative_to(source) or not path.is_file():
    +            raise ValueError(f"Required semantic source missing or outside checkout: {relative}")
    +        hashes[relative] = sha256(path)
    +    return hashes
    +
    +
    +def dependency_versions():
    +    packages = ("torch", "vllm", "vllm-omni", "diffusers", "transformers", "triton",
    +                "nvidia-cuda-runtime-cu12", "nvidia-cuda-runtime-cu13", "nvidia-cudnn-cu12",
    +                "nvidia-cudnn-cu13", "nvidia-nccl-cu12", "nvidia-nccl-cu13", "flashinfer-python")
    +    code = ("import importlib.metadata as metadata,json,sys\n"
    +            "versions={}\n"
    +            "for name in sys.argv[1:]:\n"
    +            " try: versions[name]=metadata.version(name)\n"
    +            " except metadata.PackageNotFoundError: versions[name]='not_installed'\n"
    +            "print(json.dumps(versions))\n")
    +    result = subprocess.run([sys.executable, "-c", code, *packages], capture_output=True, text=True,
    +                            timeout=30, check=True)
    +    return json.loads(result.stdout)
    +
    +
    +def semantic_dependency_versions(versions):
    +    # Source revisions cover vLLM-Omni code; editable package version text can differ.
    +    return {name: version for name, version in versions.items() if name != "vllm-omni"}
    +
    +
    +def server_argv(args):
    +    world = validate_parallel(args.tp, args.ulysses, args.vae, args.single_reference)
    +    executable = str(Path(sys.executable).parent / "vllm")
    +    argv = [executable, "serve", args.model, "--revision", MODEL_REVISION, "--omni",
    +            "--model-class-name", PIPELINE, "--dtype", "bfloat16", "--num-gpus", str(world),
    +            "--tensor-parallel-size", str(args.tp), "--usp", str(args.ulysses), "--ring", "1",
    +            "--cfg-parallel-size", "1", "--vae-patch-parallel-size", str(args.vae),
    +            "--vae-parallel-mode", "tile", "--vae-use-tiling",
    +            "--diffusion-attention-backend", "CUDNN_ATTN", "--max-num-seqs", "1",
    +            "--stage-overrides", json.dumps({"0": {"extras": {"ltx2_use_conv_vae": False}}}),
    +            "--host", "127.0.0.1", "--port", str(args.port),
    +            "--stage-init-timeout", str(args.startup_timeout)]
    +    if args.eager:
    +        argv.append("--enforce-eager")
    +    if args.diagnostic:
    +        directory = str(Path(args.output).resolve().parent / "torch-profile")
    +        argv.extend(["--profiler-config", json.dumps({"profiler": "torch", "torch_profiler_dir": directory})])
    +    return argv
    +
    +
    +def preflight():
    +    ids = [item.strip() for item in os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",") if item.strip()]
    +    if len(ids) != 4 or len(set(ids)) != 4:
    +        raise ValueError("Set CUDA_VISIBLE_DEVICES to exactly four caller-reserved B300 IDs/UUIDs")
    +    result = subprocess.run(["nvidia-smi", "--query-gpu=index,uuid,name,driver_version", "--format=csv,noheader"],
    +                            check=True, capture_output=True, text=True, timeout=30)
    +    devices = [dict(zip(("index", "uuid", "name", "driver"), [v.strip() for v in row]))
    +               for row in csv.reader(io.StringIO(result.stdout)) if len(row) == 4]
    +    selected = [gpu for gpu in devices if gpu["index"] in ids or gpu["uuid"] in ids]
    +    if len(selected) != 4 or any(not re.search(r"\bB300\b", gpu["name"]) for gpu in selected):
    +        raise ValueError("The four requested physical devices must all be B300; inspect nvidia-smi mapping")
    +    active = subprocess.run(["nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name", "--format=csv,noheader"],
    +                            check=True, capture_output=True, text=True, timeout=30)
    +    selected_uuids = {gpu["uuid"] for gpu in selected}
    +    if any(row and row[0].strip() in selected_uuids for row in csv.reader(io.StringIO(active.stdout))):
    +        raise ValueError("An allocated GPU already has a compute process; do not overlap campaign trials")
    +    return selected
    +
    +
    +def multipart(fields):
    +    boundary = "omnirsi-" + uuid.uuid4().hex
    +    chunks = []
    +    for name, value in fields.items():
    +        chunks.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
    +    chunks.append(f"--{boundary}--\r\n".encode())
    +    return b"".join(chunks), "multipart/form-data; boundary=" + boundary
    +
    +
    +def request_video(args, item, destination):
    +    settings = protocol(args)
    +    fields = {"model": args.model, "prompt": item["prompt"], "seed": item["seed"],
    +              "width": settings["width"], "height": settings["height"], "num_frames": 121, "fps": 24,
    +              "num_inference_steps": settings["num_inference_steps"],
    +              "extra_params": json.dumps({"stage_1_sigmas": settings["stage_1_sigmas"],
    +                                           "stage_2_sigmas": settings["stage_2_sigmas"],
    +                                           "video_codec_options": VIDEO_CODEC_OPTIONS})}
    +    body, content_type = multipart(fields)
    +    request = urllib.request.Request(f"http://127.0.0.1:{args.port}/v1/videos/sync", data=body,
    +                                     headers={"Content-Type": content_type, "Accept": "video/mp4"})
    +    start = time.perf_counter()
    +    with urllib.request.urlopen(request, timeout=args.request_timeout) as response:
    +        if response.status != 200 or "video" not in response.headers.get("Content-Type", ""):
    +            raise ValueError("Synchronous endpoint did not return a successful video artifact")
    +        count = 0
    +        with Path(destination).open("wb") as output:
    +            while block := response.read(1024 * 1024):
    +                output.write(block)
    +                count += len(block)
    +    elapsed = (time.perf_counter() - start) * 1000
    +    if not count or not math.isfinite(elapsed) or elapsed <= 0:
    +        raise ValueError("Incomplete or invalid synchronous request")
    +    return elapsed
    +
    +
    +def launch_server(argv, source, environment, log):
    +    """Keep supervised workers inside the runner's group, including hard timeout."""
    +    helper_pid, helper_group = os.getpid(), os.getpgrp()
    +    marker = bool(os.environ.get("OMNIRSI_RESULT_PATH"))
    +    if marker and helper_group != helper_pid:
    +        raise ValueError("OmniRSI helper must be its trial group leader; invoke the prepared Python directly")
    +    supervised = marker and helper_group == helper_pid
    +    process = subprocess.Popen(argv, cwd=source, env=environment, stdout=log, stderr=log,
    +                               start_new_session=not supervised, shell=False)
    +    ownership = {"mode": "omnirsi_trial_group" if supervised else "server_session",
    +                 "server_pid": process.pid, "helper_pid": helper_pid,
    +                 "process_group_id": helper_group if supervised else process.pid,
    +                 "helper_process_group_id": helper_group,
    +                 "server_start_new_session": not supervised}
    +    return process, ownership
    +
    +
    +def _live_group_members(group, exclude=()):
    +    members = []
    +    for path in Path("/proc").glob("[0-9]*/stat"):
    +        try:
    +            fields = path.read_text().rsplit(")", 1)[1].split()
    +            pid = int(path.parent.name)
    +            if int(fields[2]) == group and fields[0] != "Z" and pid not in exclude:
    +                members.append(pid)
    +        except (FileNotFoundError, ProcessLookupError, PermissionError):
    +            continue
    +    return members
    +
    +
    +def stop_server(process, ownership, grace_seconds=20):
    +    """Clean the owned group even when its original server leader already exited."""
    +    group = ownership["process_group_id"]
    +    inherited = ownership["mode"] == "omnirsi_trial_group"
    +    if inherited:
    +        if group != os.getpid() or group != os.getpgrp() or ownership["helper_pid"] != os.getpid():
    +            raise ValueError("Refusing cleanup of a group not owned by this supervised helper")
    +        excluded = (os.getpid(),)
    +    else:
    +        if group != process.pid or group == os.getpgrp() or ownership["server_start_new_session"] is not True:
    +            raise ValueError("Refusing cleanup of an unknown server group")
    +        excluded = ()
    +
    +    def signal_members(number):
    +        if inherited:
    +            for pid in _live_group_members(group, excluded):
    +                try:
    +                    if os.getpgid(pid) == group:
    +                        os.kill(pid, number)
    +                except ProcessLookupError:
    +                    pass
    +        else:
    +            try:
    +                os.killpg(group, number)
    +            except ProcessLookupError:
    +                pass
    +
    +    signal_members(signal.SIGTERM)
    +    deadline = time.monotonic() + grace_seconds
    +    while _live_group_members(group, excluded) and time.monotonic() < deadline:
    +        process.poll()
    +        time.sleep(0.05)
    +    remaining = _live_group_members(group, excluded)
    +    killed = bool(remaining)
    +    if remaining:
    +        signal_members(signal.SIGKILL)
    +        deadline = time.monotonic() + 5
    +        while _live_group_members(group, excluded) and time.monotonic() < deadline:
    +            process.poll()
    +            time.sleep(0.05)
    +    if process.poll() is None:
    +        process.wait(timeout=5)
    +    remaining = _live_group_members(group, excluded)
    +    return {"status": "failed" if remaining else "completed", "mode": ownership["mode"], "process_group_id": group, "term_sent": True,
    +            "kill_sent": killed, "remaining_pids": remaining,
    +            "server_returncode": process.returncode}
    +
    +
    +def run_trial(args):
    +    if sys.platform != "linux":
    +        raise ValueError("GPU campaign execution requires the prepared remote Linux environment")
    +    output = Path(args.output).resolve()
    +    validate_parallel(args.tp, args.ulysses, args.vae, args.single_reference)
    +    source, cache, _ = storage_locations(args, output.parent)
    +    before = source_snapshot(source)
    +    semantics = semantic_sources(source)
    +    if output.exists():
    +        raise ValueError("Result path already exists; keep trials immutable and use a fresh directory")
    +    output.parent.mkdir(parents=True, exist_ok=True)
    +    media = output.parent / "media"
    +    media.mkdir(exist_ok=False)
    +    base_protocol = protocol(args)
    +    record = {"status": "running", "protocol": base_protocol, "protocol_sha256": digest(base_protocol),
    +              "parallel": {"tp": args.tp, "ulysses": args.ulysses, "cfg": 1, "ring": 1, "vae": args.vae},
    +              "compile_policy": "eager" if args.eager else "default", "diagnostic": args.diagnostic,
    +              "source_repo": str(source), "source_before": before, "source_commit": before["head"],
    +              "semantic_sources_hashes": semantics, "helper_sha256": sha256(__file__),
    +              "dependency_version_scope": "Installed distribution metadata; loaded CUDA/cuDNN/NCCL runtime versions are not probed.",
    +              "tp_qualification": "Requires at least three quality-passing repeats before eligibility" if args.tp != 1 else "TP1",
    +              "server_argv": server_argv(args), "artifacts": [], "samples_ms": []}
    +    process, ownership = None, None
    +    try:
    +        record["dependency_versions"] = dependency_versions()
    +        record["devices"] = preflight()
    +        with socket.socket() as probe:
    +            if probe.connect_ex(("127.0.0.1", args.port)) == 0:
    +                raise ValueError("Campaign port is already in use; do not attach to an unknown server")
    +        if not Path(record["server_argv"][0]).is_file():
    +            raise ValueError("No vllm entrypoint beside this interpreter; use the prepared Omni Python")
    +        cache.mkdir(parents=True, exist_ok=True)
    +        environment = os.environ.copy()
    +        environment["PYTHONDONTWRITEBYTECODE"] = "1"
    +        environment["PYTHONPATH"] = str(Path(args.source_repo).resolve()) + os.pathsep + environment.get("PYTHONPATH", "")
    +        environment.setdefault("HF_HOME", str(cache / "huggingface"))
    +        for key, directory in {"TORCHINDUCTOR_CACHE_DIR": "inductor", "TRITON_CACHE_DIR": "triton",
    +                               "VLLM_CACHE_ROOT": "vllm", "CUDA_CACHE_PATH": "cuda"}.items():
    +            environment[key] = str(cache / directory)
    +        with (output.parent / "server.log").open("wb") as log:
    +            process, ownership = launch_server(record["server_argv"], source, environment, log)
    +            record["server_process"] = ownership
    +            deadline = time.monotonic() + args.startup_timeout
    +            while True:
    +                if process.poll() is not None:
    +                    raise ValueError("Server exited before ready; inspect server.log")
    +                try:
    +                    with urllib.request.urlopen(f"http://127.0.0.1:{args.port}/health", timeout=5) as response:
    +                        if response.status == 200:
    +                            break
    +                except (urllib.error.URLError, TimeoutError):
    +                    pass
    +                if time.monotonic() >= deadline:
    +                    raise TimeoutError("Server readiness deadline exceeded")
    +                time.sleep(2)
    +            for warmup in range(base_protocol["warmup_rounds"]):
    +                for index, measured_item in enumerate(base_protocol["prompts"]):
    +                    item = {**measured_item, "seed": base_protocol["warmup_seeds"][warmup][index]}
    +                    temporary = media / f"warmup-{warmup}-{item['id']}.mp4"
    +                    request_video(args, item, temporary)
    +                    temporary.unlink()
    +            if args.diagnostic:
    +                urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{args.port}/start_profile", data=b""), timeout=60).close()
    +            for item in base_protocol["prompts"]:
    +                artifact = media / (item["id"] + ".mp4")
    +                elapsed = request_video(args, item, artifact)
    +                record["samples_ms"].append({"id": item["id"], "latency_ms": elapsed})
    +                record["artifacts"].append({"id": item["id"], "path": str(artifact), "sha256": sha256(artifact)})
    +            if args.diagnostic:
    +                urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{args.port}/stop_profile", data=b""), timeout=60).close()
    +            else:
    +                record["metrics"] = {"latency_ms": mean(item["latency_ms"] for item in record["samples_ms"])}
    +            record["status"] = "completed"
    +    except KeyboardInterrupt:
    +        record.update(status="cancelled", error="interrupted by user")
    +    except (OSError, ValueError, subprocess.SubprocessError, urllib.error.URLError, TimeoutError) as exc:
    +        record.update(status="failed", error=str(exc))
    +    finally:
    +        if process is not None:
    +            try:
    +                record["server_cleanup"] = stop_server(process, ownership, args.stop_grace_seconds)
    +                if record["server_cleanup"]["remaining_pids"]:
    +                    record.update(status="failed", error="Owned server processes remained after cleanup")
    +            except (OSError, ValueError, subprocess.SubprocessError) as error:
    +                record.update(status="failed", error=f"Server cleanup failed: {error}",
    +                              server_cleanup={"status": "failed", "remaining_pids": "unknown", "error": str(error)})
    +        try:
    +            after = source_snapshot(source)
    +            record["source_after"] = after
    +            record["source_integrity"] = {"verified": before["snapshot_hash"] == after["snapshot_hash"],
    +                                          "dirty_at_start": before["dirty"]}
    +            if not record["source_integrity"]["verified"] or semantic_sources(source) != semantics:
    +                record.update(status="failed", error="Source changed during trial")
    +            if sha256(__file__) != record["helper_sha256"]:
    +                record.update(status="failed", error="Campaign helper changed during trial")
    +        except (OSError, ValueError, subprocess.SubprocessError) as error:
    +            record.update(status="failed", error=f"Source integrity check failed: {error}",
    +                          source_integrity={"verified": False, "dirty_at_start": before["dirty"]})
    +        write_json(output, record)
    +    return record
    +
    +
    +class CampaignDrift(ValueError):
    +    """A frozen campaign input changed: abort, rather than rank mixed evidence."""
    +
    +
    +def freeze_campaign(args):
    +    source, _, _ = storage_locations(args, args.output_dir)
    +    snapshot = source_snapshot(source)
    +    if snapshot["dirty"]:
    +        raise ValueError("Configuration search requires a clean pinned source checkout")
    +    reference_path = Path(args.reference_manifest).resolve()
    +    quality_path = Path(args.quality_script).resolve()
    +    reference = json.loads(reference_path.read_text(encoding="utf-8"))
    +    if not isinstance(reference, dict) or (reference.get("status") != "completed" or reference.get("diagnostic", False) or
    +            reference.get("protocol") != protocol(args) or reference.get("protocol_sha256") != digest(protocol(args))):
    +        raise ValueError("Reference must be a completed manifest for this exact frozen protocol")
    +    semantics = semantic_sources(source)
    +    if reference.get("semantic_sources_hashes") != semantics or reference.get("helper_sha256") != sha256(__file__):
    +        raise ValueError("Reference semantic sources/helper do not match this campaign")
    +    if reference.get("source_commit") != snapshot["head"]:
    +        raise ValueError("Reference and configuration search must use the same pinned source commit")
    +    artifacts = reference.get("artifacts", [])
    +    if (not isinstance(artifacts, list) or any(not isinstance(item, dict) for item in artifacts) or
    +            {item.get("id") for item in artifacts} != {item["id"] for item in protocol(args)["prompts"]} or len(artifacts) != 3):
    +        raise ValueError("Reference must contain exactly the three fixed prompt/seed artifacts")
    +    recorded_artifacts, paths = {}, set()
    +    for item in artifacts:
    +        path = Path(item["path"])
    +        path = (reference_path.parent / path).resolve() if not path.is_absolute() else path.resolve()
    +        if path in paths or not path.is_file() or sha256(path) != item.get("sha256"):
    +            raise ValueError("Reference artifact missing, duplicated or changed")
    +        recorded_artifacts[item["id"]] = {"path": str(path), "sha256": item["sha256"]}
    +        paths.add(path)
    +    versions = dependency_versions()
    +    if semantic_dependency_versions(reference.get("dependency_versions", {})) != semantic_dependency_versions(versions):
    +        raise ValueError("Reference and configuration search dependency versions differ")
    +    return {"source": snapshot, "semantic_sources_hashes": semantics, "dependency_versions": versions,
    +            "helper_sha256": sha256(__file__), "quality_script": {"path": str(quality_path), "sha256": sha256(quality_path)},
    +            "reference_manifest": {"path": str(reference_path), "sha256": sha256(reference_path), "artifacts": recorded_artifacts}}
    +
    +
    +def assert_campaign_frozen(args, frozen):
    +    try:
    +        current = source_snapshot(Path(args.source_repo).resolve())
    +        if current["snapshot_hash"] != frozen["source"]["snapshot_hash"] or current["dirty"]:
    +            raise CampaignDrift("Source changed during configuration search")
    +        if semantic_sources(Path(args.source_repo).resolve()) != frozen["semantic_sources_hashes"]:
    +            raise CampaignDrift("Semantic source files changed during configuration search")
    +        if semantic_dependency_versions(dependency_versions()) != semantic_dependency_versions(frozen["dependency_versions"]):
    +            raise CampaignDrift("Installed dependency versions changed during configuration search")
    +        if sha256(__file__) != frozen["helper_sha256"]:
    +            raise CampaignDrift("Campaign helper changed during configuration search")
    +        if sha256(frozen["quality_script"]["path"]) != frozen["quality_script"]["sha256"]:
    +            raise CampaignDrift("Quality guard changed during configuration search")
    +        reference = frozen["reference_manifest"]
    +        if sha256(reference["path"]) != reference["sha256"]:
    +            raise CampaignDrift("Reference manifest changed during configuration search")
    +        if any(sha256(item["path"]) != item["sha256"] for item in reference["artifacts"].values()):
    +            raise CampaignDrift("Reference artifact changed during configuration search")
    +    except (OSError, ValueError, subprocess.SubprocessError) as error:
    +        if isinstance(error, CampaignDrift):
    +            raise
    +        raise CampaignDrift(f"Frozen campaign evidence became unavailable: {error}") from error
    +
    +
    +def search(args):
    +    if args.repetitions < 1 or args.include_tp_candidates and args.repetitions < 3:
    +        raise ValueError("Search requires positive repetitions; TP candidates require at least three")
    +    root = Path(args.output_dir).resolve()
    +    if root.exists():
    +        raise ValueError("Search output already exists; start a new campaign directory")
    +    frozen = freeze_campaign(args)
    +    root.mkdir(parents=True)
    +    campaign = {"status": "running", "protocol": protocol(args), "protocol_sha256": digest(protocol(args)),
    +                "frozen_evidence": frozen, "cells": []}
    +    try:
    +        layouts = [(1, 4)] + ([(2, 2), (4, 1)] if args.include_tp_candidates else [])
    +        for tp, ulysses, vae in ((tp, u, v) for tp, u in layouts for v in (1, 2, 4)):
    +            cell = {"id": f"tp{tp}-u{ulysses}-v{vae}-default", "tp": tp, "ulysses": ulysses, "vae": vae, "cfg": 1,
    +                    "ring": 1, "eager": False, "status": "running", "values_ms": [], "trials": []}
    +            campaign["cells"].append(cell)
    +            write_json(root / "search.json", campaign)
    +            try:
    +                for repetition in range(args.repetitions):
    +                    assert_campaign_frozen(args, frozen)
    +                    output = root / cell["id"] / f"trial-{repetition+1:03d}" / "result.json"
    +                    trial_args = {**vars(args), "tp": tp, "ulysses": ulysses, "vae": vae, "eager": False,
    +                                  "single_reference": False, "diagnostic": False, "output": str(output)}
    +                    result = run_trial(argparse.Namespace(**trial_args))
    +                    assert_campaign_frozen(args, frozen)
    +                    if result["status"] == "cancelled":
    +                        raise KeyboardInterrupt
    +                    if result.get("source_integrity", {}).get("verified") is not True:
    +                        raise CampaignDrift("A trial source snapshot changed; search is invalid")
    +                    if result.get("server_cleanup", {}).get("remaining_pids") or result.get("server_cleanup", {}).get("status") == "failed":
    +                        raise CampaignDrift("Server workers remained; search cannot continue")
    +                    if result["status"] != "completed":
    +                        raise ValueError(result.get("error", "trial failed"))
    +                    quality = output.parent / "quality.json"
    +                    validation = subprocess.run([sys.executable, frozen["quality_script"]["path"],
    +                        "--reference-manifest", frozen["reference_manifest"]["path"], "--candidate-manifest", str(output),
    +                        "--output", str(quality), "--min-ssim", "0.99", "--min-psnr", "35",
    +                        "--max-audio-nrmse", "0.01", "--expected-validator-sha", frozen["quality_script"]["sha256"]], check=False)
    +                    assert_campaign_frozen(args, frozen)
    +                    if validation.returncode != 0 or json.loads(quality.read_text(encoding="utf-8")).get("verdict") != "PASS":
    +                        raise ValueError("A/V quality gate failed; cell is ineligible")
    +                    value = result.get("metrics", {}).get("latency_ms")
    +                    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
    +                        raise ValueError("Trial latency must be finite and positive")
    +                    cell["values_ms"].append(value)
    +                    cell["trials"].append({"manifest": str(output), "quality_report": str(quality),
    +                                           "quality_report_sha256": sha256(quality), "latency_ms": value})
    +                    write_json(root / "search.json", campaign)
    +                cell.update(status="eligible", median_ms=median(cell["values_ms"]),
    +                            tp_qualification="three_or_more_quality_passing_repeats" if tp != 1 else "TP1")
    +            except CampaignDrift:
    +                raise
    +            except (OSError, ValueError, subprocess.SubprocessError) as error:
    +                cell.update(status="ineligible", error=str(error))
    +            write_json(root / "search.json", campaign)
    +        assert_campaign_frozen(args, frozen)
    +        eligible = [cell for cell in campaign["cells"] if cell["status"] == "eligible"]
    +        if not eligible:
    +            raise ValueError("No quality-passing configuration; no best baseline can be claimed")
    +        best = min(eligible, key=lambda cell: cell["median_ms"])
    +        write_json(root / "best.json", {"scope": "Lowest recorded median among tested quality-passing four-worker cells; not a global or statistically proven optimum.",
    +                                        "best": best, "frozen_evidence": frozen, "protocol_sha256": digest(protocol())})

    <sub><sub>!P2 Badge</sub></sub> Hash the actual search protocol in best.json

    For a supported search using non-default --width or --height, the reference, trials, and search.json are all frozen with protocol(args), but this writes the digest of protocol() and therefore hashes the default 1280x704 workload. The resulting best.json disagrees with the evidence it summarizes and cannot verify the winning workload; use the campaign's argument-derived protocol here.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 12, 2026 08:56 UTC
    Code Review
    src/omnirsi/arguments.py:1
    @@ -0,0 +1,174 @@
    +"""The user configuration surface is argparse, not task files."""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import shlex
    +import sys
    +from pathlib import Path
    +
    +from . import __version__
    +from .catalog import BACKENDS, REPO_TYPES
    +from .runspec import RunSpec
    +
    +
    +def _common(parser: argparse.ArgumentParser) -> None:
    +    parser.add_argument("--repo", default=".", help="Prepared target Git checkout")
    +    parser.add_argument("--repo-type", choices=REPO_TYPES, default="vllm_omni")
    +    parser.add_argument("--backend", choices=BACKENDS, default="cpu")
    +    parser.add_argument(
    +        "--device-ids", default="", help="Comma-separated caller-assigned device IDs"
    +    )
    +    parser.add_argument(
    +        "--device-model", help="Expected CUDA device model; other probes retain raw output"
    +    )
    +    parser.add_argument(
    +        "--python", default=sys.executable, help="Python used for target package inspection"
    +    )
    +
    +
    +def parser() -> argparse.ArgumentParser:
    +    root = argparse.ArgumentParser(
    +        description="CLI-first reproducible experiments and tuning knowledge"
    +    )
    +    root.add_argument("--version", action="version", version=__version__)
    +    commands = root.add_subparsers(dest="command", required=True)
    +    doctor = commands.add_parser(
    +        "doctor", help="Inspect a prepared local target without installing dependencies"
    +    )
    +    _common(doctor)
    +
    +    for name in ("plan", "run"):
    +        child = commands.add_parser(
    +            name,
    +            help="Freeze an external-command experiment"
    +            if name == "plan"
    +            else "Measure baseline and candidate commands",
    +        )
    +        _common(child)
    +        child.add_argument(
    +            "--candidate-repo", help="Candidate checkout; defaults to the baseline checkout"
    +        )
    +        child.add_argument(
    +            "--scenario", default="external_benchmark", help="Caller-declared scenario label"
    +        )
    +        child.add_argument("--mode", choices=("config", "code", "semantic"), default="config")
    +        child.add_argument(
    +            "--agent",
    +            choices=("manual", "codex", "external"),
    +            default="manual",
    +            help="Handoff label only; no Agent is launched",
    +        )
    +        child.add_argument(
    +            "--executor",
    +            choices=("local",),
    +            default="local",
    +            help="Install this CLI on the remote machine for this first release",
    +        )
    +        child.add_argument(
    +            "--baseline-command",
    +            required=True,
    +            help="Quoted argv command; {result} is replaced with a fresh output path",
    +        )
    +        child.add_argument("--candidate-command", required=True)
    +        child.add_argument(
    +            "--validation-command",
    +            help="Explicit quality/correctness command; missing evidence is INCONCLUSIVE",
    +        )
    +        child.add_argument(
    +            "--metric-key",
    +            default="metrics.latency_ms",
    +            help="Flat or dotted key in benchmark JSON",
    +        )
    +        child.add_argument("--metric-unit", default="ms")
    +        child.add_argument("--comparison-scope", default="external_command")
    +        child.add_argument("--direction", choices=("minimize", "maximize"), default="minimize")
    +        child.add_argument("--repetitions", type=int, default=3)
    +        child.add_argument("--min-improvement-pct", type=float, default=0.0)
    +        child.add_argument(
    +            "--max-minutes",
    +            type=float,
    +            default=120.0,
    +            help="Experiment deadline, at most seven days",
    +        )
    +        child.add_argument("--workload-id", help="Caller-declared fixed workload identity")
    +        child.add_argument("--model", help="Model identity/path recorded in the experiment")
    +        child.add_argument("--model-revision")
    +        child.add_argument("--output-dir", default="runs")
    +        child.add_argument("--dry-run", action="store_true")
    +
    +    for name in ("status", "report"):
    +        child = commands.add_parser(
    +            name,
    +            help="Read a recorded experiment" if name == "status" else "Regenerate its HTML report",
    +        )
    +        child.add_argument("--run-id", required=True)
    +        child.add_argument("--output-dir", default="runs")
    +
    +    knowledge = commands.add_parser(
    +        "knowledge", help="Search or inspect source-grounded imported experience"
    +    )
    +    actions = knowledge.add_subparsers(dest="knowledge_action", required=True)
    +    search = actions.add_parser("search")
    +    search.add_argument("query", nargs="?", default="")
    +    search.add_argument("--repo-type", choices=REPO_TYPES)
    +    search.add_argument("--backend", choices=BACKENDS)
    +    search.add_argument("--scenario")
    +    search.add_argument("--limit", type=int, default=10)
    +    search.add_argument("--json", action="store_true")
    +    show = actions.add_parser("show")
    +    show.add_argument("id")
    +    context = commands.add_parser(
    +        "context", help="Export cited knowledge for manual Codex/Agent handoff"
    +    )
    +    context.add_argument("query", nargs="?", default="")
    +    context.add_argument("--repo-type", choices=REPO_TYPES, required=True)
    +    context.add_argument("--backend", choices=BACKENDS, required=True)
    +    context.add_argument("--scenario")
    +    context.add_argument("--limit", type=int, default=5)
    +    context.add_argument("--output", help="Write a Markdown context file instead of stdout")
    +    return root
    +
    +
    +def device_ids(args: argparse.Namespace) -> tuple[str, ...]:
    +    values = tuple(value.strip() for value in args.device_ids.split(",") if value.strip())
    +    if len(set(values)) != len(values):
    +        raise ValueError("device IDs must be unique")
    +    return values
    +
    +
    +def make_spec(args: argparse.Namespace) -> RunSpec:
    +    def command(value: str | None) -> tuple[str, ...] | None:
    +        if value is None:
    +            return None
    +        parsed = tuple(shlex.split(value, posix=True))
    +        if not parsed:
    +            raise ValueError("Commands cannot be empty")
    +        return parsed
    +
    +    spec = RunSpec(
    +        repo=str(Path(args.repo).resolve()),
    +        candidate_repo=str(Path(args.candidate_repo).resolve()) if args.candidate_repo else None,
    +        repo_type=args.repo_type,
    +        backend=args.backend,
    +        scenario=args.scenario,
    +        mode=args.mode,
    +        baseline_command=command(args.baseline_command),
    +        candidate_command=command(args.candidate_command),
    +        validation_command=command(args.validation_command),
    +        metric_key=args.metric_key,
    +        metric_unit=args.metric_unit,
    +        comparison_scope=args.comparison_scope,
    +        direction=args.direction,
    +        repetitions=args.repetitions,
    +        min_improvement_pct=args.min_improvement_pct,
    +        max_minutes=args.max_minutes,
    +        workload_id=args.workload_id,
    +        model=args.model,
    +        model_revision=args.model_revision,
    +        agent=args.agent,
    +        device_ids=device_ids(args),

    <sub><sub>!P2 Badge</sub></sub> Preserve the selected executor in RunSpec

    --executor is part of the plan/run CLI and resolves to local, but make_spec never copies args.executor, leaving every CLI-generated plan and run.lock.json with RunSpec.executor == "default". This records an executor value users cannot select and loses execution provenance; pass the parsed executor into the snapshot.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 12, 2026 08:56 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 16393ae493

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    david6666666 david6666666 commented on Oct 12, 2026 09:06 UTC
    Author

    Updated in 9a9b2d605c999667da539b4b5b08b64e58d23575 (DCO signed).

  • Translated all remaining Chinese repository prose to English: the README, historical LTX-2.5 test plan, and optimization task prompt.

  • Preserved docs/assets/component-architecture.svg and docs/assets/gpu-workflow.svg byte-for-byte.

  • Added component-architecture-en.svg and gpu-workflow-en.svg, with English titles, descriptions, labels, and adjusted text layout.

  • Both English diagrams are embedded in the README and architecture guide; links to the Chinese originals remain available. The diagrams retain their documented scope as the target architecture and long-term workflow.
  • Validation: a repository-wide language scan finds Chinese only in the two preserved originals; original SHA-256 hashes are unchanged; both English SVGs parse with valid accessibility/marker references and were rendered and visually checked; relative Markdown links resolve; executable documentation code blocks are unchanged except for a translated shell comment; git diff --check passes. This is a documentation/assets update, so no new GPU or performance results are claimed.

    The existing nine commits remain intact and ordered. This is one appended commit, bringing the PR to ten commits. Historical discussion comments have not been rewritten.

    david6666666 david6666666 commented on Oct 12, 2026 09:18 UTC
    Author

    README refresh in 7ca4829f91a9e7d4a8e6cec829ffded2e0db4e5d (DCO signed).

    View the new README

  • Removed the entire CPU contract smoke-test section and synthetic benchmark example from the README.

  • Followed the requested OpenRSI presentation structure: a centered visual introduction, compact navigation, clear project value, a prominent result, and a short getting-started path.

  • Added an original OmniRSI SVG banner. Reduced README text from approximately 1,628 to 438 whitespace-delimited words (73% fewer).

  • Kept the recorded 30.60% result with its workload, accuracy scope, acceptance issue, and full evidence links. No new performance claim or measurement is introduced.

  • Kept both English diagrams embedded in expandable sections, with links to the unchanged Chinese originals. Detailed implementation and experiment information is reached through documentation links.

  • Removed the quickstart guide's stale instruction to run a synthetic example from the README.
  • Validation: GitHub's Markdown renderer retains all navigation anchors, both diagram expanders, and all three local images. Relative paths and fragment targets resolve; the new SVG parses and was rendered and visually inspected. Both displayed knowledge/context commands execute successfully against this checkout. git diff --check passes. All prior commits remain intact and ordered.

    amy-why-3459 amy-why-3459 commented on Oct 12, 2026 09:28 UTC
    Contributor

    Ascend 910B follow-up, separate from the B300 PASS

    One 910B1, Qwen-Image-2.1-Turbo, BF16, eager, TORCH_SDPA, CFG=1, 1280×704, native 8 sigmas. Two warmup rounds, then three repeated prompts, seeds 42/43/44. Unoptimized baseline mean 3111.5 ms. A 30% line is 2178 ms. This cohort does not reach it and does not replace the B300 384.16 → 266.60 ms PASS.

    | Stack | Mean of 3 | vs 3111.5 ms | RGBA |
    | --- | ---: | ---: | --- |
    | Conditioning reuse only | 2654.3 ms | −14.7% | identical |
    | Reuse + NPU interleaved RoPE | 2459.6 ms | −21.0% | identical |
    | Reuse + NPU RoPE + QWEN21_VAE_FASTPATH=1 | 2425.5 ms | −22.0% | quality gate passed, not pixel-identical |
    | Same stack, later rerun | 2431.9 ms | −21.8% | quality gate passed, not pixel-identical |

    The first published conditioning-reuse number on this host was 2658.2 ms (−14.6%). NPU RoPE uses npu_rotary_mul interleave mode. Atlas A2 npu_apply_rotary_pos_emb has no interleave pairing. The cos/sin table follows the current freqs tensor and is sliced to the target-token tail on decode.

    Rejected without changing steps, resolution, or the sampler: eager RoPE cos/sin cache, per-step mask/prompt tensor cache (OOM), expanded SDPA mask cache, npu_fusion_attention at precise 2 / 0 / decode-only, TASK_QUEUE_ENABLE=1 and =2, enforce_eager=0 (2718.8 ms, slower), dropping the autograd guard on the prompt cache, and RoPE + VAE fastpath + fusion attention (OOM during initialization).

    A timed first request on the RoPE + VAE stack spent about 550 ms in prompt encode, 1.5 s in the 8-step denoise, and 190 ms in the VAE. Denoise is still the largest piece.

    Upstream patch: https://github.com/vllm-project/vllm-omni/pull/8729 at 399cc01d1. vLLM 0.31.0. Ascend image-generation context:

    python -m omnirsi context --repo-type vllm_omni --backend ascend \
      --scenario diffusion.image_generation --output diffusion-context.md
    

    Imported Ascend records are mostly diffusion.video_generation, so this export returns the shared diffusion.* guidance. Medians are descriptive. This is not the B300 five-group HTTP result.

    david6666666 david6666666 commented on Oct 13, 2026 02:34 UTC
    Author

    Modular refactor completed: implemented boundaries and regression results

    The local experiment framework now has concrete Harness × Model × Infra modules. Previously shared infrastructure lived in model examples, and the three extension directories were mostly placeholders. New adapters can reuse one AB/BA scheduler, process cleanup implementation and performance evaluator.

    Four separate DCO-signed commits were appended in the requested order. The previous 14 commits, including the Ascend contributor's commits and attribution, remain unchanged:

    | Commit | Change |
    | --- | --- |
    | 3f1d72f | Extract source identity, artifact hashing, environment checks, device qualification and owned-process lifecycle into Infra; remove the Qwen runner's direct dependency on the LTX helper. |
    | 5542bca | Move AB/BA orchestration, external scenarios, evaluation and reports into Harness; separate local execution and platform probes; retain root compatibility entrypoints. |
    | da842f5 | Add model-neutral request/metric protocols, reusable warmup/sample collection and explicit image quality gates; test extension through scenario/target/backend adapters. |
    | ab343f9 | Add the two implemented-architecture diagrams, directory/extension guide and refactor regression evidence. |

    Implemented module architecture

    !Implemented modules

    Module-to-directory map

    !Directory map

    | Extension | Primary locations |
    | --- | --- |
    | Model or scenario | model/protocols, model/validators, harness/scenarios |
    | Repository | infra/targets, a composed scenario, data/repo_packs |
    | Hardware | infra/platforms, data/platform_packs, independent backend qualification |

    Architecture, callable contracts and extension examples. Named repository/backend registrations still require catalog descriptors; the shared orchestration, cleanup and adjudication algorithms do not change.

    Verification

    | Check | Result |
    | --- | --- |
    | Full control suite, including optional image-validator tests | 123 passed, 60 subtests |
    | Extension boundary | New metric schema, non-Git target and backend probe reuse the actual AB/BA runner and real subprocess executor |
    | HTTP sampling and quality | Real local HTTP transport; first-output retention, partial evidence, RGB/alpha drift and hash mismatch coverage |
    | Noneditable wheel in a separate dependency-free environment | All 40 Python modules packaged; CLI run/status/report, source checks and Ascend context work without source checkout imports |
    | Historical frozen validators and their LTX helper | Four files byte-for-byte unchanged |
    | Lint, formatting and whitespace in the refactor range | Passed |
    | Full-step Qwen functional E2E on 4× B300 | Both runners completed; 4/4 corresponding native RGBA pairs pixel-identical, including the first response |
    | E2E integrity and cleanup | Source, dependencies, model assets and helper checks passed; no surviving owned processes; GPUs returned to zero allocated memory |

    The GPU comparison used pre-refactor OmniRSI 884ea89 versus modular da842f5, with unchanged vLLM-Omni 6550e3f6, the same prepared runtime/model/cache and GPUs 0/1/2/3. Each side started a fresh server, ran six warmups and three complete 1280×704, BF16, native eight-step, TP1/Ulysses4, eager/FA4 requests. RGB and alpha were compared at native resolution with verified output hashes; all maximum pixel differences are zero.

    The one-run request means were 276.1044 ms before / 276.4625 ms after. This is a functional regression smoke, not a new latency optimization or statistical equivalence claim. Existing B300/NPU performance results retain their original scope. Plan, raw-metric/output-hash summary, CPU log, wheel smoke and validator. Native PNGs and full server logs are retained locally as documented; the 28 MiB image bundle is not committed.

    Compatibility boundary

    Existing CLI flags, root import paths and JSON/report contracts are preserved. Historical ltx25_quality.py, qwen21_turbo_quality.py, qwen21_turbo_validation_adapter.py, and their transitive ltx25_b300.py helper remain frozen. That historical validator dependency is intentional; new shared modules do not import campaign examples. Fresh campaigns must freeze new helper hashes/references instead of mixing this runner with old manifests.

    Automatic agents, SSH execution, distributed leases and Hub publication remain future work. ROCm/Ascend discovery is not a new compatibility certification. The two earlier Chinese diagrams and their English variants are preserved, and the README now displays the two implemented-boundary diagrams above.

    david6666666 david6666666 commented on Oct 13, 2026 06:24 UTC
    Author

    Focused Qwen documentation and examples

    Updated in DCO-signed commit 168c81f9d6ba331e13a3f613dec6619b79451732; previous commits remain in order.

  • docs/: 26 → 5 Markdown files, 1,880 → 705 lines. Retained quickstart, architecture, contribution rules, and one guide each for Qwen-Image-2.1-Turbo B300 and Ascend. Removed duplicate plans/drafts/prompts, obsolete LTX material and template stubs.

  • examples/: three maintained Qwen entrypoints: B300 runner, PNG quality validator and the historical v4 directory adapter. Synthetic scripts and frozen legacy helpers are test fixtures. The complete historical patch is now under evidence/; the redundant phase-1 patch is recoverable from history.

  • B300 profiling, H1–H19 decisions, failed cohorts, source pins, reproduction and review lessons are consolidated. Ascend attribution, non-pixel-identical VAE scope and locally_verified=false remain explicit. Both architecture diagrams and the original Chinese/English assets are retained.

  • Current Qwen validation now imports shared artifact utilities directly and no longer imports LTX. Numerical/manifest checks are unchanged; historical implementations remain byte-for-byte frozen in fixtures. Current helper hashes require fresh references for new campaigns.
  • Qwen B300 guide · Qwen Ascend guide · Contribution rules

    Validation: 126 passed, 60 subtests; Ruff and changed-range whitespace checks pass. Maintained Markdown file links and anchors resolve; all three Qwen entrypoints load and guard hashes cover the shared utilities. Added current-versus-frozen validator comparisons on native-sized synthetic RGBA images for identical outputs, RGB regressions and alpha regressions. No GPU/NPU inference rerun or new performance claim is attributed to this documentation cleanup. Historical evidence manifests are untouched.

    david6666666 david6666666 commented on Oct 13, 2026 07:05 UTC
    Author

    Knowledge consolidation and CLI compatibility

    Implemented in 3e1eb20 with DCO. Existing commits are preserved in order.

    Previously, search/show/context read only experience.json; the per-entry README repeated much of the same content, and the hand-maintained index missed one entry. The pack now has one JSON file per experience and one README for navigation and maintenance.

    data/repo_packs/<repo>/knowledge/
      README.md
      common/diffusion/<entry>.json   3 common methods
      cuda/diffusion/<entry>.json     6 CUDA cases
      ascend/diffusion/<entry>.json   3 Ascend cases
    

  • Directory ownership: repository → backend → component → entry. Model, scenario, SKU, dtype/software prerequisites and tags stay in fields, avoiding copies for every model.

  • One canonical content source: search/show and readable context use the same JSON. The loader checks directory/ID/scope consistency before retrieval.

  • Evidence maturity is separate from directory scope and merge status. All current records remain imported and locally_verified=false; upstream_reported describes an imported report, without upgrading its credibility.

  • Removed PR and review-thread links from all knowledge records and exported context. Retained source repositories, revisions, dates, known authors, limitations and negative results. A repository link is explicitly source attribution, not measurement evidence.

  • Incorporated portable lessons on independent benchmark review/freezing and focused tests for behavior absent from E2E coverage.
  • Validation: 135 tests and 60 subtests pass; Ruff, formatting and whitespace checks pass. The clean wheel contains exactly 12 JSON records and one README and matches the source resources byte-for-byte. Installed search/show/context and external-process synthetic AB/BA/status/report work without inference dependencies. All 12 record IDs and CLI arguments are preserved. New malformed-scope checks prevent misplaced records from leaking into another backend's context.

    No new GPU/NPU qualification or performance claim is made. Historical evidence is unchanged. Hierarchy, retrieval rules and maintenance workflow.

    david6666666 david6666666 commented on Oct 13, 2026 07:46 UTC
    Reviewer

    Found two additional evidence checks that can return PASS with incomplete or changed inputs. Both reproduced locally on this head.

    hsliuustc0106 hsliuustc0106 commented on code on Oct 13, 2026 11:01 UTC
    Code Review
    examples/qwen21_turbo_b300.py:1
    @@ -0,0 +1,272 @@
    +"""Frozen 720p-class Qwen-Image-2.1-Turbo online B300 campaign.
    +
    +Uses the stdlib OmniRSI infrastructure package for source/device/process
    +ownership. New campaigns must freeze fresh helper hashes and references.
    +"""
    +import argparse
    +import ast
    +import importlib.metadata
    +import json
    +import os
    +from pathlib import Path
    +import socket
    +from statistics import mean
    +import subprocess
    +import sys
    +import time
    +import urllib.request
    +
    +from omnirsi.harness.scenarios.media import collect_samples
    +from omnirsi.model.protocols.image import ImageProtocol
    +from omnirsi.infra import campaign as lifecycle
    +from omnirsi.infra.platforms.cuda import qualify_devices
    +
    +MODEL = "Qwen/Qwen-Image-2.1-Turbo"
    +REVISION = "d65dbc9a7e8f6b5479e33dee6030eaab2a906509"
    +SIGMAS = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
    +PROMPTS = [
    +    'A photorealistic red fox standing in a snowy forest at dawn, detailed fur, soft sunlight, a wide landscape composition.',
    +    'A clean product photograph of a blue ceramic teapot and two white cups on a wooden table, natural window lighting.',
    +    'A colorful travel poster of a rocky ocean coast at sunset with the exact headline "OCEAN JOURNEY", readable typography.',
    +]
    +HELD_OUT_PROMPTS = [
    +    'A watercolor painting of a yellow bicycle beside a purple flower shop, with three hanging baskets.',
    +    'A studio photograph of a transparent glass vase with five orange tulips on a dark green background.',
    +    'A minimalist book cover reading "NIGHT GARDEN", with silver moonlight and delicate blue flowers.',
    +]
    +PROTECTED_FILES = [
    +    'vllm_omni/model_extras/qwen_image_21.py',
    +    'vllm_omni/entrypoints/openai/diffusion.py',
    +    'vllm_omni/entrypoints/openai/api_server.py',
    +    'vllm_omni/entrypoints/openai/image_api_utils.py',
    +    'vllm_omni/diffusion/distributed/autoencoders/autoencoder_kl_qwenimage21.py',
    +]
    +PROTECTED_METHODS = {'__init__', 'prepare_timesteps', 'prepare_latents', '_pack_latents', '_unpack_latents'}
    +
    +
    +def protocol(diagnostic=False, profile_steps=2, held_out=False):
    +    if not 1 <= profile_steps <= 8:
    +        raise ValueError('Profile steps must be 1..8')
    +    sigmas = [SIGMAS[i * 7 // max(1, profile_steps - 1)] for i in range(profile_steps)] if diagnostic else SIGMAS
    +    return {'model': MODEL, 'model_revision': REVISION, 'width': 1280, 'height': 704,
    +            'dtype': 'bfloat16', 'true_cfg_scale': 1.0, 'sigmas': sigmas,
    +            'attention_backend': 'FLASH_ATTN', 'prefix_kv_cache': 'checkpoint_default_native',
    +            'compile_policy': 'enforce_eager',
    +            'codec': 'PNG', 'response_format': 'b64_json', 'concurrency': 1,
    +            'pixel_mode': 'RGBA', 'output_compression': 100,
    +            'prompts': [{'id': f'prompt-{i:03d}-seed-{(142 if held_out else 42)+i}', 'prompt': p,
    +                         'seed': (142 if held_out else 42)+i} for i,p in enumerate(HELD_OUT_PROMPTS if held_out else PROMPTS)],
    +            'warmup_seeds': [[10042,10043,10044],[11042,11043,11044]],
    +            'timing': 'POST until complete HTTP JSON response downloaded; PNG decode/write outside timer',
    +            'conditioning_scope': 'Repeated prompts with new seeds; deterministic conditioning reuse allowed; final-image reuse forbidden'}
    +
    +
    +def protected_sources(source):
    +    result = {p: lifecycle.sha256(source / p) for p in PROTECTED_FILES}
    +    relative = 'vllm_omni/diffusion/models/qwen_image_21/pipeline_qwen_image_21.py'
    +    tree = ast.parse((source / relative).read_text())
    +    for node in tree.body:
    +        if isinstance(node, ast.FunctionDef) and node.name in {'get_qwen_image_21_pre_process_func', 'get_qwen_image_21_post_process_func'}:
    +            result[relative + ':' + node.name] = lifecycle.digest(ast.dump(node, include_attributes=False))
    +    for node in tree.body:
    +        if isinstance(node, ast.ClassDef) and node.name == 'QwenImage21Pipeline':
    +            found = set()
    +            for method in node.body:
    +                if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)) and method.name in PROTECTED_METHODS:
    +                    result[relative + ':' + method.name] = lifecycle.digest(ast.dump(method, include_attributes=False))
    +                    found.add(method.name)
    +            if found != PROTECTED_METHODS:
    +                raise ValueError('Protected pipeline method missing')
    +            break
    +    else:
    +        raise ValueError('Protected pipeline class missing')
    +    return result
    +
    +
    +def dependencies():
    +    versions = lifecycle.semantic_dependency_versions(lifecycle.dependency_versions())
    +    for name in ['Pillow', 'numpy', 'scikit-image', 'flash-attn-4', 'nvidia-cutlass-dsl', 'kernels']:
    +        versions[name] = importlib.metadata.version(name)
    +    return versions
    +
    +
    +def model_assets(model, cache):
    +    manifest = cache.parent/'artifacts/model-assets.json'
    +    assets = json.loads(manifest.read_text())
    +    if Path(assets['model']).resolve() != model or assets['revision'] != REVISION:
    +        raise ValueError('Model asset manifest does not match the pinned snapshot')
    +    actual = {str(p.relative_to(model)) for p in model.rglob('*') if p.is_file()}
    +    if actual != {item['path'] for item in assets['files']}:
    +        raise ValueError('Model file coverage changed')
    +    for item in assets['files']:
    +        stat = (model/item['path']).stat()
    +        if (stat.st_size, stat.st_mtime_ns) != (item['bytes'], item['mtime_ns']):
    +            raise ValueError('Model asset changed after SHA256 freeze')

    [P2] Verify actual model bytes against the frozen SHA-256

    model_assets checks each file's size and mtime but never compares its contents with the manifest's per-file sha256. I reproduced this by changing weight.bin from original to modified (same length), restoring its original mtime with os.utime, and calling model_assets again: it accepted the modified weights and returned the same manifest hash, although the actual file digest no longer matched. Timestamp-preserving replacement can therefore retain a verified pinned-model identity while running different weights. Compare each actual file digest with its frozen digest. This previously reported concern remains unresolved at the reviewed head.

    hsliuustc0106 hsliuustc0106 commented on code on Oct 13, 2026 11:01 UTC
    Code Review
    examples/qwen21_turbo_quality.py:1
    @@ -0,0 +1,140 @@
    +"""Independent PNG accuracy and frozen-protocol gate for Qwen Turbo trials."""
    +import argparse
    +import json
    +import math
    +import os
    +from pathlib import Path
    +import sys
    +
    +from omnirsi.infra import artifacts as lifecycle
    +
    +
    +def load(path):
    +    value=json.loads(Path(path).read_text())
    +    if value.get('status')!='completed' or value.get('diagnostic') or not value.get('source_integrity',{}).get('verified'):
    +        raise ValueError('Completed non-diagnostic source-stable trial required')
    +    if lifecycle.digest(value['protocol'])!=value['protocol_sha256']:
    +        raise ValueError('Invalid protocol digest')
    +    return value
    +
    +
    +def owned_artifact_paths(manifest, manifest_path):
    +    """Resolve each saved output beneath its own trial, never the reference or another trial."""
    +    root = Path(manifest_path).resolve().parent
    +    entries = [*manifest['artifacts'], manifest['first_request']]
    +    paths = set()
    +    for entry in entries:
    +        path = Path(entry['path'])
    +        path = (path if path.is_absolute() else root / path).resolve()
    +        if not path.is_relative_to(root) or not path.is_file():
    +            raise ValueError('Artifact must be a file within its trial directory')
    +        if path in paths:
    +            raise ValueError('Reused artifact path within a trial')
    +        paths.add(path)
    +        entry['path'] = str(path)
    +    return paths
    +
    +
    +def compare_images(item, other):
    +    from PIL import Image
    +    import numpy as np
    +    from skimage.metrics import structural_similarity
    +    arrays=[]
    +    for entry in [other,item]:
    +        if lifecycle.sha256(entry['path'])!=entry['sha256']:raise ValueError('PNG hash mismatch')
    +        with Image.open(entry['path']) as image:
    +            image.load()
    +            if image.format!='PNG' or image.size!=(1280,704) or image.mode!='RGBA':
    +                raise ValueError('Expected complete 1280x704 native RGBA PNG')
    +            arrays.append(np.asarray(image).copy())
    +    a,b=arrays
    +    mse=float(np.mean((a.astype(np.float64)-b.astype(np.float64))**2))
    +    psnr=math.inf if mse==0 else 10*math.log10(255**2/mse)
    +    ssim=float(structural_similarity(a,b,channel_axis=2,data_range=255))
    +    channel_metrics=[]
    +    for name, left, right in [('rgb',a[:,:,:3],b[:,:,:3]),('alpha',a[:,:,3],b[:,:,3])]:
    +        channel_mse=float(np.mean((left.astype(np.float64)-right.astype(np.float64))**2))
    +        channel_psnr=math.inf if channel_mse==0 else 10*math.log10(255**2/channel_mse)
    +        channel_ssim=float(structural_similarity(left,right,channel_axis=2 if name=='rgb' else None,data_range=255))
    +        channel_metrics.append({'channel':name,'ssim':channel_ssim,'psnr_db':'inf' if channel_mse==0 else channel_psnr,
    +                                'passed':channel_ssim>=0.99 and channel_psnr>=35})
    +    passed=all(x['passed'] for x in channel_metrics)
    +    return {'ssim':ssim,'psnr_db':'inf' if mse==0 else psnr,
    +                    'channels':channel_metrics,'verdict':'PASS' if passed else 'FAIL'}
    +
    +
    +def validate(reference_path,candidate_path,expected_parallel=None,*,seen_paths=None):
    +    ref,cand=load(reference_path),load(candidate_path)
    +    reference_paths = owned_artifact_paths(ref, reference_path)
    +    candidate_paths = owned_artifact_paths(cand, candidate_path)
    +    if reference_paths & candidate_paths or (seen_paths is not None and seen_paths & candidate_paths):
    +        raise ValueError('Reused reference or cross-trial artifact paths')
    +    if seen_paths is not None:
    +        seen_paths.update(candidate_paths)
    +    for name in ['protocol','protocol_sha256','protected_sources','guard_hashes','dependency_versions','model_assets_sha256']:
    +        if ref[name]!=cand[name]:raise ValueError(f'Frozen {name} mismatch')
    +    if expected_parallel and (cand['parallel']['tp'],cand['parallel']['ulysses'])!=expected_parallel:
    +        raise ValueError('Frozen winner parallel mismatch')
    +    refs={item['id']:item for item in ref['artifacts'] if item['group']==1}
    +    expected={item['id'] for item in ref['protocol']['prompts']}
    +    if set(refs)!=expected or len(ref['artifacts'])!=3 or len(ref['groups_ms'])!=1:
    +        raise ValueError('Canonical reference coverage mismatch')
    +    groups={item['group'] for item in cand['artifacts']}
    +    if groups!=set(range(1,len(cand['groups_ms'])+1)):raise ValueError('Missing candidate group')
    +    if len(cand['artifacts'])!=len(groups)*len(expected):raise ValueError('Wrong artifact count')

    [P2] Reject candidate manifests with zero measured image groups

    The coverage checks accept groups_ms=[] and artifacts=[]: both the group-set equality and artifact-count equality hold for empty inputs. I reproduced this using the artifact-ownership fixture, retaining the candidate's owned first-request image and matching frozen metadata while clearing those two arrays; validate(reference, candidate, (1, 4)) returned PASS with exactly one comparison and zero measured images. Require a positive candidate group count and complete measured-image coverage before comparing the first request, so partial evidence cannot pass the quality gate.

    hsliuustc0106 hsliuustc0106 commented on code on Oct 13, 2026 11:01 UTC
    Code Review
    src/omnirsi/harness/evaluation.py:1
    @@ -0,0 +1,97 @@
    +"""Evidence gates, independent from command execution and Agent assertions."""
    +
    +import math
    +
    +from ..claim import Verdict
    +from ..model.protocols.metrics import read_metric as read_metric
    +from ..runspec import RunSpec
    +
    +
    +def _summary(trials: list[dict]) -> dict | None:
    +    values = [trial["metric"] for trial in trials if trial.get("metric") is not None]
    +    if not values:
    +        return None
    +    ordered = sorted(values)
    +    midpoint = len(ordered) // 2
    +    middle = (
    +        ordered[midpoint]
    +        if len(ordered) % 2
    +        else ordered[midpoint - 1] + (ordered[midpoint] - ordered[midpoint - 1]) / 2
    +    )
    +    spread = (max(values) - min(values)) / middle * 100
    +    return {
    +        "values": values,
    +        "median": middle,
    +        "min": min(values),
    +        "max": max(values),
    +        "range_pct_of_median": spread if math.isfinite(spread) else None,
    +    }
    +
    +
    +def evaluate(
    +    spec: RunSpec,
    +    baseline: list[dict],
    +    candidate: list[dict],
    +    validation: dict | None,
    +    integrity: dict | None = None,
    +) -> dict:
    +    failed, incomplete = [], []
    +    for label, trials in (("baseline", baseline), ("candidate", candidate)):
    +        if len(trials) != spec.repetitions:
    +            incomplete.append(
    +                f"{label}: expected {spec.repetitions} trials, recorded {len(trials)}"
    +            )
    +        for index, trial in enumerate(trials, 1):
    +            if trial.get("status") in {"failed", "timeout", "error"}:
    +                failed.append(f"{label} trial {index}: {trial.get('status')}")
    +            elif trial.get("status") != "completed":
    +                incomplete.append(f"{label} trial {index}: {trial.get('status')}")
    +            if trial.get("metric") is None:
    +                incomplete.append(
    +                    f"{label} trial {index}: {trial.get('metric_error') or 'metric missing'}"
    +                )
    +    if validation is None:
    +        incomplete.append("quality validation command was not supplied")
    +    elif validation.get("status") in {"failed", "timeout", "error"}:
    +        failed.append(f"quality validation: {validation.get('status')}")
    +    elif validation.get("status") != "completed":
    +        incomplete.append(f"quality validation: {validation.get('status')}")
    +    if integrity is None or not integrity.get("verified"):
    +        incomplete.append((integrity or {}).get("reason", "source integrity was not verified"))
    +
    +    before, after = _summary(baseline), _summary(candidate)
    +    improvement = None
    +    all_metrics = len(baseline) == len(candidate) == spec.repetitions and all(
    +        t.get("status") == "completed" and t.get("metric") is not None for t in baseline + candidate
    +    )
    +    if all_metrics:
    +        improvement = (after["median"] - before["median"]) / before["median"] * 100
    +        if spec.direction == "minimize":
    +            improvement *= -1
    +        if not math.isfinite(improvement):
    +            improvement = None
    +            incomplete.append("derived improvement is not finite; check metric scale and units")
    +        elif improvement <= 0 or improvement < spec.min_improvement_pct:
    +            failed.append(
    +                f"measured gain {improvement:.6g}% must be positive and meet "
    +                f"{spec.min_improvement_pct:.6g}% threshold"
    +            )
    +    verdict = Verdict.FAIL if failed else Verdict.INCONCLUSIVE if incomplete else Verdict.PASS

    [P2] Keep incomplete experiments INCONCLUSIVE

    This precedence makes any failed/timeout trial produce a conclusive campaign FAIL even when the requested comparison never completed. I reproduced a five-repetition spec with one baseline timeout, no candidate trials and no quality result: evaluate returned FAIL alongside reasons reporting the missing trials and quality evidence. The repository contract in AGENTS.md and docs/contributing.md specifies INCONCLUSIVE for partial runs or incomplete evidence. Preserve execution failure in run status and reasons, while keeping the campaign verdict INCONCLUSIVE until enough frozen evidence exists to adjudicate a gate; also account for the runner's explicit failed-verdict override when handling execution exceptions. This previously reported concern remains unresolved at the reviewed head.

    hsliuustc0106 hsliuustc0106 commented on Oct 13, 2026 11:01 UTC
    Reviewer

    Reviewed frozen head 3e1eb205ed874e594ac596c122838f9380d6cc37. Three actionable issues remain, detailed inline.

    Validation: the CPU suite passed after resolving local import-path conflicts (an installed tests package shadowed the repository tests, and subprocess imports needed PYTHONPATH=src); Ruff passed. No GPU/NPU execution was performed. The model-hash and partial-verdict concerns were already raised in existing review comments and remain unresolved at this head.

    david6666666 david6666666 commented on code on Oct 13, 2026 11:40 UTC
    Code Review
    examples/qwen21_turbo_b300.py:1
    @@ -0,0 +1,272 @@
    +"""Frozen 720p-class Qwen-Image-2.1-Turbo online B300 campaign.
    +
    +Uses the stdlib OmniRSI infrastructure package for source/device/process
    +ownership. New campaigns must freeze fresh helper hashes and references.
    +"""
    +import argparse
    +import ast
    +import importlib.metadata
    +import json
    +import os
    +from pathlib import Path
    +import socket
    +from statistics import mean
    +import subprocess
    +import sys
    +import time
    +import urllib.request
    +
    +from omnirsi.harness.scenarios.media import collect_samples
    +from omnirsi.model.protocols.image import ImageProtocol
    +from omnirsi.infra import campaign as lifecycle
    +from omnirsi.infra.platforms.cuda import qualify_devices
    +
    +MODEL = "Qwen/Qwen-Image-2.1-Turbo"
    +REVISION = "d65dbc9a7e8f6b5479e33dee6030eaab2a906509"
    +SIGMAS = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
    +PROMPTS = [
    +    'A photorealistic red fox standing in a snowy forest at dawn, detailed fur, soft sunlight, a wide landscape composition.',
    +    'A clean product photograph of a blue ceramic teapot and two white cups on a wooden table, natural window lighting.',
    +    'A colorful travel poster of a rocky ocean coast at sunset with the exact headline "OCEAN JOURNEY", readable typography.',
    +]
    +HELD_OUT_PROMPTS = [
    +    'A watercolor painting of a yellow bicycle beside a purple flower shop, with three hanging baskets.',
    +    'A studio photograph of a transparent glass vase with five orange tulips on a dark green background.',
    +    'A minimalist book cover reading "NIGHT GARDEN", with silver moonlight and delicate blue flowers.',
    +]
    +PROTECTED_FILES = [
    +    'vllm_omni/model_extras/qwen_image_21.py',
    +    'vllm_omni/entrypoints/openai/diffusion.py',
    +    'vllm_omni/entrypoints/openai/api_server.py',
    +    'vllm_omni/entrypoints/openai/image_api_utils.py',
    +    'vllm_omni/diffusion/distributed/autoencoders/autoencoder_kl_qwenimage21.py',
    +]
    +PROTECTED_METHODS = {'__init__', 'prepare_timesteps', 'prepare_latents', '_pack_latents', '_unpack_latents'}
    +
    +
    +def protocol(diagnostic=False, profile_steps=2, held_out=False):
    +    if not 1 <= profile_steps <= 8:
    +        raise ValueError('Profile steps must be 1..8')
    +    sigmas = [SIGMAS[i * 7 // max(1, profile_steps - 1)] for i in range(profile_steps)] if diagnostic else SIGMAS
    +    return {'model': MODEL, 'model_revision': REVISION, 'width': 1280, 'height': 704,
    +            'dtype': 'bfloat16', 'true_cfg_scale': 1.0, 'sigmas': sigmas,
    +            'attention_backend': 'FLASH_ATTN', 'prefix_kv_cache': 'checkpoint_default_native',
    +            'compile_policy': 'enforce_eager',
    +            'codec': 'PNG', 'response_format': 'b64_json', 'concurrency': 1,
    +            'pixel_mode': 'RGBA', 'output_compression': 100,
    +            'prompts': [{'id': f'prompt-{i:03d}-seed-{(142 if held_out else 42)+i}', 'prompt': p,
    +                         'seed': (142 if held_out else 42)+i} for i,p in enumerate(HELD_OUT_PROMPTS if held_out else PROMPTS)],
    +            'warmup_seeds': [[10042,10043,10044],[11042,11043,11044]],
    +            'timing': 'POST until complete HTTP JSON response downloaded; PNG decode/write outside timer',
    +            'conditioning_scope': 'Repeated prompts with new seeds; deterministic conditioning reuse allowed; final-image reuse forbidden'}
    +
    +
    +def protected_sources(source):
    +    result = {p: lifecycle.sha256(source / p) for p in PROTECTED_FILES}
    +    relative = 'vllm_omni/diffusion/models/qwen_image_21/pipeline_qwen_image_21.py'
    +    tree = ast.parse((source / relative).read_text())
    +    for node in tree.body:
    +        if isinstance(node, ast.FunctionDef) and node.name in {'get_qwen_image_21_pre_process_func', 'get_qwen_image_21_post_process_func'}:
    +            result[relative + ':' + node.name] = lifecycle.digest(ast.dump(node, include_attributes=False))
    +    for node in tree.body:
    +        if isinstance(node, ast.ClassDef) and node.name == 'QwenImage21Pipeline':
    +            found = set()
    +            for method in node.body:
    +                if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)) and method.name in PROTECTED_METHODS:
    +                    result[relative + ':' + method.name] = lifecycle.digest(ast.dump(method, include_attributes=False))
    +                    found.add(method.name)
    +            if found != PROTECTED_METHODS:
    +                raise ValueError('Protected pipeline method missing')
    +            break
    +    else:
    +        raise ValueError('Protected pipeline class missing')
    +    return result
    +
    +
    +def dependencies():
    +    versions = lifecycle.semantic_dependency_versions(lifecycle.dependency_versions())
    +    for name in ['Pillow', 'numpy', 'scikit-image', 'flash-attn-4', 'nvidia-cutlass-dsl', 'kernels']:
    +        versions[name] = importlib.metadata.version(name)
    +    return versions
    +
    +
    +def model_assets(model, cache):
    +    manifest = cache.parent/'artifacts/model-assets.json'
    +    assets = json.loads(manifest.read_text())
    +    if Path(assets['model']).resolve() != model or assets['revision'] != REVISION:
    +        raise ValueError('Model asset manifest does not match the pinned snapshot')
    +    actual = {str(p.relative_to(model)) for p in model.rglob('*') if p.is_file()}
    +    if actual != {item['path'] for item in assets['files']}:
    +        raise ValueError('Model file coverage changed')
    +    for item in assets['files']:
    +        stat = (model/item['path']).stat()
    +        if (stat.st_size, stat.st_mtime_ns) != (item['bytes'], item['mtime_ns']):
    +            raise ValueError('Model asset changed after SHA256 freeze')

    Confirmed and fixed in 82218b4. Every actual model file is now streamed through SHA-256 and compared with its frozen per-file digest; size/mtime and coverage checks remain. The regression replaces original with equal-length modified bytes and restores the original mtime: the reviewed implementation accepts it, while the fix rejects it. I also verified all files in the prepared real model snapshot against the existing frozen SHA-256 manifest. Hashing is outside HTTP measurement timing and is repeated during final integrity checks.

    david6666666 david6666666 commented on code on Oct 13, 2026 11:40 UTC
    Code Review
    examples/qwen21_turbo_quality.py:1
    @@ -0,0 +1,140 @@
    +"""Independent PNG accuracy and frozen-protocol gate for Qwen Turbo trials."""
    +import argparse
    +import json
    +import math
    +import os
    +from pathlib import Path
    +import sys
    +
    +from omnirsi.infra import artifacts as lifecycle
    +
    +
    +def load(path):
    +    value=json.loads(Path(path).read_text())
    +    if value.get('status')!='completed' or value.get('diagnostic') or not value.get('source_integrity',{}).get('verified'):
    +        raise ValueError('Completed non-diagnostic source-stable trial required')
    +    if lifecycle.digest(value['protocol'])!=value['protocol_sha256']:
    +        raise ValueError('Invalid protocol digest')
    +    return value
    +
    +
    +def owned_artifact_paths(manifest, manifest_path):
    +    """Resolve each saved output beneath its own trial, never the reference or another trial."""
    +    root = Path(manifest_path).resolve().parent
    +    entries = [*manifest['artifacts'], manifest['first_request']]
    +    paths = set()
    +    for entry in entries:
    +        path = Path(entry['path'])
    +        path = (path if path.is_absolute() else root / path).resolve()
    +        if not path.is_relative_to(root) or not path.is_file():
    +            raise ValueError('Artifact must be a file within its trial directory')
    +        if path in paths:
    +            raise ValueError('Reused artifact path within a trial')
    +        paths.add(path)
    +        entry['path'] = str(path)
    +    return paths
    +
    +
    +def compare_images(item, other):
    +    from PIL import Image
    +    import numpy as np
    +    from skimage.metrics import structural_similarity
    +    arrays=[]
    +    for entry in [other,item]:
    +        if lifecycle.sha256(entry['path'])!=entry['sha256']:raise ValueError('PNG hash mismatch')
    +        with Image.open(entry['path']) as image:
    +            image.load()
    +            if image.format!='PNG' or image.size!=(1280,704) or image.mode!='RGBA':
    +                raise ValueError('Expected complete 1280x704 native RGBA PNG')
    +            arrays.append(np.asarray(image).copy())
    +    a,b=arrays
    +    mse=float(np.mean((a.astype(np.float64)-b.astype(np.float64))**2))
    +    psnr=math.inf if mse==0 else 10*math.log10(255**2/mse)
    +    ssim=float(structural_similarity(a,b,channel_axis=2,data_range=255))
    +    channel_metrics=[]
    +    for name, left, right in [('rgb',a[:,:,:3],b[:,:,:3]),('alpha',a[:,:,3],b[:,:,3])]:
    +        channel_mse=float(np.mean((left.astype(np.float64)-right.astype(np.float64))**2))
    +        channel_psnr=math.inf if channel_mse==0 else 10*math.log10(255**2/channel_mse)
    +        channel_ssim=float(structural_similarity(left,right,channel_axis=2 if name=='rgb' else None,data_range=255))
    +        channel_metrics.append({'channel':name,'ssim':channel_ssim,'psnr_db':'inf' if channel_mse==0 else channel_psnr,
    +                                'passed':channel_ssim>=0.99 and channel_psnr>=35})
    +    passed=all(x['passed'] for x in channel_metrics)
    +    return {'ssim':ssim,'psnr_db':'inf' if mse==0 else psnr,
    +                    'channels':channel_metrics,'verdict':'PASS' if passed else 'FAIL'}
    +
    +
    +def validate(reference_path,candidate_path,expected_parallel=None,*,seen_paths=None):
    +    ref,cand=load(reference_path),load(candidate_path)
    +    reference_paths = owned_artifact_paths(ref, reference_path)
    +    candidate_paths = owned_artifact_paths(cand, candidate_path)
    +    if reference_paths & candidate_paths or (seen_paths is not None and seen_paths & candidate_paths):
    +        raise ValueError('Reused reference or cross-trial artifact paths')
    +    if seen_paths is not None:
    +        seen_paths.update(candidate_paths)
    +    for name in ['protocol','protocol_sha256','protected_sources','guard_hashes','dependency_versions','model_assets_sha256']:
    +        if ref[name]!=cand[name]:raise ValueError(f'Frozen {name} mismatch')
    +    if expected_parallel and (cand['parallel']['tp'],cand['parallel']['ulysses'])!=expected_parallel:
    +        raise ValueError('Frozen winner parallel mismatch')
    +    refs={item['id']:item for item in ref['artifacts'] if item['group']==1}
    +    expected={item['id'] for item in ref['protocol']['prompts']}
    +    if set(refs)!=expected or len(ref['artifacts'])!=3 or len(ref['groups_ms'])!=1:
    +        raise ValueError('Canonical reference coverage mismatch')
    +    groups={item['group'] for item in cand['artifacts']}
    +    if groups!=set(range(1,len(cand['groups_ms'])+1)):raise ValueError('Missing candidate group')
    +    if len(cand['artifacts'])!=len(groups)*len(expected):raise ValueError('Wrong artifact count')

    Confirmed and fixed in 82218b4. A candidate must contain at least one measured group before image comparisons. The existing group/ID/count/ownership checks still enforce complete measured coverage. New negative regressions cover first-response-only manifests and an incomplete measured group, and assert that neither reaches image comparison. The numerical RGB/alpha formulas and thresholds are unchanged; historical fixtures and published campaign records are untouched.

    david6666666 david6666666 commented on code on Oct 13, 2026 11:40 UTC
    Code Review
    src/omnirsi/harness/evaluation.py:1
    @@ -0,0 +1,97 @@
    +"""Evidence gates, independent from command execution and Agent assertions."""
    +
    +import math
    +
    +from ..claim import Verdict
    +from ..model.protocols.metrics import read_metric as read_metric
    +from ..runspec import RunSpec
    +
    +
    +def _summary(trials: list[dict]) -> dict | None:
    +    values = [trial["metric"] for trial in trials if trial.get("metric") is not None]
    +    if not values:
    +        return None
    +    ordered = sorted(values)
    +    midpoint = len(ordered) // 2
    +    middle = (
    +        ordered[midpoint]
    +        if len(ordered) % 2
    +        else ordered[midpoint - 1] + (ordered[midpoint] - ordered[midpoint - 1]) / 2
    +    )
    +    spread = (max(values) - min(values)) / middle * 100
    +    return {
    +        "values": values,
    +        "median": middle,
    +        "min": min(values),
    +        "max": max(values),
    +        "range_pct_of_median": spread if math.isfinite(spread) else None,
    +    }
    +
    +
    +def evaluate(
    +    spec: RunSpec,
    +    baseline: list[dict],
    +    candidate: list[dict],
    +    validation: dict | None,
    +    integrity: dict | None = None,
    +) -> dict:
    +    failed, incomplete = [], []
    +    for label, trials in (("baseline", baseline), ("candidate", candidate)):
    +        if len(trials) != spec.repetitions:
    +            incomplete.append(
    +                f"{label}: expected {spec.repetitions} trials, recorded {len(trials)}"
    +            )
    +        for index, trial in enumerate(trials, 1):
    +            if trial.get("status") in {"failed", "timeout", "error"}:
    +                failed.append(f"{label} trial {index}: {trial.get('status')}")
    +            elif trial.get("status") != "completed":
    +                incomplete.append(f"{label} trial {index}: {trial.get('status')}")
    +            if trial.get("metric") is None:
    +                incomplete.append(
    +                    f"{label} trial {index}: {trial.get('metric_error') or 'metric missing'}"
    +                )
    +    if validation is None:
    +        incomplete.append("quality validation command was not supplied")
    +    elif validation.get("status") in {"failed", "timeout", "error"}:
    +        failed.append(f"quality validation: {validation.get('status')}")
    +    elif validation.get("status") != "completed":
    +        incomplete.append(f"quality validation: {validation.get('status')}")
    +    if integrity is None or not integrity.get("verified"):
    +        incomplete.append((integrity or {}).get("reason", "source integrity was not verified"))
    +
    +    before, after = _summary(baseline), _summary(candidate)
    +    improvement = None
    +    all_metrics = len(baseline) == len(candidate) == spec.repetitions and all(
    +        t.get("status") == "completed" and t.get("metric") is not None for t in baseline + candidate
    +    )
    +    if all_metrics:
    +        improvement = (after["median"] - before["median"]) / before["median"] * 100
    +        if spec.direction == "minimize":
    +            improvement *= -1
    +        if not math.isfinite(improvement):
    +            improvement = None
    +            incomplete.append("derived improvement is not finite; check metric scale and units")
    +        elif improvement <= 0 or improvement < spec.min_improvement_pct:
    +            failed.append(
    +                f"measured gain {improvement:.6g}% must be positive and meet "
    +                f"{spec.min_improvement_pct:.6g}% threshold"
    +            )
    +    verdict = Verdict.FAIL if failed else Verdict.INCONCLUSIVE if incomplete else Verdict.PASS

    Confirmed and fixed in 82218b4. Incomplete evidence now takes precedence: failed/error/timeout measurements and interrupted validators produce INCONCLUSIVE while execution status and reasons retain the failure. Removed the runner exception override that forced FAIL. A completed nonzero quality command and a complete comparison missing its frozen gain threshold still produce FAIL. Regressions cover the five-repetition/one-timeout reproduction, measurement and validation deadlines, executor exceptions, and an observed latency regression with missing quality evidence. The latter remains INCONCLUSIVE while retaining the observed-gain reason.

    david6666666 david6666666 commented on Oct 13, 2026 11:53 UTC
    Author

    Follow-up to hsliuustc0106's review and upstream Qwen lessons

    Fixed in 82218b49bf5d6810866347d60789fda60235c9b0, appended as a separate DCO-signed commit. Existing commits remain in order.

    | Finding | Reproduction on the reviewed code | Fixed behavior |
    | --- | --- | --- |
    | Model provenance checked only size/mtime | Replacing a weight file with different bytes of the same length and restoring its mtime was accepted. | Hash every actual model file and compare its SHA-256 against the frozen manifest before launch and during final integrity verification. Hashing stays outside the HTTP latency timer. |
    | An empty measured group could pass quality | A candidate with only a first-response image and no measured groups passed. | Require a positive measured group count before comparing images, in addition to the existing complete artifact/ID/ownership checks. Missing measured artifacts are rejected before image comparison. |
    | Partial execution could be a conclusive failure | A timed-out partial experiment was marked FAIL. | Incomplete evidence takes precedence and yields INCONCLUSIVE, preserving the execution failure/timeout reasons. Fully observed quality or performance gate misses remain FAIL. |

    All three cases were reproduced against the reviewed version and checked against the fixes. The three human review threads have been answered and resolved.

    Validation

  • Full OmniRSI suite: 139 passed, 60 subtests passed.

  • Final knowledge/catalog checks after updating the imported review record: 19 passed, 2 subtests passed.

  • Ruff checks, changed-file formatting, git diff --check, and the knowledge export check passed.

  • The actual prepared Qwen model files matched their frozen per-file hashes; a standalone full-byte verification took 16.61 seconds in preparation. The manifest SHA-256 is 535e02b900befda61207adb71707eaa7499c2b02d4c0035def507c531a961cbc.

  • The updated runner completed a separate 4× B300 Qwen native HTTP correctness regression against upstream candidate 1215513757efbbb0a85e71d1c5466d5d9e01c327: the first response plus three measured outputs were 4/4 pixel-identical in both RGB and alpha to their corresponding frozen reference outputs. Source/helper/dependency and model-byte checks passed, and owned workers exited cleanly. This used the prepared environment, TP1/Ulysses4/Ring1/VAE1, BF16, eager/FA4, 1280×704 and the native eight-step schedule.
  • The earlier admission attempt correctly refused to launch while the selected GPUs still had the Ulysses regression workers; it was retained as a failed record. The successful image run used a fresh output directory after those workers exited. This is correctness evidence, not a new latency measurement or a requalification of the historical 30% result. Upstream review changes and validation.

    Lessons incorporated

    docs/contributing.md now describes byte-level provenance, complete quality coverage, and the distinction between execution status and evidence verdict. It also records the upstream review guidance: prefer module-level imports except for genuine optional transitive dependencies, share eligibility predicates, colocate tiny ownership types with their consumers, and preserve eager BF16 rounding points in exact fused kernels. The canonical vLLM-Omni review record includes the corresponding upstream references and remains labeled as imported knowledge, rather than being promoted to a fresh performance claim.

    Historical validator Python snapshots under tests/fixtures/legacy/ are unchanged. The maintained validator's coverage admission was tightened without changing image comparison formulas or thresholds.

    Reviewers
    Assignees
    david6666666 david6666666
    Labels
    risk: low confidence: 87.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 87.8% · Lower = rushed or shallow review
    87.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.7% · Safe to merge
    8.7%