"""Export the official MoGe-3 ViT-L checkpoint to ezonnx's FP32 ONNX graphs. Run with the upstream MoGe and utils3d-moge packages on PYTHONPATH, plus PyTorch 2.8+ and ONNX. No CUDA or FlexGEMM installation is required. """ import argparse from pathlib import Path import numpy as np import onnx from onnx import TensorProto, helper, numpy_helper import torch from torch import nn class BaseGraph(nn.Module): def __init__(self, model): super().__init__() self.model = model def forward(self, image, aspect_ratio): h, w = image.shape[2] // 14, image.shape[3] // 14 feature, cls = self.model.encoder(image, h, w, return_class_token=True) ratio_norm = (1 + aspect_ratio.square()).sqrt() pyramid = [] for level in range(5): gh, gw = h * 2**level, w * 2**level y = (2 * (torch.arange(gh, device=image.device, dtype=image.dtype) + .5) / gh - 1) x = (2 * (torch.arange(gw, device=image.device, dtype=image.dtype) + .5) / gw - 1) xx = (x * aspect_ratio / ratio_norm).view(1, gw).expand(gh, gw) yy = (y / ratio_norm).view(gh, 1).expand(gh, gw) uv = torch.stack((xx, yy))[None] pyramid.append(torch.cat((feature, uv), dim=1) if level == 0 else uv) decoded = self.model.neck(pyramid) return ( pyramid[0], self.model.points_head(decoded)[-1], self.model.mask_head(decoded)[-1], self.model.normal_head(decoded)[-1], self.model.scale_head(cls).exp(), ) def _register_cubic_antialias(): from torch.onnx.symbolic_helper import _unpack_list def resize(g, x, size, align_corners, scales_h, scales_w): leading = g.op( "Slice", g.op("Shape", x), g.op("Constant", value_t=torch.tensor([0])), g.op("Constant", value_t=torch.tensor([2])), ) size = g.op("Concat", leading, *[ g.op("Reshape", g.op("Cast", dim, to_i=7), g.op("Constant", value_t=torch.tensor([1]))) for dim in _unpack_list(size) ], axis_i=0) empty = g.op("Constant", value_t=torch.empty(0)) return g.op("Resize", x, empty, empty, size, mode_s="cubic", coordinate_transformation_mode_s="half_pixel", cubic_coeff_a_f=-0.5, antialias_i=1, exclude_outside_i=1) torch.onnx.register_custom_op_symbolic("aten::_upsample_bicubic2d_aa", resize, 18) def export_base(checkpoint, directory): from moge.model.v2 import MoGeModel config, state = checkpoint["model_config"], checkpoint["model"] keys = ("encoder", "neck", "points_head", "mask_head", "normal_head", "scale_head") net = MoGeModel(**{key: config[key] for key in keys}, remap_output="exp") net.load_state_dict({k: v for k, v in state.items() if not k.startswith("refiner.")}, strict=True, assign=True) net.onnx_compatible_mode = True _register_cubic_antialias() net = BaseGraph(net.eval()).eval() target = directory / "moge3_vitl_base.onnx" with torch.no_grad(): torch.onnx.export( net, (torch.zeros(1, 3, 112, 140), torch.tensor(1.25)), str(target), opset_version=18, dynamo=False, do_constant_folding=False, input_names=["image", "aspect_ratio"], output_names=["features", "coords", "mask_logits", "normals", "metric_scale"], dynamic_axes={ "image": {2: "height", 3: "width"}, "features": {2: "token_rows", 3: "token_cols"}, **{name: {2: "map_height", 3: "map_width"} for name in ("coords", "mask_logits", "normals")}, }, ) # Normalize to one external data file, as required by the ezonnx loader. graph = onnx.load(target) (directory / (target.name + "_data")).unlink(missing_ok=True) onnx.save_model(graph, target, save_as_external_data=True, all_tensors_to_one_file=True, location=target.name + "_data", size_threshold=1024) onnx.checker.check_model(str(target)) print("Exported", target, flush=True) class RefinerGraph: """Translate each sparse convolution to 27 gather/matmul operations. Inputs are explicit neighborhood tables, allowing the same graph to be run on an arbitrary voxel layout and for each refinement iteration. """ def __init__(self, weights): self.weights = weights self.nodes = [] self.constants = {} self.pad_rows = self.constant("pad_rows", np.array([0, 0, 1, 0], np.int64)) self.axis1 = self.constant("axis1", np.array([1], np.int64)) self.taps = [self.constant(f"tap{i}", np.array(i, np.int64)) for i in range(27)] def constant(self, name, value): self.constants[name] = numpy_helper.from_array(np.asarray(value), name) return name def op(self, op, *inputs, **attrs): name = f"v{len(self.nodes)}" self.nodes.append(helper.make_node(op, inputs, [name], name=name, **attrs)) return name def weight(self, name, *, transpose=False): value = self.weights[f"refiner.{name}"].detach().numpy() return self.constant(name, value.T if transpose else value) def linear(self, x, name): return self.op("Add", self.op("MatMul", x, self.weight(name + ".weight", transpose=True)), self.weight(name + ".bias")) def silu(self, x): return self.op("Mul", x, self.op("Sigmoid", x)) def conv(self, x, neighbors, prefix): padded = self.op("Pad", x, self.pad_rows) weights = self.weights[f"refiner.{prefix}.weight"].numpy() weights = weights.reshape(weights.shape[0], 27, weights.shape[-1]) total = self.weight(prefix + ".bias") for tap, index in enumerate(self.taps): rows = self.op("Gather", neighbors, index, axis=1) gathered = self.op("Gather", padded, rows) kernel = self.constant(f"{prefix}.kernel{tap}", weights[:, tap, :].T) total = self.op("Add", total, self.op("MatMul", gathered, kernel)) return total def block(self, x, neighbors, prefix): h = self.op("LayerNormalization", x, self.weight(prefix + ".norm1.weight"), self.weight(prefix + ".norm1.bias"), epsilon=1e-6) h = self.conv(self.silu(h), neighbors, prefix + ".conv1") h = self.conv(self.silu(h), neighbors, prefix + ".conv2") return self.op("Add", x, h) def pool(self, x, k): padded = self.op("Pad", x, self.pad_rows) children = self.op("Gather", padded, f"children{k}") total = self.op("ReduceSum", children, self.axis1, keepdims=0) return self.op("Div", total, f"counts{k}") def build(self): f32, i64 = TensorProto.FLOAT, TensorProto.INT64 vi = helper.make_tensor_value_info inputs = [vi("feats", f32, ["v0", 3]), vi("encoder", f32, ["tokens", 1026]), vi("encoder_index", i64, ["v4"])] inputs += [vi(f"neighbors{i}", i64, [f"v{i}", 27]) for i in range(5)] for i in range(4): inputs.extend([vi(f"parents{i}", i64, [f"v{i}"]), vi(f"children{i}", i64, [f"v{i+1}", 8]), vi(f"counts{i}", f32, [f"v{i+1}", 1])]) x = self.linear("feats", "input_proj") skip = [] for i in range(5): x = self.block(x, f"neighbors{i}", f"down_stages.{i}.0") if i < 4: skip.append(x) x = self.linear(self.pool(x, i), f"downsample_blocks.{i}.linear") encoder = self.op("Gather", "encoder", "encoder_index") x = self.op("Concat", x, self.linear(encoder, "encoder_fuse"), axis=1) x = self.linear(self.silu(self.linear(x, "fuse_proj.0")), "fuse_proj.2") x = self.block(x, "neighbors4", "bottleneck_stage.0") for i in range(4): k = 3 - i x = self.linear(x, f"upsample_blocks.{i}.linear") x = self.op("Add", self.op("Gather", x, f"parents{k}"), skip[k]) x = self.block(x, f"neighbors{k}", f"up_stages.{i}.0") x = self.linear(x, "out_proj") self.nodes.append(helper.make_node("Identity", [x], ["update"])) graph = helper.make_graph(self.nodes, "MoGe3Refiner", inputs, [vi("update", f32, ["v0", 1])], self.constants.values()) return helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)], ir_version=9) def export_refiner(checkpoint, directory): config = checkpoint["model_config"]["refiner"] expected = {"model_channels": [32, 64, 128, 256, 512], "downsample_factors": [2]*4, "encoder_blocks_per_level": 1, "decoder_blocks_per_level": 1, "bottleneck_blocks": 1, "encoder_channels": 1026} if any(config[key] != value for key, value in expected.items()): raise ValueError("Unsupported MoGe-3 checkpoint refiner architecture.") target = directory / "moge3_vitl_refiner.onnx" onnx.save_model(RefinerGraph(checkpoint["model"]).build(), target) onnx.checker.check_model(str(target)) print("Exported", target, flush=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("checkpoint", type=Path) parser.add_argument("directory", type=Path) parser.add_argument("--part", choices=["base", "refiner", "all"], default="all") args = parser.parse_args() args.directory.mkdir(parents=True, exist_ok=True) torch.set_num_threads(2) checkpoint = torch.load(args.checkpoint, map_location="cpu", mmap=True, weights_only=True) if args.part in ("base", "all"): export_base(checkpoint, args.directory) if args.part in ("refiner", "all"): export_refiner(checkpoint, args.directory) if __name__ == "__main__": main()