增加视觉图片输入与决策特征跟踪并记录空盒误判排查
This commit is contained in:
parent
a7133dd979
commit
428161e86e
26
HAND_AI.md
26
HAND_AI.md
@ -102,3 +102,29 @@ dotnet run --project tests/Avalonia.Smoke -p:BundlePythonRuntime=false -- --proc
|
||||
```
|
||||
|
||||
覆盖稳定帧触发、单请求、拒绝/低置信度、超时、旧结果失效、配方往返、HTTP 消息及异常响应、界面开关,以及延迟响应时保留原判定帧。
|
||||
|
||||
## 2026-11-12 图片输入排查
|
||||
|
||||
海康盒子图和裁剪图被 `noul` 错判为空后,对在线接口进行了猫、狗、盒子整图、盒子裁剪和黑色图片五组对照。相同盒子整图的结果为:中文“空盒”99.7924%,英文“空盒”99.7789%,英文“盒内有物”99.9989%,多选分类为 `box_with_objects`。正反问题同时给出高正例概率,说明是非判断不可靠;英文提问没有消除问题。猫图的多选分类也有误,因此这组多选结果不能当成准确率验证。
|
||||
|
||||
为检查模型输入,短暂停止原服务,在独立进程中使用原 `server.add_vision_api` 路由和 FastAPI TestClient 上传同样的图片,不修改 Laya 源码。对视觉模型 `_run` 与 `_features` 加入临时跟踪,记录真实 `pixel_values`、图像 token、网格及送入决策引擎的特征摘要;诊断结束后重新启动原服务。
|
||||
|
||||
- 损坏图片被接口以 422 拒绝,证明上传内容实际经过解码检查。
|
||||
- 五张图产生五组不同的像素张量与引擎特征;每个问题都传入图像,图像 token 数与网格匹配。
|
||||
- 路由内诊断与原在线服务的所有答案一致;没有观察到固定旧图或固定答案缓存。
|
||||
- `noul → boolean → probs.True → noul` 的映射检查通过,没有将真假概率读反。
|
||||
- 当前 `vegaml/_vision.py` 的说明明确写明决策引擎按文本特征训练,视觉路径为零样本复用。输入通路正确不能保证这条决策路径在工位图片上有效;具体误判机制尚未锁定。
|
||||
|
||||
诊断工具(依赖本机 Laya 环境,结果写入忽略的 `artifacts/`):
|
||||
|
||||
```powershell
|
||||
$env:PYTHONUTF8 = '1'
|
||||
E:\LayaAI\.venv\Scripts\python.exe tools/diagnose_laya_vision.py --output artifacts/laya-box-benchmark/input-audit-http.json
|
||||
|
||||
# 张量跟踪会在独立进程加载视觉模型;先释放原服务的 GPU 显存。
|
||||
E:\LayaAI\stop.ps1
|
||||
E:\LayaAI\.venv\Scripts\python.exe tools/diagnose_laya_vision.py --trace-local --output artifacts/laya-box-benchmark/input-audit-tensors.json
|
||||
pwsh -File tools/Start-HandAiLaya.ps1 -CheckOnly
|
||||
```
|
||||
|
||||
输入使用此前抓拍的 `hikvision-box-retake.jpg`、`hikvision-box-retake-crop.jpg` 和 Laya 自带的猫狗示例。此测试不修改生产接口或放行条件,当前 `noul` 结果不适合作为可靠的自动完成依据。
|
||||
|
||||
158
tools/diagnose_laya_vision.py
Normal file
158
tools/diagnose_laya_vision.py
Normal file
@ -0,0 +1,158 @@
|
||||
"""Trace image inputs and compare Laya vision answers across image/question controls."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
QUESTIONS = {
|
||||
"zh_empty": {"type": "noul", "instructions": "图中打开的棕色纸盒里面是否为空?只检查纸盒内部,不考虑盒子外的物体。空表示盒内没有任何物品。"},
|
||||
"en_empty": {"type": "noul", "instructions": "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box."},
|
||||
"en_nonempty": {"type": "noul", "instructions": "Are there any objects inside the open cardboard box?"},
|
||||
"scene": {"type": "choice", "instructions": "Which description best matches this image?", "criteria": {
|
||||
"cat": "cats", "dog": "a dog", "box_with_objects": "an open cardboard box containing objects",
|
||||
"empty_box": "an empty open cardboard box", "other": "none of these"}},
|
||||
}
|
||||
|
||||
|
||||
def sha(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def post(url, data, questions):
|
||||
boundary = uuid.uuid4().hex
|
||||
body = (f'--{boundary}\r\nContent-Disposition: form-data; name="questions"\r\n\r\n'.encode()
|
||||
+ json.dumps(questions, ensure_ascii=False).encode("utf-8")
|
||||
+ f'\r\n--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'.encode()
|
||||
+ data + f'\r\n--{boundary}--\r\n'.encode())
|
||||
req = urllib.request.Request(url, data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
|
||||
started = time.perf_counter()
|
||||
with urllib.request.urlopen(req, timeout=180) as response:
|
||||
result = json.load(response)
|
||||
return result, round((time.perf_counter() - started) * 1000, 2)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--laya-root", type=Path, default=Path(r"E:\LayaAI"))
|
||||
parser.add_argument("--endpoint", default="http://127.0.0.1:8000/v1/vision/decide")
|
||||
parser.add_argument("--trace-local", action="store_true", help="In-process ASGI route and tensor trace; stop GPU server first to free memory")
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
from PIL import Image
|
||||
artifacts = Path(__file__).resolve().parents[1] / "artifacts" / "laya-box-benchmark"
|
||||
cases = [("cat", args.laya_root / "vision-sample.png"), ("dog", args.laya_root / "vision-dog-sample.jpg"),
|
||||
("box_full", artifacts / "hikvision-box-retake.jpg"), ("box_crop", artifacts / "hikvision-box-retake-crop.jpg")]
|
||||
blank = io.BytesIO()
|
||||
Image.new("RGB", (470, 670), (0, 0, 0)).save(blank, format="JPEG", quality=95)
|
||||
inputs = [(name, path.read_bytes()) for name, path in cases] + [("black_control", blank.getvalue())]
|
||||
source_paths = [args.laya_root / "server.py", args.laya_root / "vision_runtime.py",
|
||||
args.laya_root / ".venv/Lib/site-packages/vegaml/_vision.py",
|
||||
args.laya_root / ".venv/Lib/site-packages/laya/vega.py"]
|
||||
report = {"mode": "local_asgi_tensor_trace" if args.trace_local else "running_http_service", "questions": QUESTIONS,
|
||||
"source_sha256": {str(path): sha(path.read_bytes()) for path in source_paths}, "cases": []}
|
||||
traces = []
|
||||
if args.trace_local:
|
||||
import torch
|
||||
sys.path.insert(0, str(args.laya_root))
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from server import add_vision_api
|
||||
from vision_runtime import runner
|
||||
from laya.vega import _fold, _to_vega_questions
|
||||
bool_question = {"type": "noul", "instructions": "Is the box empty?"}
|
||||
assert _to_vega_questions({"q": bool_question})["q"]["type"] == "boolean"
|
||||
for probability in (.01, .99):
|
||||
assert _fold({"probs": {"False": 1 - probability, "True": probability}}, bool_question)["noul"] == probability
|
||||
report["boolean_mapping_checked"] = True
|
||||
runner._load()
|
||||
model = runner.model
|
||||
|
||||
def tensor_info(value):
|
||||
cpu = value.detach().cpu().contiguous()
|
||||
return {"shape": list(cpu.shape), "dtype": str(cpu.dtype),
|
||||
"sha256": sha(cpu.view(torch.uint8).numpy().tobytes()),
|
||||
"mean": float(cpu.float().mean()), "std": float(cpu.float().std()),
|
||||
"finite": bool(torch.isfinite(cpu).all())}
|
||||
|
||||
original_run = model._run
|
||||
|
||||
def traced_run(ids, pixel_values=None, grid=None):
|
||||
trace = {"pixel_values": tensor_info(pixel_values) if pixel_values is not None else None,
|
||||
"grid": grid.detach().cpu().tolist() if grid is not None else None,
|
||||
"image_pad_tokens": int((ids == model.pad_id).sum()), "input_tokens": int(ids.numel())}
|
||||
trace["expected_image_tokens"] = int(grid.prod()) // model.proc.image_processor.merge_size ** 2
|
||||
traces.append(trace)
|
||||
result = original_run(ids, pixel_values, grid)
|
||||
trace["captured_layers"] = {str(key): tensor_info(value) for key, value in result.items()}
|
||||
return result
|
||||
|
||||
model._run = traced_run
|
||||
original_features = model._features
|
||||
|
||||
def traced_features(*params, **kwargs):
|
||||
before = len(traces)
|
||||
result = original_features(*params, **kwargs)
|
||||
for index, features in enumerate(result[0]):
|
||||
traces[before + index]["pooled_engine_features"] = tensor_info(features)
|
||||
traces[before + index]["pooled_option_features"] = tensor_info(result[1][index])
|
||||
return result
|
||||
|
||||
model._features = traced_features
|
||||
app = FastAPI()
|
||||
add_vision_api(app)
|
||||
client = TestClient(app)
|
||||
|
||||
def send(data):
|
||||
before = len(traces)
|
||||
response = client.post("/v1/vision/decide", files={"file": ("capture.jpg", data, "image/jpeg")}, data={"questions": json.dumps(QUESTIONS, ensure_ascii=False)})
|
||||
response.raise_for_status()
|
||||
return response.json(), traces[before:]
|
||||
|
||||
malformed = client.post("/v1/vision/decide", files={"file": ("bad.jpg", b"this is not an image", "image/jpeg")}, data={"questions": json.dumps(QUESTIONS)})
|
||||
report["malformed_image_status"] = malformed.status_code
|
||||
else:
|
||||
try:
|
||||
post(args.endpoint, b"this is not an image", QUESTIONS)
|
||||
report["malformed_image_status"] = 200
|
||||
except urllib.error.HTTPError as error:
|
||||
report["malformed_image_status"] = error.code
|
||||
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
for name, data in inputs:
|
||||
started = time.perf_counter()
|
||||
if args.trace_local:
|
||||
result, trace = send(data)
|
||||
else:
|
||||
result, _ = post(args.endpoint, data, QUESTIONS)
|
||||
trace = None
|
||||
row = {"case": name, "upload_sha256": sha(data), "upload_bytes": len(data),
|
||||
"elapsed_ms": round((time.perf_counter() - started) * 1000, 2), "result": result, "tensor_trace": trace}
|
||||
report["cases"].append(row)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps({"case": name, "answers": {key: value.get("noul", value.get("choice")) for key, value in result["answers"].items()},
|
||||
"processed_size": result["processed_size"], "trace_count": len(trace) if trace else 0}, ensure_ascii=False), flush=True)
|
||||
if report["malformed_image_status"] != 422:
|
||||
raise RuntimeError("Invalid image was not rejected with 422")
|
||||
if args.trace_local:
|
||||
pixel_hashes = [row["tensor_trace"][0]["pixel_values"]["sha256"] for row in report["cases"]]
|
||||
feature_hashes = [row["tensor_trace"][0]["pooled_engine_features"]["sha256"] for row in report["cases"]]
|
||||
report["checks"] = {"unique_pixel_inputs": len(set(pixel_hashes)), "unique_engine_features": len(set(feature_hashes)),
|
||||
"all_questions_receive_pixels": all(t["pixel_values"] is not None and t["image_pad_tokens"] > 0 for row in report["cases"] for t in row["tensor_trace"]),
|
||||
"image_token_counts_match_grid": all(t["image_pad_tokens"] == t["expected_image_tokens"] for row in report["cases"] for t in row["tensor_trace"])}
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps(report["checks"], ensure_ascii=False), flush=True)
|
||||
assert report["checks"]["unique_pixel_inputs"] == len(inputs)
|
||||
assert report["checks"]["unique_engine_features"] == len(inputs)
|
||||
assert report["checks"]["all_questions_receive_pixels"]
|
||||
assert report["checks"]["image_token_counts_match_grid"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue
Block a user