部署D3-lite并验证图片判断与连续及间歇延迟

This commit is contained in:
tfarcraw 2026-11-12 21:15:29 +08:00
parent 77555d8565
commit 2146d9365d
5 changed files with 215 additions and 13 deletions

View File

@ -193,3 +193,36 @@ E:\Imajev\.venv\Scripts\python.exe tools/benchmark_imajev_chinese.py --output ar
- q28:完成条件要求底座到位且上盖扣紧,只确认底座、上盖状态没有记录,问步骤是否已完成,模型回答“否”;标准为“不确定”。
逐题中文材料、问题、选项、标准答案、模型结果及耗时在 `artifacts/imajev-benchmark/chinese-text-32.txt`;完整请求和响应在同名 JSON,推理前题库在 `chinese-text-32-questions.json`。
## D3-lite 独立测试
按要求停止 Imajev,D3-lite 安装于 `E:\D3Lite`,服务地址为 `http://127.0.0.1:8766`。Laya 继续停止;此服务尚未接入 SOP 自动推进。模型固定为 `vllm-sr/d3-lite@6c01fba14e74f63b70e1ef442b0b6d1b934339d5`。下载工具新增 `--repo`、`--revision`、`--modelscope`,镜像文件仍校验固定 Hugging Face 版本的大文件 SHA-256,加载时再用上游 `MODEL_MANIFEST.json` 全量校验。下载清单和实际运行配置在安装目录的 `local-model-manifest.json`、`local-serving-settings.json`。
独立环境只读复用现有 CUDA PyTorch,并在自身环境安装 Transformers 5.17.0 等依赖,不修改原模型环境。RTX 4060 Laptop 8GB,PyTorch 2.11.0+cu128,BF16 主干、FP32 读出、batch 1、最大 2048 token,保留上游 `noncausal_full_attention` 与默认温度。上游 fast path 在该 NVIDIA GPU 上未启用,使用 Torch reference kernels;不能将此结果解释为已启用 CUDA graph。启动仅预热文本,首次图片请求另记。
```powershell
# 已有独立 Python 环境后下载固定模型。
E:\D3Lite\.venv\Scripts\python.exe tools/download_imajev_local.py --root E:\D3Lite --repo vllm-sr/d3-lite --revision 6c01fba14e74f63b70e1ef442b0b6d1b934339d5 --modelscope
E:\D3Lite\.venv\Scripts\python.exe tools/start_d3_lite_local.py
# 另一个终端中运行。
E:\D3Lite\.venv\Scripts\python.exe tools/benchmark_d3_lite.py
dotnet run --project tests/Mvs.Smoke -- --d3-benchmark artifacts/d3-lite-benchmark
```
接口沿用上游 `/v1/systemone`,JSON `images` 接收 JPEG data URL。包装层仅附加实际上传字节的 SHA-256 和服务端耗时;逐次检查图片哈希,不改变模型问题、概率或答案映射。D3 响应没有 Imajev 的自动 `unknown_probability` / `abstained` 字段,不能把强制选择当作可靠拒答。
### 2026-11-12 本机结果
复用此前目视核验的盒子裁剪、无手、持物和手中物体裁剪,使用完全相同的 JPEG 字节。中英文各 5 组问题,每组先记录一次预热,再连续请求 5 次。中文采用“盒子空了没?”、“手里拿着东西吗?”和“手里这东西是黄的、绿的,还是红蓝都有?”。
| 测试方式 | 次数 | 平均 | P95 | 最大 | 低于 200ms |
| --- | --- | --- | --- | --- | --- |
| 固定图片连续 HTTP 请求,预热后 | 50 | 91.75ms | 109.62ms | 119.29ms | 50/50 |
| 海康新帧回调至结果,预热后 | 20 | 84.51ms | 107.83ms | 108.94ms | 20/20 |
| 颜色裁剪,首次等待 10 秒、后续间隔 3 秒 | 5 | 386.87ms | 424.57ms | 424.57ms | 0/5 |
固定图片 50 次答案均符合预期,但这是少量照片的重复请求,不是 50 个独立场景的准确率。中文颜色选择“有红有蓝”,选项概率 99.11%;中文非空盒的“是空盒”概率为 41.69%,虽然落在否侧但接近边界,不适合直接当高置信放行依据。间歇请求仍全部超过 200ms,连续测试的快延迟不能代表现场偶发触发速度。
海康计时包含已解码 BGR 回调后的克隆、512 长边缩图、JPEG 编码、HTTP 和响应解析,不含曝光、传感器读出、相机传输及启动;首帧预热 573.74ms。此次新拍画面为闭合纸盒,无法目视验证盒内是否为空,因此该组仅作延迟测试,不计判断准确率。
完整结果与输入保存在 `artifacts/d3-lite-benchmark/summary.json`、`results.json`、`intermittent.json`、`camera-e2e.json` 和 `fresh-camera-input.jpg`。5 次间歇请求的 P95 就是最大值,不应视为稳定的尾延迟估计。

