Datasets:
Download harness/export_decoder.py from cp500/hyperkd-rs: direct link, hf CLI and curl.
- Browser
- Download file 3.63 kB
-
https://huggingface.co/datasets/cp500/hyperkd-rs/resolve/main/harness/export_decoder.py
- Command line
-
hf download hf://datasets/cp500/hyperkd-rs/harness/export_decoder.py
-
curl -L -o export_decoder.py https://huggingface.co/datasets/cp500/hyperkd-rs/resolve/main/harness/export_decoder.py
3.63 kB
| """Export the HyperKD-RS fine-tuned SAM 2.1 decoder to ONNX int8, drop-in | |
| compatible with the Space's existing sam2bp_decoder_int8.onnx interface: | |
| in : image_embed, high_res_feats_0/1, point_coords, point_labels, | |
| mask_input, has_mask_input | |
| out: masks (N,3,256,256) clamped, iou_predictions (N,3) | |
| Quantization: dynamic int8 on MatMul only (matches the shipped encoder/decoder; | |
| ort-web WASM has no ConvInteger kernel). | |
| Usage: python export_decoder.py (on the GPU box, from ~/run) | |
| """ | |
| import os | |
| import torch | |
| import torch.nn as nn | |
| from sam2.build_sam import build_sam2 | |
| sam = build_sam2("configs/sam2.1/sam2.1_hiera_b+.yaml", | |
| os.path.expanduser("~/sam2/checkpoints/sam2.1_hiera_base_plus.pt"), | |
| device="cpu") | |
| ck = torch.load(os.path.expanduser("~/sam21_hyperkd_decoder.pt"), map_location="cpu") | |
| sam.sam_mask_decoder.load_state_dict(ck["decoder"]) | |
| sam.sam_prompt_encoder.load_state_dict(ck["prompt"]) | |
| sam.eval() | |
| class Decoder(nn.Module): | |
| def __init__(self, model): | |
| super().__init__() | |
| self.pe = model.sam_prompt_encoder | |
| self.md = model.sam_mask_decoder | |
| self.img_size = model.image_size # 1024 | |
| def forward(self, image_embed, high_res_feats_0, high_res_feats_1, | |
| point_coords, point_labels, mask_input, has_mask_input): | |
| # embed points (match prompt-encoder internals at fixed 1024 input) | |
| pc = point_coords + 0.5 | |
| pc = pc / self.img_size | |
| pe = self.pe.pe_layer._pe_encoding(pc) | |
| pl = point_labels.unsqueeze(-1) | |
| pe = pe * (pl != -1) | |
| pe = pe + self.pe.not_a_point_embed.weight * (pl == -1) | |
| for i in range(self.pe.num_point_embeddings): | |
| pe = pe + self.pe.point_embeddings[i].weight * (pl == i) | |
| sparse = pe | |
| dense = self.pe.mask_downscaling(mask_input) * has_mask_input.reshape(-1, 1, 1, 1) + \ | |
| self.pe.no_mask_embed.weight.reshape(1, -1, 1, 1) * (1 - has_mask_input.reshape(-1, 1, 1, 1)) | |
| masks, ious, _, _ = self.md( | |
| image_embeddings=image_embed, | |
| image_pe=self.pe.get_dense_pe(), | |
| sparse_prompt_embeddings=sparse, | |
| dense_prompt_embeddings=dense, | |
| multimask_output=True, | |
| repeat_image=point_coords.shape[0] > 1, | |
| high_res_features=[high_res_feats_0, high_res_feats_1]) | |
| return torch.clamp(masks, -32.0, 32.0), ious | |
| dec = Decoder(sam) | |
| args = (torch.randn(1, 256, 64, 64), torch.randn(1, 32, 256, 256), | |
| torch.randn(1, 64, 128, 128), torch.randn(1, 1, 2), | |
| torch.ones(1, 1), torch.zeros(1, 1, 256, 256), torch.zeros(1)) | |
| torch.onnx.export(dec, args, os.path.expanduser("~/sam2bp_decoder_ft.onnx"), | |
| input_names=["image_embed", "high_res_feats_0", "high_res_feats_1", | |
| "point_coords", "point_labels", "mask_input", "has_mask_input"], | |
| output_names=["masks", "iou_predictions"], | |
| dynamic_axes={"point_coords": {0: "num_labels", 1: "num_points"}, | |
| "point_labels": {0: "num_labels", 1: "num_points"}, | |
| "mask_input": {0: "num_labels"}, | |
| "has_mask_input": {0: "num_labels"}}, | |
| opset_version=17) | |
| from onnxruntime.quantization import quantize_dynamic, QuantType | |
| quantize_dynamic(os.path.expanduser("~/sam2bp_decoder_ft.onnx"), | |
| os.path.expanduser("~/sam2bp_decoder_ft_int8.onnx"), | |
| weight_type=QuantType.QInt8, op_types_to_quantize=["MatMul"]) | |
| import pathlib | |
| for f in ("sam2bp_decoder_ft.onnx", "sam2bp_decoder_ft_int8.onnx"): | |
| p = pathlib.Path.home() / f | |
| print(f, f"{p.stat().st_size/1e6:.1f} MB") | |
| print("EXPORT_DONE") | |