Datasets:
File size: 3,633 Bytes
7a108b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | """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")
|