View File

@ -16,10 +16,11 @@ try
foreach(var device in cameras)Console.WriteLine($"DEVICE: {device.Name}");
if(errors.Count>0)throw new Exception("Camera enumeration reported an error");
Console.WriteLine($"PASS: SDK initialized and enumerated {cameras.Count} camera(s)");
var benchmarkIndex = Array.IndexOf(args, "--imajev-benchmark");
var d3BenchmarkIndex = Array.IndexOf(args, "--d3-benchmark");
var benchmarkIndex = d3BenchmarkIndex >= 0 ? d3BenchmarkIndex : Array.IndexOf(args, "--imajev-benchmark");
if (benchmarkIndex >= 0)
{
if (benchmarkIndex + 1 >= args.Length) throw new ArgumentException("--imajev-benchmark requires an output directory");
if (benchmarkIndex + 1 >= args.Length) throw new ArgumentException("AI benchmark requires an output directory");
var directory = Path.GetFullPath(args[benchmarkIndex + 1]);
Directory.CreateDirectory(directory);
var device = cameras.FirstOrDefault() ?? throw new Exception("No Hikvision camera found");
@ -49,15 +50,27 @@ try
Cv2.Resize(image, resized, new Size((int)Math.Round(image.Width * scale), (int)Math.Round(image.Height * scale)), 0, 0, InterpolationFlags.Area);
if (!Cv2.ImEncode(".jpg", resized, out var jpeg)) throw new IOException("JPEG encode failed");
var preparedMs = Stopwatch.GetElapsedTime(captured.Started).TotalMilliseconds;
using var form = new MultipartFormDataContent();
form.Add(new StringContent(JsonSerializer.Serialize(new { state = new { }, questions = new { empty = new { type = "noul", instructions = "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box." } } }), Encoding.UTF8), "request");
var content = new ByteArrayContent(jpeg);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(content, "image", "camera.jpg");
using var response = await http.PostAsync("http://127.0.0.1:8765/v1/systemone", form);
using HttpContent body = d3BenchmarkIndex >= 0
? new StringContent(JsonSerializer.Serialize(new { state = "", images = new[] { "data:image/jpeg;base64," + Convert.ToBase64String(jpeg) }, questions = new { empty = new { type = "noul", instructions = "盒子空了没?" } } }), Encoding.UTF8, "application/json")
: new MultipartFormDataContent();
if (body is MultipartFormDataContent form)
{
form.Add(new StringContent(JsonSerializer.Serialize(new { state = new { }, questions = new { empty = new { type = "noul", instructions = "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box." } } }), Encoding.UTF8), "request");
var content = new ByteArrayContent(jpeg);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(content, "image", "camera.jpg");
}
var endpoint = d3BenchmarkIndex >= 0 ? "http://127.0.0.1:8766/v1/systemone" : "http://127.0.0.1:8765/v1/systemone";
using var response = await http.PostAsync(endpoint, body);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
using var result = JsonDocument.Parse(json);
if (d3BenchmarkIndex >= 0)
{
var digest = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(jpeg)).ToLowerInvariant();
if (result.RootElement.GetProperty("usage").GetProperty("image_sha256")[0].GetString() != digest)
throw new InvalidOperationException("D3 server received a different image");
}
var totalMs = Stopwatch.GetElapsedTime(captured.Started).TotalMilliseconds;
if (index == 0) File.WriteAllBytes(Path.Combine(directory, "fresh-camera-input.jpg"), jpeg);
var entry = new { index, warmup = index == 0, preprocess_ms = preparedMs, frame_to_result_ms = totalMs, response = result.RootElement.Clone() };

View File

