samwell commited on
Commit
96dce1f
·
verified ·
1 Parent(s): a878f0f

Upload export_medsiglip.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. export_medsiglip.py +412 -0
export_medsiglip.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LaborView AI - MedSigLIP Edge Export
3
+ Export trained MedSigLIP model to ONNX/CoreML/TFLite for mobile deployment
4
+ """
5
+
6
+ # /// script
7
+ # dependencies = [
8
+ # "torch>=2.0.0",
9
+ # "transformers>=4.50.0",
10
+ # "onnx>=1.14.0",
11
+ # "onnxruntime>=1.16.0",
12
+ # "onnxruntime-gpu>=1.16.0",
13
+ # "huggingface_hub>=0.20.0",
14
+ # "numpy>=1.24.0",
15
+ # "pillow>=10.0.0",
16
+ # ]
17
+ # ///
18
+
19
+ import os
20
+ import sys
21
+ import json
22
+ import argparse
23
+ from pathlib import Path
24
+ from dataclasses import dataclass
25
+ from typing import Dict, List, Optional, Tuple
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+ import numpy as np
31
+ from PIL import Image
32
+
33
+
34
+ @dataclass
35
+ class Config:
36
+ # Model
37
+ encoder_pretrained: str = "google/medsiglip-448"
38
+ encoder_hidden_dim: int = 1152
39
+ projection_dim: int = 256
40
+ num_plane_classes: int = 2
41
+ num_seg_classes: int = 3
42
+ image_size: int = 448
43
+
44
+ # Export
45
+ hub_model_id: str = "samwell/laborview-medsiglip"
46
+ output_dir: Path = Path("./exports")
47
+ opset_version: int = 17
48
+
49
+
50
+ class SegmentationDecoder(nn.Module):
51
+ """Decoder for upsampling vision features to segmentation mask"""
52
+
53
+ def __init__(self, input_dim: int, num_classes: int, decoder_channels=[512, 256, 128, 64]):
54
+ super().__init__()
55
+
56
+ self.input_proj = nn.Conv2d(input_dim, decoder_channels[0], 1)
57
+
58
+ self.up_blocks = nn.ModuleList()
59
+ in_ch = decoder_channels[0]
60
+ for out_ch in decoder_channels[1:]:
61
+ self.up_blocks.append(nn.Sequential(
62
+ nn.ConvTranspose2d(in_ch, out_ch, 4, stride=2, padding=1),
63
+ nn.BatchNorm2d(out_ch),
64
+ nn.GELU()
65
+ ))
66
+ in_ch = out_ch
67
+
68
+ self.final_up = nn.Sequential(
69
+ nn.ConvTranspose2d(decoder_channels[-1], 32, 4, stride=2, padding=1),
70
+ nn.BatchNorm2d(32),
71
+ nn.GELU(),
72
+ nn.ConvTranspose2d(32, 32, 4, stride=2, padding=1),
73
+ nn.BatchNorm2d(32),
74
+ nn.GELU(),
75
+ )
76
+
77
+ self.classifier = nn.Conv2d(32, num_classes, 1)
78
+
79
+ def forward(self, x, target_size=None):
80
+ B = x.shape[0]
81
+
82
+ if x.dim() == 3:
83
+ num_patches = x.shape[1]
84
+ H = W = int(num_patches ** 0.5)
85
+ x = x.transpose(1, 2).reshape(B, -1, H, W)
86
+
87
+ x = self.input_proj(x)
88
+
89
+ for block in self.up_blocks:
90
+ x = block(x)
91
+
92
+ x = self.final_up(x)
93
+ x = self.classifier(x)
94
+
95
+ if target_size:
96
+ x = F.interpolate(x, size=target_size, mode='bilinear', align_corners=False)
97
+
98
+ return x
99
+
100
+
101
+ class LaborViewMedSigLIP(nn.Module):
102
+ """LaborView model with MedSigLIP vision encoder"""
103
+
104
+ def __init__(self, config: Config):
105
+ super().__init__()
106
+ self.config = config
107
+
108
+ from transformers import AutoModel
109
+
110
+ print(f"Loading MedSigLIP from {config.encoder_pretrained}...")
111
+ self.encoder = AutoModel.from_pretrained(
112
+ config.encoder_pretrained,
113
+ trust_remote_code=True
114
+ )
115
+
116
+ if hasattr(self.encoder, 'vision_model'):
117
+ self.vision_encoder = self.encoder.vision_model
118
+ else:
119
+ self.vision_encoder = self.encoder
120
+
121
+ if hasattr(self.vision_encoder.config, 'hidden_size'):
122
+ hidden_dim = self.vision_encoder.config.hidden_size
123
+ else:
124
+ hidden_dim = config.encoder_hidden_dim
125
+
126
+ self.projector = nn.Sequential(
127
+ nn.Linear(hidden_dim, config.projection_dim),
128
+ nn.LayerNorm(config.projection_dim),
129
+ nn.GELU(),
130
+ nn.Linear(config.projection_dim, config.projection_dim)
131
+ )
132
+
133
+ self.cls_head = nn.Linear(config.projection_dim, config.num_plane_classes)
134
+ self.seg_decoder = SegmentationDecoder(hidden_dim, config.num_seg_classes)
135
+
136
+ def forward(self, pixel_values):
137
+ if hasattr(self, 'vision_encoder'):
138
+ outputs = self.vision_encoder(pixel_values)
139
+ else:
140
+ outputs = self.encoder.get_image_features(pixel_values, return_dict=True)
141
+
142
+ if hasattr(outputs, 'last_hidden_state'):
143
+ hidden = outputs.last_hidden_state
144
+ elif hasattr(outputs, 'pooler_output'):
145
+ hidden = outputs.pooler_output
146
+ else:
147
+ hidden = outputs
148
+
149
+ if hidden.dim() == 2:
150
+ pooled = hidden
151
+ B, D = hidden.shape
152
+ seq = hidden.unsqueeze(1).expand(B, 32*32, D)
153
+ elif hidden.dim() == 3:
154
+ pooled = hidden.mean(dim=1)
155
+ seq = hidden
156
+ else:
157
+ B, D, H, W = hidden.shape
158
+ pooled = hidden.mean(dim=[2, 3])
159
+ seq = hidden.flatten(2).transpose(1, 2)
160
+
161
+ projected = self.projector(pooled)
162
+ plane_logits = self.cls_head(projected)
163
+ seg_masks = self.seg_decoder(seq, target_size=pixel_values.shape[-2:])
164
+
165
+ return plane_logits, seg_masks
166
+
167
+
168
+ class LaborViewExportWrapper(nn.Module):
169
+ """Wrapper for ONNX export - returns dict-like outputs"""
170
+
171
+ def __init__(self, model):
172
+ super().__init__()
173
+ self.model = model
174
+
175
+ def forward(self, pixel_values):
176
+ plane_logits, seg_masks = self.model(pixel_values)
177
+ # Return segmentation probabilities and class prediction
178
+ seg_probs = F.softmax(seg_masks, dim=1)
179
+ plane_pred = plane_logits.argmax(dim=1)
180
+ return seg_probs, plane_pred
181
+
182
+
183
+ def load_trained_model(config: Config):
184
+ """Load trained model from HuggingFace Hub"""
185
+ from huggingface_hub import hf_hub_download
186
+
187
+ print(f"Downloading model from {config.hub_model_id}...")
188
+
189
+ # Download checkpoint
190
+ checkpoint_path = hf_hub_download(
191
+ repo_id=config.hub_model_id,
192
+ filename="best.pt"
193
+ )
194
+
195
+ print(f"Loading checkpoint from {checkpoint_path}...")
196
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
197
+
198
+ # Create model
199
+ model = LaborViewMedSigLIP(config)
200
+
201
+ # Load state dict
202
+ model.load_state_dict(checkpoint["model_state_dict"])
203
+
204
+ print(f"Model loaded successfully!")
205
+ if "val_loss" in checkpoint:
206
+ print(f" Val Loss: {checkpoint['val_loss']:.4f}")
207
+ if "val_iou" in checkpoint:
208
+ print(f" Val IoU: {checkpoint['val_iou']:.4f}")
209
+
210
+ return model
211
+
212
+
213
+ def export_to_onnx(model, config: Config, quantize: bool = True):
214
+ """Export model to ONNX format"""
215
+ import onnx
216
+ from onnxruntime.quantization import quantize_dynamic, QuantType
217
+
218
+ config.output_dir.mkdir(parents=True, exist_ok=True)
219
+
220
+ model.eval()
221
+ wrapper = LaborViewExportWrapper(model)
222
+ wrapper.eval()
223
+
224
+ # Create dummy input
225
+ dummy_input = torch.randn(1, 3, config.image_size, config.image_size)
226
+
227
+ # Export paths
228
+ onnx_path = config.output_dir / "laborview_medsiglip.onnx"
229
+ onnx_quant_path = config.output_dir / "laborview_medsiglip_int8.onnx"
230
+
231
+ print(f"Exporting to ONNX: {onnx_path}")
232
+
233
+ # Export to ONNX
234
+ torch.onnx.export(
235
+ wrapper,
236
+ dummy_input,
237
+ str(onnx_path),
238
+ export_params=True,
239
+ opset_version=config.opset_version,
240
+ do_constant_folding=True,
241
+ input_names=['pixel_values'],
242
+ output_names=['seg_probs', 'plane_pred'],
243
+ dynamic_axes={
244
+ 'pixel_values': {0: 'batch_size'},
245
+ 'seg_probs': {0: 'batch_size'},
246
+ 'plane_pred': {0: 'batch_size'}
247
+ }
248
+ )
249
+
250
+ # Verify ONNX model
251
+ onnx_model = onnx.load(str(onnx_path))
252
+ onnx.checker.check_model(onnx_model)
253
+ print(f"ONNX model verified successfully!")
254
+
255
+ # Get model size
256
+ onnx_size = onnx_path.stat().st_size / (1024 * 1024 * 1024)
257
+ print(f"ONNX model size: {onnx_size:.2f} GB")
258
+
259
+ # Quantize to INT8
260
+ if quantize:
261
+ print(f"Quantizing to INT8: {onnx_quant_path}")
262
+ quantize_dynamic(
263
+ str(onnx_path),
264
+ str(onnx_quant_path),
265
+ weight_type=QuantType.QInt8
266
+ )
267
+
268
+ quant_size = onnx_quant_path.stat().st_size / (1024 * 1024 * 1024)
269
+ print(f"Quantized model size: {quant_size:.2f} GB")
270
+ print(f"Size reduction: {(1 - quant_size/onnx_size) * 100:.1f}%")
271
+
272
+ return onnx_path, onnx_quant_path if quantize else None
273
+
274
+
275
+ def export_to_coreml(model, config: Config):
276
+ """Export model to CoreML format for iOS"""
277
+ try:
278
+ import coremltools as ct
279
+ except ImportError:
280
+ print("coremltools not installed. Skipping CoreML export.")
281
+ print("Install with: pip install coremltools")
282
+ return None
283
+
284
+ config.output_dir.mkdir(parents=True, exist_ok=True)
285
+
286
+ model.eval()
287
+ wrapper = LaborViewExportWrapper(model)
288
+ wrapper.eval()
289
+
290
+ # Trace the model
291
+ dummy_input = torch.randn(1, 3, config.image_size, config.image_size)
292
+ traced_model = torch.jit.trace(wrapper, dummy_input)
293
+
294
+ coreml_path = config.output_dir / "laborview_medsiglip.mlpackage"
295
+
296
+ print(f"Exporting to CoreML: {coreml_path}")
297
+
298
+ # Convert to CoreML
299
+ mlmodel = ct.convert(
300
+ traced_model,
301
+ inputs=[
302
+ ct.TensorType(
303
+ name="pixel_values",
304
+ shape=(1, 3, config.image_size, config.image_size),
305
+ dtype=np.float32
306
+ )
307
+ ],
308
+ outputs=[
309
+ ct.TensorType(name="seg_probs"),
310
+ ct.TensorType(name="plane_pred")
311
+ ],
312
+ minimum_deployment_target=ct.target.iOS16,
313
+ compute_precision=ct.precision.FLOAT16 # Use FP16 for mobile
314
+ )
315
+
316
+ # Add metadata
317
+ mlmodel.author = "LaborView AI"
318
+ mlmodel.short_description = "Ultrasound segmentation for labor monitoring"
319
+ mlmodel.version = "1.0"
320
+
321
+ # Save
322
+ mlmodel.save(str(coreml_path))
323
+
324
+ print(f"CoreML model saved!")
325
+
326
+ return coreml_path
327
+
328
+
329
+ def verify_onnx_model(onnx_path: Path, config: Config):
330
+ """Verify ONNX model with sample inference"""
331
+ import onnxruntime as ort
332
+
333
+ print(f"\nVerifying ONNX model: {onnx_path}")
334
+
335
+ # Create session
336
+ session = ort.InferenceSession(str(onnx_path))
337
+
338
+ # Get input/output info
339
+ input_info = session.get_inputs()[0]
340
+ print(f"Input: {input_info.name}, shape: {input_info.shape}, type: {input_info.type}")
341
+
342
+ for output in session.get_outputs():
343
+ print(f"Output: {output.name}, shape: {output.shape}, type: {output.type}")
344
+
345
+ # Run inference
346
+ dummy_input = np.random.randn(1, 3, config.image_size, config.image_size).astype(np.float32)
347
+
348
+ outputs = session.run(None, {"pixel_values": dummy_input})
349
+
350
+ seg_probs, plane_pred = outputs
351
+ print(f"\nTest inference:")
352
+ print(f" Segmentation output shape: {seg_probs.shape}")
353
+ print(f" Plane prediction: {plane_pred}")
354
+
355
+ # Measure inference time
356
+ import time
357
+ times = []
358
+ for _ in range(10):
359
+ start = time.time()
360
+ session.run(None, {"pixel_values": dummy_input})
361
+ times.append(time.time() - start)
362
+
363
+ avg_time = np.mean(times) * 1000
364
+ print(f" Average inference time: {avg_time:.1f} ms")
365
+
366
+ return True
367
+
368
+
369
+ def main():
370
+ parser = argparse.ArgumentParser(description="Export MedSigLIP for edge deployment")
371
+ parser.add_argument("--output-dir", type=str, default="./exports", help="Output directory")
372
+ parser.add_argument("--quantize", action="store_true", default=True, help="Quantize to INT8")
373
+ parser.add_argument("--coreml", action="store_true", help="Export to CoreML")
374
+ parser.add_argument("--verify", action="store_true", default=True, help="Verify exported model")
375
+ args = parser.parse_args()
376
+
377
+ config = Config()
378
+ config.output_dir = Path(args.output_dir)
379
+
380
+ # Load trained model
381
+ model = load_trained_model(config)
382
+ model.eval()
383
+
384
+ # Export to ONNX
385
+ onnx_path, onnx_quant_path = export_to_onnx(model, config, quantize=args.quantize)
386
+
387
+ # Verify
388
+ if args.verify and onnx_path:
389
+ verify_onnx_model(onnx_path, config)
390
+ if onnx_quant_path:
391
+ verify_onnx_model(onnx_quant_path, config)
392
+
393
+ # Export to CoreML
394
+ if args.coreml:
395
+ export_to_coreml(model, config)
396
+
397
+ print("\n" + "="*50)
398
+ print("Export Summary:")
399
+ print("="*50)
400
+
401
+ for f in config.output_dir.glob("*"):
402
+ size_mb = f.stat().st_size / (1024 * 1024)
403
+ if size_mb > 1024:
404
+ print(f" {f.name}: {size_mb/1024:.2f} GB")
405
+ else:
406
+ print(f" {f.name}: {size_mb:.1f} MB")
407
+
408
+ print("\nDone!")
409
+
410
+
411
+ if __name__ == "__main__":
412
+ main()