"""Export D-FINE-N (COCO) to ONNX that runs in ONNX Runtime Web on WebGPU and WASM. Usage: python export.py [model.onnx] Tested with torch 2.15.0, transformers 5.26.0, onnx 1.23.2, onnxruntime 1.32.0. """ import os import sys from urllib.request import urlopen import numpy as np import onnx import onnxruntime as ort import torch from onnx import helper, numpy_helper, shape_inference from PIL import Image from transformers import DFineForObjectDetection SOURCE = "ustc-community/dfine-nano-coco" REVISION = "066438d3d8f0da137a37b38fdf3368fd4afceced" OUT = sys.argv[1] if len(sys.argv) > 1 else "model.onnx" RAW = OUT.replace(".onnx", ".raw.onnx") class Wrapper(torch.nn.Module): def __init__(self, model): super().__init__() self.model = model def forward(self, pixel_values): out = self.model(pixel_values=pixel_values) return out.logits, out.pred_boxes model = DFineForObjectDetection.from_pretrained(SOURCE, revision=REVISION).eval() # PyTorch reference, taken before export: tracing leaves the module in a state # that gives different results afterwards. photo = Image.open(urlopen("http://images.cocodataset.org/val2017/000000039769.jpg")).convert("RGB") pixels = np.asarray(photo.resize((640, 640), Image.BILINEAR), np.float32) / 255 x = torch.from_numpy(pixels.transpose(2, 0, 1)[None].copy()) with torch.no_grad(): ref = model(pixel_values=x) dummy = torch.rand(1, 3, 640, 640) torch.onnx.export( Wrapper(model), (dummy,), RAW, input_names=["pixel_values"], output_names=["logits", "pred_boxes"], opset_version=17, dynamo=False, ) # WebGPU patches. Neither changes the outputs. m = onnx.load(RAW) # 1. WebGPU's MaxPool has no ceil_mode. On a stride-1 pool it changes nothing. for node in m.graph.node: if node.op_type == "MaxPool": attrs = {a.name: helper.get_attribute_value(a) for a in node.attribute} if attrs.get("ceil_mode") == 1 and all(s == 1 for s in attrs.get("strides", [1, 1])): for a in node.attribute: if a.name == "ceil_mode": a.i = 0 # 2. WebGPU's MatMul rejects a 1-D second input (decoder/integral): make it a column. rank = { v.name: len(v.type.tensor_type.shape.dim) for v in shape_inference.infer_shapes(m).graph.value_info } m.graph.initializer.append(numpy_helper.from_array(np.array([1], np.int64), "webgpu_axes_1")) nodes = [] for node in m.graph.node: if node.op_type == "MatMul" and rank.get(node.input[1]) == 1: col = node.input[1] + "_col" nodes.append(helper.make_node("Unsqueeze", [node.input[1], "webgpu_axes_1"], [col], name=node.name + "_col")) node.input[1] = col nodes.append(node) del m.graph.node[:] m.graph.node.extend(nodes) onnx.checker.check_model(m) onnx.save(m, OUT) os.remove(RAW) # Check against PyTorch: the same detections above 0.3. (Raw outputs can differ where # low-score queries tie in the top-k query selection.) def detections(logits, boxes): scores = 1 / (1 + np.exp(-logits[0])) keep = scores.max(1) > 0.3 rows = np.c_[scores.argmax(1)[keep], scores.max(1)[keep], boxes[0][keep]] return rows[np.lexsort(rows.T[::-1])] logits, boxes = ort.InferenceSession(OUT).run(None, {"pixel_values": x.numpy()}) a, b = detections(logits, boxes), detections(ref.logits.numpy(), ref.pred_boxes.numpy()) assert a.shape == b.shape and np.allclose(a, b, atol=1e-3), "ONNX and PyTorch disagree" print(f"ok: {len(a)} detections match PyTorch")