@ -0,0 +1,91 @@
"""Compare D3-lite on the existing real camera controls, using ordinary short questions."""
import argparse
import base64
import hashlib
import io
import json
import math
from pathlib import Path
import statistics
import time
import urllib.request
def post(endpoint, image, question, choices=None, state=""):
field = {"type": "choice" if choices else "noul", "instructions": question}
if choices:
field["criteria"] = choices
payload = {"state": state, "questions": {"q": field}}
if image is not None:
payload["images"] = ["data:image/jpeg;base64," + base64.b64encode(image).decode()]
request = urllib.request.Request(endpoint, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers={"Content-Type": "application/json; charset=utf-8"})
started = time.perf_counter()
with urllib.request.urlopen(request, timeout=120) as response:
content = response.read()
elapsed = round((time.perf_counter() - started) * 1000, 2)
result = json.loads(content)
expected_hashes = [] if image is None else [hashlib.sha256(image).hexdigest()]
assert result["usage"]["image_sha256"] == expected_hashes
answer = result["answers"]["q"]
if "error" in answer:
raise RuntimeError(answer)
actual = answer["choice"] if choices else answer["noul"] > .5
return {"http_ms": elapsed, "actual": actual, "response": result}
def stats(runs):
values = sorted(row["http_ms"] for row in runs)
return {"count": len(runs), "mean_ms": round(statistics.mean(values), 2), "p95_ms": values[math.ceil(.95 * len(values)) - 1], "max_ms": max(values), "under_200ms": sum(value < 200 for value in values)}
def main():
from PIL import Image
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--endpoint", default="http://127.0.0.1:8766/v1/systemone")
parser.add_argument("--count", type=int, default=5)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
repo = Path(__file__).resolve().parents[1]
images = repo / "artifacts/imajev-benchmark"
colors = {"黄": "黄色", "绿": "绿色", "有红有蓝": "红色和蓝色都有"}
english_colors = {"yellow": "yellow", "green": "green", "red_and_blue": "both red and blue"}
cases = [
("非空盒_中文", "nonempty_crop-input.jpg", "盒子空了没?", None, False),
("非空盒_英文", "nonempty_crop-input.jpg", "Is the box empty?", None, False),
("空盒_中文", "empty_crop-input.jpg", "盒子空了没?", None, True),
("空盒_英文", "empty_crop-input.jpg", "Is the box empty?", None, True),
("无手_中文", "no_hand-input.jpg", "手里拿着东西吗?", None, False),
("无手_英文", "no_hand-input.jpg", "Is there a hand holding an object?", None, False),
("持物_中文", "hikvision-imajev-holding-20261112-194959-input.jpg", "手里拿着东西吗?", None, True),
("持物_英文", "hikvision-imajev-holding-20261112-194959-input.jpg", "Is there a hand holding an object?", None, True),
("颜色_中文", "hikvision-imajev-color-20261112-195330-hand-crop-input.jpg", "手里这东西是黄的、绿的,还是红蓝都有?", colors, "有红有蓝"),
("颜色_英文", "hikvision-imajev-color-20261112-195330-hand-crop-input.jpg", "What color is the object held in the hand?", english_colors, "red_and_blue"),
]
report = {"model": "d3-lite", "endpoint": args.endpoint, "scope": "Same real camera images as Imajev, maximum edge 512; one question per request; first call per case recorded separately as warmup", "note": "The upstream D3 response has no automatic abstention/unknown field; confidence is not a correctness guarantee", "cases": []}
args.output.parent.mkdir(parents=True, exist_ok=True)
for name, filename, question, choices, expected in cases:
source = images / filename
# Reuse the exact prepared JPEG bytes from the Imajev test, without recompression.
data = source.read_bytes()
with Image.open(io.BytesIO(data)) as image:
size = image.size
row = {"case": name, "input": str(source), "image_size": size, "image_sha256": hashlib.sha256(data).hexdigest(),
"question": question, "choices": choices, "expected": expected, "runs": []}
row["warmup"] = post(args.endpoint, data, question, choices)
report["cases"].append(row)
for _ in range(args.count):
run = post(args.endpoint, data, question, choices)
run["correct"] = run["actual"] == expected
row["runs"].append(run)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
row["summary"] = {**stats(row["runs"]), "correct": sum(run["correct"] for run in row["runs"])}
print(json.dumps({"case": name, "actual": row["runs"][0]["actual"], "answer": row["runs"][0]["response"]["answers"]["q"], **row["summary"]}, ensure_ascii=False), flush=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
all_runs = [run for case in report["cases"] for run in case["runs"]]
report["summary"] = {**stats(all_runs), "correct": sum(run["correct"] for run in all_runs)}
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(report["summary"]), flush=True)
if __name__ == "__main__":
main()

View File

