159 lines
8.7 KiB
Python
159 lines
8.7 KiB
Python
"""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()
|