Upload convert.py with huggingface_hub
Browse files- convert.py +42 -0
convert.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys, torch, torch.nn as nn
|
| 2 |
+
import coremltools as ct
|
| 3 |
+
sys.path.insert(0, "/tmp/clothseg/repo")
|
| 4 |
+
from network import U2NET
|
| 5 |
+
|
| 6 |
+
CKPT = "/tmp/clothseg/cloth_segm_u2net_latest.pth"
|
| 7 |
+
OUT = "/tmp/clothseg/ClothSegmentation.mlpackage"
|
| 8 |
+
|
| 9 |
+
# Build + load (the checkpoint was saved as a plain state_dict, possibly with a module. prefix).
|
| 10 |
+
net = U2NET(in_ch=3, out_ch=4)
|
| 11 |
+
sd = torch.load(CKPT, map_location="cpu")
|
| 12 |
+
if isinstance(sd, dict) and "model_state_dict" in sd:
|
| 13 |
+
sd = sd["model_state_dict"]
|
| 14 |
+
sd = { (k[7:] if k.startswith("module.") else k): v for k, v in sd.items() }
|
| 15 |
+
net.load_state_dict(sd)
|
| 16 |
+
net.eval()
|
| 17 |
+
|
| 18 |
+
# Wrapper: return only the fused output d0, as per-class softmax probabilities (1,4,768,768).
|
| 19 |
+
class Wrap(nn.Module):
|
| 20 |
+
def __init__(self, m): super().__init__(); self.m = m
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
d0 = self.m(x)[0] # (1,4,768,768) logits
|
| 23 |
+
return torch.softmax(d0, dim=1) # per-class probabilities
|
| 24 |
+
|
| 25 |
+
wrap = Wrap(net).eval()
|
| 26 |
+
dummy = torch.randn(1, 3, 768, 768)
|
| 27 |
+
with torch.no_grad():
|
| 28 |
+
traced = torch.jit.trace(wrap, dummy)
|
| 29 |
+
|
| 30 |
+
# CoreML image input: pixels [0,255] -> model wants (p/255-0.5)/0.5 = p/127.5 - 1.
|
| 31 |
+
mlmodel = ct.convert(
|
| 32 |
+
traced,
|
| 33 |
+
inputs=[ct.ImageType(name="image", shape=(1, 3, 768, 768),
|
| 34 |
+
scale=1.0/127.5, bias=[-1.0, -1.0, -1.0],
|
| 35 |
+
color_layout=ct.colorlayout.RGB)],
|
| 36 |
+
outputs=[ct.TensorType(name="probs")],
|
| 37 |
+
minimum_deployment_target=ct.target.iOS16,
|
| 38 |
+
compute_precision=ct.precision.FLOAT16,
|
| 39 |
+
)
|
| 40 |
+
mlmodel.short_description = "U2NET cloth segmentation (bg/upper/lower/full) — 768x768, softmax probs"
|
| 41 |
+
mlmodel.save(OUT)
|
| 42 |
+
print("SAVED", OUT)
|