@ -1,4 +1,4 @@
"""Download pinned Imajev-2B data-only weights with resumable, verified HTTP ranges."""
"""Download pinned model files with resumable, verified HTTP ranges (Imajev-2B by default)."""
import argparse
import concurrent.futures
import hashlib
@ -25,13 +25,19 @@ def main():
parser.add_argument("--root", type=Path, default=Path(r"E:\Imajev"))
parser.add_argument("--workers", type=int, default=16)
parser.add_argument("--modelscope-base", action="store_true", help="Fetch base weights from ModelScope; still require pinned Hugging Face size/SHA-256")
parser.add_argument("--repo", help="Download one other repository instead of the default Imajev pair")
parser.add_argument("--revision", help="Required immutable 40-character revision when --repo is supplied")
parser.add_argument("--modelscope", action="store_true", help="Fetch files from ModelScope, verified against pinned Hugging Face metadata")
args = parser.parse_args()
curl = shutil.which("curl.exe") or shutil.which("curl")
if not curl:
raise RuntimeError("curl is required")
root = args.root.resolve()
if args.repo and (not args.revision or len(args.revision) != 40 or any(c not in "0123456789abcdef" for c in args.revision)):
parser.error("--repo requires an immutable 40-character hexadecimal --revision")
models = [(args.repo, args.revision, "model", None)] if args.repo else MODELS
manifest = []
for repo, revision, folder, allowed in MODELS:
for repo, revision, folder, allowed in models:
with urllib.request.urlopen(f"https://huggingface.co/api/models/{repo}/revision/{revision}?blobs=true", timeout=30) as response:
metadata = json.load(response)
entry = {"repo": repo, "revision": revision, "files": {}}
@ -45,7 +51,7 @@ def main():
expected = file.get("lfs", {}).get("sha256")
if not (dest.exists() and dest.stat().st_size == size and (not expected or digest(dest) == expected)):
url = f"https://huggingface.co/{repo}/resolve/{revision}/{name}"
if args.modelscope_base and repo == "Qwen/Qwen3.5-2B":
if args.modelscope or args.modelscope_base and repo == "Qwen/Qwen3.5-2B":
url = f"https://modelscope.cn/models/{repo}/resolve/master/{name}"
print(f"Downloading {repo}/{name}: {size / 1024**2:.1f} MiB", flush=True)
partial = dest.with_name(dest.name + ".partial")
@ -85,8 +91,9 @@ def main():
manifest.append(entry)
print(f"Verified {repo}", flush=True)
(root / "local-model-manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
(root / "artifacts").mkdir(exist_ok=True)
(root / "artifacts/model-local-2b.json").write_text(json.dumps({"repo": MODELS[0][0], "revision": MODELS[0][1], "path": str(root / MODELS[0][2])}, indent=2), encoding="utf-8")
if not args.repo:
(root / "artifacts").mkdir(exist_ok=True)
(root / "artifacts/model-local-2b.json").write_text(json.dumps({"repo": MODELS[0][0], "revision": MODELS[0][1], "path": str(root / MODELS[0][2])}, indent=2), encoding="utf-8")
if __name__ == "__main__":

View File

@ -0,0 +1,58 @@
"""Serve a verified local D3-lite package; keep upstream prompts, attention and answer mapping."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import sys
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(r"E:\D3Lite"))
parser.add_argument("--port", type=int, default=8766)
args = parser.parse_args()
root = args.root.resolve()
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
sys.path.insert(0, str(root / "model"))
import torch
import transformers
from d3_runtime import D3
from d3_server import Decider, SystemOneServer
if not torch.cuda.is_available():
raise RuntimeError("CUDA is required for this benchmark")
torch.set_num_threads(4)
model = D3.from_pretrained(root / "model", device="cuda:0", batch_size=1,
verify="full", max_length=2048, local_files_only=True)
if model.image_unavailable is not None:
raise RuntimeError(f"Vision failed to initialize: {model.image_unavailable}")
# The stock warmup also runs four 1.6MP images. This test uses one 512px image on an 8GB GPU.
model.warmup(lengths=(64, 384), images=False)
settings = {"repo": "vllm-sr/d3-lite", "revision": "6c01fba14e74f63b70e1ef442b0b6d1b934339d5",
"device": torch.cuda.get_device_name(), "torch": torch.__version__,
"transformers": transformers.__version__, "runtime": model.runtime_info(),
"provenance": model.provenance()}
(root / "local-serving-settings.json").write_text(json.dumps(settings, indent=2, default=str), encoding="utf-8")
class TracedDecider(Decider):
def answer(self, body):
started = time.perf_counter()
result = super().answer(body)
# Add request provenance only. No probabilities, prompts, model inputs or choices are altered.
result["usage"]["image_sha256"] = [hashlib.sha256(base64.b64decode(value.split(",", 1)[1], validate=True)).hexdigest() for value in body.get("images", [])]
result["usage"]["server_ms"] = round((time.perf_counter() - started) * 1000, 2)
return result
server = SystemOneServer(("127.0.0.1", args.port), TracedDecider(model))
print(json.dumps({"status": "ready", "url": f"http://127.0.0.1:{args.port}", "runtime": model.runtime_info()}, default=str), flush=True)
try:
server.serve_forever()
finally:
server.server_close()
if __name__ == "__main__":
main()