aisop/tools/probe_d3_rocm.py

123 lines
6.1 KiB
Python

"""Probe D3 on a ROCm host without modifying its checkpoint or forcing a GPU architecture."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import statistics
import sys
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--images", type=Path)
parser.add_argument("--mode", choices=("plain", "fast", "graph"), default="plain")
parser.add_argument("--graph-tokens", type=int, default=128)
parser.add_argument("--graph-bucket", type=int, default=128)
args = parser.parse_args()
if args.graph_tokens <= 0 or args.graph_bucket <= 0:
parser.error("graph token budget and bucket must be positive")
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["D3_FAST"] = "0" if args.mode == "plain" else "1"
# One bounded text graph, rather than allocating all context-length buckets.
os.environ["D3_GRAPH_TOKENS"] = str(args.graph_tokens) if args.mode == "graph" else "0"
os.environ["D3_GRAPH_BUCKET"] = str(args.graph_bucket)
sys.path.insert(0, str(args.root.resolve() / "model"))
import torch
import transformers
report = {"mode": args.mode, "torch": torch.__version__, "hip": torch.version.hip,
"transformers": transformers.__version__, "cuda_available": torch.cuda.is_available(),
"architecture_override": os.environ.get("HSA_OVERRIDE_GFX_VERSION"),
"environment": {key: os.environ.get(key) for key in (
"D3_FAST", "D3_GRAPH_TOKENS", "D3_GRAPH_BUCKET",
"TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL")}, "runs": []}
def save():
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
try:
if not torch.version.hip or not torch.cuda.is_available():
raise RuntimeError("A working ROCm PyTorch GPU is required")
torch.set_num_threads(4)
report["device"] = str(torch.cuda.get_device_properties(0))
# Validate basic BF16 matrix multiplication and HIP graph capture before loading the model.
with torch.inference_mode():
matrix = torch.ones((64, 64), device="cuda", dtype=torch.bfloat16)
for _ in range(3):
product = matrix @ matrix
torch.cuda.synchronize()
assert product[0, 0].item() == 64
report["basic_bf16_matmul"] = "passed"
try:
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
product = matrix @ matrix
graph.replay()
torch.cuda.synchronize()
assert product[0, 0].item() == 64
report["basic_bf16_hip_graph"] = "passed"
except Exception as exc:
report["basic_bf16_hip_graph"] = f"{type(exc).__name__}: {exc}"
save()
from d3_runtime import D3
started = time.perf_counter()
model = D3.from_pretrained(args.root / "model", device="cuda:0", batch_size=1,
verify="full", max_length=2048, local_files_only=True)
report["load_seconds"] = round(time.perf_counter() - started, 2)
report["runtime"] = model.runtime_info()
report["provenance"] = model.provenance()
save()
report["warmup_seconds"] = model.warmup(lengths=(64, 384), images=False)
save()
cases = [("text", None, "桌上有一个红盒子。", "盒子是红的吗?", None)]
if args.images:
cases += [
("nonempty", "nonempty_crop-input.jpg", "", "盒子空了没?", None),
("empty", "empty_crop-input.jpg", "", "盒子空了没?", None),
("holding", "hikvision-imajev-holding-20261112-194959-input.jpg", "", "手里拿着东西吗?", None),
("color", "hikvision-imajev-color-20261112-195330-hand-crop-input.jpg", "", "手里这东西是黄的、绿的,还是红蓝都有?", {"黄": "黄色", "绿": "绿色", "有红有蓝": "红色和蓝色都有"}),
]
for name, filename, state, question, choices in cases:
field = {"type": "choice" if choices else "noul", "instructions": question}
if choices:
field["criteria"] = choices
image_path = args.images / filename if filename else None
row = {"case": name, "question": question, "runs": [],
"sha256": hashlib.sha256(image_path.read_bytes()).hexdigest() if image_path else None}
report["runs"].append(row)
for i in range(6):
started = time.perf_counter()
result = model.system_one(state=state, questions={"q": field},
images=[str(image_path)] if image_path else None)
model.synchronize()
row["runs"].append({"warmup": i == 0, "ms": round((time.perf_counter() - started) * 1000, 2), "response": result})
save()
row["mean_ms"] = round(statistics.mean(r["ms"] for r in row["runs"][1:]), 2)
print(json.dumps({"case": name, "mean_ms": row["mean_ms"], "answer": result}, ensure_ascii=False), flush=True)
if args.images:
intermittent = []
report["intermittent"] = intermittent
for _ in range(3):
time.sleep(3)
started = time.perf_counter()
result = model.system_one(state=state, questions={"q": field}, images=[str(image_path)])
model.synchronize()
intermittent.append({"idle_seconds": 3, "ms": round((time.perf_counter() - started) * 1000, 2), "response": result})
save()
report["fast_report_after"] = model.fast_report()
report["peak_allocated_mib"] = round(torch.cuda.max_memory_allocated() / 1024**2, 2)
except Exception as exc:
report["error"] = f"{type(exc).__name__}: {exc}"
save()
raise
finally:
save()
if __name__ == "__main__":
main()