部署并实测Imajev二十亿参数模型的视觉判断与海康帧延迟
This commit is contained in:
parent
428161e86e
commit
d7b2517c21
50
HAND_AI.md
50
HAND_AI.md
@ -2,6 +2,8 @@
|
||||
|
||||
分支:`experiment/hand-motion-ai-decision`。
|
||||
|
||||
Imajev-2B 的独立部署与对照测试脚本见文末。该实验使用 8765 端口,不会把运行中的 SOP 自动切换到新模型。
|
||||
|
||||
相机 → 通用 MediaPipe 手部检测 → 当前步骤的区域/移动条件 → 取当前原始画面为 JPEG → 兼容 Chat Completions 的视觉模型 → 完成判定。
|
||||
|
||||
手部动作表示“到了检查这个步骤的时机”。AI 返回 `completed=true`,且 `confidence` 达到配方阈值,才算步骤完成。只包含手部/计时条件且未配置物体规则的配方不会加载 YOLO,也不需要标注、训练零件模型。手部检测仍需要 `models/` 中的 palm 和 landmark ONNX。
|
||||
@ -128,3 +130,51 @@ pwsh -File tools/Start-HandAiLaya.ps1 -CheckOnly
|
||||
```
|
||||
|
||||
输入使用此前抓拍的 `hikvision-box-retake.jpg`、`hikvision-box-retake-crop.jpg` 和 Laya 自带的猫狗示例。此测试不修改生产接口或放行条件,当前 `noul` 结果不适合作为可靠的自动完成依据。
|
||||
|
||||
## Imajev-2B 独立测试
|
||||
|
||||
安装目录为 `E:\Imajev`,代码来源 `mohit67890/imajev`。基础模型固定为 `Qwen/Qwen3.5-2B@15852e8c16360a2fea060d615a32b45270f8a8fc`,适配器及决策读出固定为 `mohit67890/imajev-2b@e8cb9fc6e054a61ee3fdcff3cd20005ea6194588`。下载工具对大文件校验固定版本的 LFS SHA-256;ModelScope 下载源也必须通过相同校验。清单保存在安装目录的 `local-model-manifest.json`。
|
||||
|
||||
独立 `.venv` 通过 `laya-runtime.pth` 复用现有 Laya 的只读 Python 依赖目录(主要是 CUDA PyTorch 与 Transformers),PEFT 与 Accelerate 安装在 Imajev 自己的环境中;不修改 Laya 环境或模型。Laya 服务在本轮测试期间保持停止。
|
||||
|
||||
```powershell
|
||||
# 已有代码与独立 Python 环境后下载固定权重;支持续传。
|
||||
E:\Imajev\.venv\Scripts\python.exe tools/download_imajev_local.py --modelscope-base
|
||||
|
||||
# 常驻 GPU 服务,默认 8765 端口;每次只做一个选项顺序,不生成解释或思考文本。
|
||||
E:\Imajev\.venv\Scripts\python.exe tools/start_imajev_local.py
|
||||
|
||||
# 在另一个终端测试;结果与实际上传图片写入 artifacts/imajev-benchmark/。
|
||||
E:\Imajev\.venv\Scripts\python.exe tools/benchmark_imajev_vision.py --output artifacts/imajev-benchmark/results.json
|
||||
```
|
||||
|
||||
服务使用作者的 Torch backend、合并 LoRA 后的 BF16 权重、独立决策读出及随模型发布的温度校准,尝试仅录制长度 384 的 CUDA graph 以控制显存;捕获失败时按上游实现退回 eager。`--eager` 可完全关闭 fast path。合并时的 BF16 舍入可能改变接近并列的判断,相关配置和实际捕获情况保存在 `E:\Imajev\local-serving-settings.json`,也可从 `/health/imajev` 查询。
|
||||
|
||||
问题使用作者声明支持的英文。测试将输入最长边缩至 512,发送至 `/v1/systemone` 的 `image` 文件项和 `request` JSON 项;逐次比对返回的图片 SHA-256。每组先记录一次预热,再统计 5 次请求。覆盖非空盒整图与裁剪、真空盒裁剪、无手画面和“盒内有物”的反向问题。真空盒和无手来源于此前 `hikvision-hand-holding.jpg`,已目视核验;本组不包含“手确实拿着东西”的正样本。
|
||||
|
||||
`noul` 在 Imajev 中等于 `P(true) + 0.5 × P(unknown)`,因此记录时必须同时查看 `unknown_probability` 与 `abstained`。这些是少量固定图片的功能和延迟对照,重复正确次数不代表现场泛化准确率,5 次请求也不足以给出稳定的 P95 延迟估计。
|
||||
|
||||
### 2026-11-12 本机结果
|
||||
|
||||
上游代码固定为 `318e8dad55c12a1c6faddbec5f30489d2ee529ff`。RTX 4060 Laptop 8GB,BF16 合并 LoRA、单次选项顺序、作者校准、fast path,长度 384 的 CUDA graph 成功启用。依赖为 PyTorch `2.11.0+cu128`、Transformers `5.22.2`、PEFT `0.21.2`、Accelerate `1.15.0`。
|
||||
|
||||
先完成每组 5 次的功能检查,再对每组进行 20 次热态请求,共 100 次;均核对服务端图片哈希。各组结果稳定且无拒答:
|
||||
|
||||
| 图片与问题 | 判断 | 正例概率 | HTTP 均值 | HTTP P95 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 有物盒整图:是否为空 | 否 | 0.67% | 141.98ms | 154.61ms |
|
||||
| 有物盒裁剪:是否为空 | 否 | 0.91% | 140.68ms | 154.16ms |
|
||||
| 空盒裁剪:是否为空 | 是 | 90.97% | 141.51ms | 152.05ms |
|
||||
| 无手整图:是否有手拿物 | 否 | 1.34% | 147.24ms | 155.55ms |
|
||||
| 有物盒裁剪:里面是否有物品 | 是 | 98.86% | 142.50ms | 157.60ms |
|
||||
|
||||
100 次均低于 200ms:平均 142.78ms,P95 155.63ms,最大 158.21ms。首次图片请求为 889.37ms,不计入热态统计;启动时加载约 11.39 秒。HTTP 时间从开始发请求到收完响应,不含客户端图片准备。
|
||||
|
||||
另用海康持续采集真实新帧,第一帧预热后测量 20 帧,从已解码 BGR 帧回调、克隆、512 长边缩图、JPEG 编码到 HTTP 响应解析,平均 142.02ms、P95 152.96ms、最大 155.02ms,20 次均低于 200ms;图片预处理平均 8.79ms。首次预热 678.12ms。此计时不含曝光、传感器读出、相机传输及相机启动;这轮画面是空盒,空盒分数约 75.2%–81.4%,因此不能将“分类正确”解释为满足配方默认 85% 的自动放行门槛。
|
||||
|
||||
```powershell
|
||||
# Imajev 服务就绪后,以独立真实帧测量,不复用预先编码的图片。
|
||||
dotnet run --project tests/Mvs.Smoke -- --imajev-benchmark artifacts/imajev-benchmark
|
||||
```
|
||||
|
||||
完整结果保存在 `artifacts/imajev-benchmark/summary.json`、`steady-100.json`、`camera-e2e.json` 和对应输入图。这里是三张原始照片、裁剪和正反问题的重复测试,不是 100 张独立样本的准确率测试;还缺持物正样本、手部遮挡、不同零件及光照变化的验证。模型目前仅作为独立测试服务运行于 `127.0.0.1:8765`,尚未接入 SOP 步骤推进,Laya 保持停止。
|
||||
|
||||
@ -1,6 +1,10 @@
|
||||
using MvCameraControl;
|
||||
using SopHelper.Engine.Camera;
|
||||
using OpenCvSharp;
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
try
|
||||
{
|
||||
@ -12,6 +16,58 @@ 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");
|
||||
if (benchmarkIndex >= 0)
|
||||
{
|
||||
if (benchmarkIndex + 1 >= args.Length) throw new ArgumentException("--imajev-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");
|
||||
TaskCompletionSource<(Mat Image, long Started)>? requested = null;
|
||||
var seen = 0;
|
||||
camera.FrameArrived += frame =>
|
||||
{
|
||||
if (Interlocked.Increment(ref seen) < 5) return;
|
||||
var pending = Interlocked.Exchange(ref requested, null);
|
||||
if (pending is not null)
|
||||
{
|
||||
var started = Stopwatch.GetTimestamp();
|
||||
pending.TrySetResult((frame.Bgr.Clone(), started));
|
||||
}
|
||||
};
|
||||
if (!await camera.ConnectAsync(device) || !await camera.StartAsync()) throw new Exception("Open/start failed");
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
|
||||
var runs = new List<object>();
|
||||
for (var index = 0; index <= 20; index++)
|
||||
{
|
||||
var next = new TaskCompletionSource<(Mat Image, long Started)>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
Interlocked.Exchange(ref requested, next);
|
||||
var captured = await next.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
using var image = captured.Image;
|
||||
using var resized = new Mat();
|
||||
var scale = 512.0 / Math.Max(image.Width, image.Height);
|
||||
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);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
using var result = JsonDocument.Parse(json);
|
||||
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() };
|
||||
runs.Add(entry);
|
||||
File.WriteAllText(Path.Combine(directory, "camera-e2e.json"), JsonSerializer.Serialize(new { camera = device.Name, scope = "From decoded BGR frame callback before clone, resize and JPEG encode through HTTP response parsing; excludes exposure, sensor readout, camera transport and camera startup", runs }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
Console.WriteLine($"CAMERA AI: {index}, preprocess={preparedMs:F1}ms, frame_to_result={totalMs:F1}ms");
|
||||
}
|
||||
camera.Disconnect();
|
||||
return 0;
|
||||
}
|
||||
var snapshotIndex = Array.IndexOf(args, "--snapshot");
|
||||
if (snapshotIndex >= 0)
|
||||
{
|
||||
|
||||
89
tools/benchmark_imajev_vision.py
Normal file
89
tools/benchmark_imajev_vision.py
Normal file
@ -0,0 +1,89 @@
|
||||
"""Test the same real camera frames against Imajev, one question per HTTP request."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def post(endpoint, image, question_id, question):
|
||||
boundary = uuid.uuid4().hex
|
||||
request = {"state": {}, "questions": {question_id: {"type": "noul", "instructions": question}}}
|
||||
body = (f'--{boundary}\r\nContent-Disposition: form-data; name="request"\r\n\r\n'.encode()
|
||||
+ json.dumps(request).encode()
|
||||
+ f'\r\n--{boundary}\r\nContent-Disposition: form-data; name="image"; filename="camera.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'.encode()
|
||||
+ image + f'\r\n--{boundary}--\r\n'.encode())
|
||||
req = urllib.request.Request(endpoint, data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
|
||||
started = time.perf_counter()
|
||||
with urllib.request.urlopen(req, timeout=180) as response:
|
||||
content = response.read()
|
||||
elapsed = (time.perf_counter() - started) * 1000
|
||||
return json.loads(content), elapsed
|
||||
|
||||
|
||||
def main():
|
||||
from PIL import Image
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--endpoint", default="http://127.0.0.1:8765/v1/systemone")
|
||||
parser.add_argument("--count", type=int, default=5)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
root = Path(__file__).resolve().parents[1] / "artifacts/laya-box-benchmark"
|
||||
# Both were already inspected: the retake contains objects; the later hand-holding capture has an empty box and no hands.
|
||||
cases = [
|
||||
("nonempty_full", "hikvision-box-retake.jpg", None, "empty", "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box.", False),
|
||||
("nonempty_crop", "hikvision-box-retake-crop.jpg", None, "empty", "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box.", False),
|
||||
("empty_crop", "hikvision-hand-holding.jpg", (1060, 490, 1510, 1140), "empty", "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box.", True),
|
||||
("no_hand", "hikvision-hand-holding.jpg", None, "holding", "Is there a visible hand holding an object in this image?", False),
|
||||
("nonempty_opposite", "hikvision-box-retake-crop.jpg", None, "nonempty", "Are there any objects inside the open cardboard box?", True),
|
||||
]
|
||||
report = {"endpoint": args.endpoint, "image_max_edge": 512, "timing_scope": "HTTP send to complete response; excludes image preparation; one untimed warmup per case recorded separately", "cases": []}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
for name, filename, crop, question_id, question, expected in cases:
|
||||
source = root / filename
|
||||
with Image.open(source) as original:
|
||||
image = original.convert("RGB")
|
||||
if crop:
|
||||
image = image.crop(crop)
|
||||
image.thumbnail((512, 512))
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="JPEG", quality=95)
|
||||
data = buffer.getvalue()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
prepared = args.output.parent / f"{name}-input.jpg"
|
||||
prepared.write_bytes(data)
|
||||
row = {"case": name, "source": str(source), "crop_xyxy": crop, "input": str(prepared),
|
||||
"upload_sha256": digest, "input_size": list(image.size), "question_id": question_id,
|
||||
"question": question, "expected_yes": expected, "runs": []}
|
||||
warmup, elapsed = post(args.endpoint, data, question_id, question)
|
||||
row["warmup"] = {"http_ms": round(elapsed, 2), "response": warmup}
|
||||
report["cases"].append(row)
|
||||
print(json.dumps({"case": name, "stage": "warmup", "http_ms": round(elapsed, 2), "answer": warmup["answers"][question_id]}, ensure_ascii=False), flush=True)
|
||||
for index in range(args.count):
|
||||
result, elapsed = post(args.endpoint, data, question_id, question)
|
||||
if result["usage"]["images"][0]["sha256"] != digest:
|
||||
raise RuntimeError("Server image hash does not match upload")
|
||||
answer = result["answers"][question_id]
|
||||
probability = answer["noul"]
|
||||
run = {"run": index + 1, "http_ms": round(elapsed, 2), "server_ms": result["usage"]["total_ms"],
|
||||
"yes_probability": probability, "unknown_probability": answer["unknown_probability"],
|
||||
"abstained": answer["abstained"], "prediction_yes": probability >= .5,
|
||||
"correct": not answer["abstained"] and (probability >= .5) == expected, "response": result}
|
||||
row["runs"].append(run)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps({"case": name, **{key: value for key, value in run.items() if key != "response"}}, ensure_ascii=False), flush=True)
|
||||
durations = [run["http_ms"] for run in row["runs"]]
|
||||
row["summary"] = {"mean_http_ms": round(statistics.mean(durations), 2), "min_http_ms": min(durations),
|
||||
"max_http_ms": max(durations), "under_200ms": sum(ms < 200 for ms in durations),
|
||||
"correct_count": sum(run["correct"] for run in row["runs"])}
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps({"case": name, **row["summary"]}), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
93
tools/download_imajev_local.py
Normal file
93
tools/download_imajev_local.py
Normal file
@ -0,0 +1,93 @@
|
||||
"""Download pinned Imajev-2B data-only weights with resumable, verified HTTP ranges."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import urllib.request
|
||||
|
||||
MODELS = [
|
||||
("Qwen/Qwen3.5-2B", "15852e8c16360a2fea060d615a32b45270f8a8fc", "models/Qwen3.5-2B", None),
|
||||
("mohit67890/imajev-2b", "e8cb9fc6e054a61ee3fdcff3cd20005ea6194588", "adapters/imajev-2b",
|
||||
{"adapter_config.json", "adapter_model.safetensors", "decision_readout.json", "decision_readout.safetensors", "calibration.json", "README.md", "RELEASE-SPEC.md"}),
|
||||
]
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open("rb") as source:
|
||||
return hashlib.file_digest(source, "sha256").hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
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")
|
||||
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()
|
||||
manifest = []
|
||||
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": {}}
|
||||
for file in metadata["siblings"]:
|
||||
name = file["rfilename"]
|
||||
if name == ".gitattributes" or "/" in name or (allowed is not None and name not in allowed):
|
||||
continue
|
||||
dest = root / folder / name
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
size = file["size"]
|
||||
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":
|
||||
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")
|
||||
if size > 16 * 1024**2:
|
||||
part_dir = root / "downloads" / folder.replace("/", "-") / name
|
||||
part_dir.mkdir(parents=True, exist_ok=True)
|
||||
chunk = 8 * 1024**2
|
||||
count = (size + chunk - 1) // chunk
|
||||
|
||||
def fetch(index):
|
||||
start = index * chunk
|
||||
end = min(size, start + chunk) - 1
|
||||
part = part_dir / f"{index:05d}.part"
|
||||
if not part.exists() or part.stat().st_size != end - start + 1:
|
||||
subprocess.run([curl, "-sS", "-L", "--fail", "--retry", "3", "--connect-timeout", "15", "--max-time", "600",
|
||||
"-r", f"{start}-{end}", "-o", str(part), url + f"?part={index}"], check=True)
|
||||
if part.stat().st_size != end - start + 1:
|
||||
raise RuntimeError(f"Incorrect range length: {part}")
|
||||
return part
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as pool:
|
||||
futures = [pool.submit(fetch, index) for index in range(count)]
|
||||
for completed, future in enumerate(concurrent.futures.as_completed(futures), 1):
|
||||
future.result()
|
||||
if completed % 25 == 0 or completed == count:
|
||||
print(f"{repo}/{name}: {completed}/{count} chunks", flush=True)
|
||||
with partial.open("wb") as output:
|
||||
for index in range(count):
|
||||
with (part_dir / f"{index:05d}.part").open("rb") as source:
|
||||
shutil.copyfileobj(source, output, 8 * 1024**2)
|
||||
else:
|
||||
subprocess.run([curl, "-sS", "-L", "--fail", "--retry", "3", "--max-time", "120", "-o", str(partial), url], check=True)
|
||||
if partial.stat().st_size != size or (expected and digest(partial) != expected):
|
||||
raise RuntimeError(f"Size/SHA-256 verification failed: {partial}")
|
||||
partial.replace(dest)
|
||||
entry["files"][name] = {"sha256": digest(dest), "bytes": size}
|
||||
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 __name__ == "__main__":
|
||||
main()
|
||||
51
tools/start_imajev_local.py
Normal file
51
tools/start_imajev_local.py
Normal file
@ -0,0 +1,51 @@
|
||||
"""Serve pinned local Imajev-2B with a small CUDA graph budget on an 8GB GPU."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path(r"E:\Imajev"))
|
||||
parser.add_argument("--port", type=int, default=8765)
|
||||
parser.add_argument("--eager", action="store_true", help="Skip fast path and CUDA graph capture")
|
||||
args = parser.parse_args()
|
||||
root = args.root.resolve()
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
|
||||
for directory in (root / "src", root / "scripts"):
|
||||
sys.path.insert(0, str(directory))
|
||||
import torch
|
||||
import uvicorn
|
||||
from playground.server import TorchBackend, create_app
|
||||
from vision_decision.calibration import TemperatureCalibrator
|
||||
if not torch.cuda.is_available():
|
||||
raise RuntimeError("CUDA is required for this benchmark")
|
||||
torch.set_num_threads(4)
|
||||
adapter = root / "adapters/imajev-2b"
|
||||
backend = TorchBackend(bundle=root / "artifacts/model-local-2b.json", adapter=adapter,
|
||||
device="cuda", rotations=1, max_input_tokens=1024,
|
||||
fast=not args.eager, graph_lengths=[384], merge_lora=True)
|
||||
backend.model = "imajev-2b"
|
||||
calibration = TemperatureCalibrator.load(adapter / "calibration.json")
|
||||
app = create_app(backend, examples=[], calibration=calibration)
|
||||
settings = {"model": backend.model, "device": torch.cuda.get_device_name(),
|
||||
"dtype": "bfloat16", "rotations": 1, "calibrated": True,
|
||||
"merged_lora": True, "fast": backend.fast, "graph_lengths": backend.graph_lengths,
|
||||
"load_seconds": backend.load_seconds, "adapter": str(adapter)}
|
||||
|
||||
@app.get("/health/imajev")
|
||||
def health():
|
||||
return settings
|
||||
|
||||
# create_app mounts its static UI at '/', so register the diagnostic route before that mount.
|
||||
app.router.routes.insert(0, app.router.routes.pop())
|
||||
print(json.dumps(settings, ensure_ascii=False), flush=True)
|
||||
(root / "local-serving-settings.json").write_text(json.dumps(settings, indent=2), encoding="utf-8")
|
||||
uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="warning")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue
Block a user