esp32: add onnx-graphsurgeon dep to export_job.py
Browse files- export_job.py +84 -84
export_job.py
CHANGED
|
@@ -1,84 +1,84 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = ["torch", "torchvision", "pillow", "numpy", "onnx", "onnxscript", "onnx2tf", "tensorflow-cpu", "tf-keras", "huggingface_hub>=0.30", "timm", "datasets>=4.0"]
|
| 4 |
-
# ///
|
| 5 |
-
"""HF-job credibility gate: convert the wave-3 winner checkpoint (best.pt) to a
|
| 6 |
-
quantized TFLite model for ESP32 TFLite-Micro and upload the artifact to the code repo.
|
| 7 |
-
|
| 8 |
-
Path: best.pt -> ONNX (torch.onnx) -> SavedModel (onnx2tf, float) -> TFLite with
|
| 9 |
-
dynamic-range int8 weights (Optimize.DEFAULT). TFLite-Micro runs this fine on ESP32.
|
| 10 |
-
"""
|
| 11 |
-
import os, sys, io
|
| 12 |
-
import numpy as np
|
| 13 |
-
import torch
|
| 14 |
-
from huggingface_hub import HfApi, hf_hub_download
|
| 15 |
-
|
| 16 |
-
tok = os.environ["HF_TOKEN"]
|
| 17 |
-
api = HfApi(token=tok)
|
| 18 |
-
ckpt = hf_hub_download("Tonic/challenge5-acoustic-squeezenet1_1-s7", "best.pt",
|
| 19 |
-
repo_type="model", token=tok)
|
| 20 |
-
print("ckpt:", os.path.getsize(ckpt) // 1024, "KB", flush=True)
|
| 21 |
-
|
| 22 |
-
here = os.path.dirname(os.path.abspath(__file__))
|
| 23 |
-
print("step: torch.load", flush=True)
|
| 24 |
-
ck = torch.load(ckpt, map_location="cpu", weights_only=False)
|
| 25 |
-
print("step: ckpt loaded", flush=True)
|
| 26 |
-
sd = ck.get("state_dict", ck) if isinstance(ck, dict) else ck
|
| 27 |
-
arch = ck.get("arch", "squeezenet1_1") if isinstance(ck, dict) else "squeezenet1_1"
|
| 28 |
-
|
| 29 |
-
import importlib.util
|
| 30 |
-
jt_path = hf_hub_download("Tonic/challenge5-acoustic-code", "job_train.py", repo_type="model", token=tok)
|
| 31 |
-
spec = importlib.util.spec_from_file_location("job_train", jt_path)
|
| 32 |
-
jt = importlib.util.module_from_spec(spec)
|
| 33 |
-
print("step: exec job_train", flush=True)
|
| 34 |
-
spec.loader.exec_module(jt)
|
| 35 |
-
print("step: job_train imported", flush=True)
|
| 36 |
-
backbone, feat = jt.build_backbone(arch, pretrained=False)
|
| 37 |
-
class WakeCNN(torch.nn.Module):
|
| 38 |
-
def __init__(self, b, f):
|
| 39 |
-
super().__init__()
|
| 40 |
-
self.backbone = b
|
| 41 |
-
self.head_wake = torch.nn.Linear(f, 1)
|
| 42 |
-
self.head_class = torch.nn.Linear(f, 4)
|
| 43 |
-
def forward(self, x):
|
| 44 |
-
f = self.backbone(x)
|
| 45 |
-
return self.head_wake(f).squeeze(-1), self.head_class(f)
|
| 46 |
-
model = WakeCNN(backbone, feat)
|
| 47 |
-
sd = {k: v for k, v in sd.items() if k.startswith("backbone.") or k.startswith("head_")}
|
| 48 |
-
print("step: load_state_dict", flush=True)
|
| 49 |
-
model.load_state_dict(sd, strict=True)
|
| 50 |
-
print("step: state loaded", flush=True)
|
| 51 |
-
model.eval()
|
| 52 |
-
print("arch:", arch, "params:", sum(p.numel() for p in model.parameters()), flush=True)
|
| 53 |
-
|
| 54 |
-
SIZE = 224
|
| 55 |
-
onnx_path = "/tmp/model_full_224.onnx"
|
| 56 |
-
torch.onnx.export(model, torch.zeros(1, 3, SIZE, SIZE), onnx_path, opset_version=17, dynamo=False,
|
| 57 |
-
input_names=["spectrogram"], output_names=["wake_logit", "sound_class_logits"],
|
| 58 |
-
dynamic_axes={"spectrogram": {0: "batch"}})
|
| 59 |
-
print("onnx exported", flush=True)
|
| 60 |
-
|
| 61 |
-
print("step: import onnx2tf", flush=True)
|
| 62 |
-
import onnx2tf
|
| 63 |
-
sm_dir = "/tmp/saved_model"
|
| 64 |
-
onnx2tf.convert(input_onnx_file_path=onnx_path, output_folder_path=sm_dir,
|
| 65 |
-
not_use_onnxsim=True, verbosity="error")
|
| 66 |
-
print("onnx2tf done", flush=True)
|
| 67 |
-
|
| 68 |
-
print("step: import tensorflow", flush=True)
|
| 69 |
-
import tensorflow as tf
|
| 70 |
-
print("step: tf imported", flush=True)
|
| 71 |
-
conv = tf.lite.TFLiteConverter.from_saved_model(sm_dir)
|
| 72 |
-
conv.optimizations = [tf.lite.Optimize.DEFAULT] # dynamic-range int8 weights
|
| 73 |
-
tfl = conv.convert()
|
| 74 |
-
out = "/tmp/model_full_224_dynamic_int8.tflite"
|
| 75 |
-
open(out, "wb").write(tfl)
|
| 76 |
-
print("tflite dynamic-int8:", os.path.getsize(out) // 1024, "KB", flush=True)
|
| 77 |
-
|
| 78 |
-
api.upload_file(path_or_fileobj=out, path_in_repo="esp32/model_full_224_dynamic_int8.tflite",
|
| 79 |
-
repo_id="Tonic/challenge5-acoustic-code", repo_type="model", token=tok,
|
| 80 |
-
commit_message=f"esp32: dynamic-int8 tflite of squeezenet1_1-s7 ({os.path.getsize(out)//1024} KB)")
|
| 81 |
-
api.upload_file(path_or_fileobj=onnx_path, path_in_repo="esp32/model_full_224.onnx",
|
| 82 |
-
repo_id="Tonic/challenge5-acoustic-code", repo_type="model", token=tok,
|
| 83 |
-
commit_message="esp32: onnx of squeezenet1_1-s7")
|
| 84 |
-
print("UPLOADED esp32/ artifacts", flush=True)
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = ["torch", "torchvision", "pillow", "numpy", "onnx", "onnxscript", "onnx2tf", "onnx-graphsurgeon", "onnxsim", "tensorflow-cpu", "tf-keras", "huggingface_hub>=0.30", "timm", "datasets>=4.0"]
|
| 4 |
+
# ///
|
| 5 |
+
"""HF-job credibility gate: convert the wave-3 winner checkpoint (best.pt) to a
|
| 6 |
+
quantized TFLite model for ESP32 TFLite-Micro and upload the artifact to the code repo.
|
| 7 |
+
|
| 8 |
+
Path: best.pt -> ONNX (torch.onnx) -> SavedModel (onnx2tf, float) -> TFLite with
|
| 9 |
+
dynamic-range int8 weights (Optimize.DEFAULT). TFLite-Micro runs this fine on ESP32.
|
| 10 |
+
"""
|
| 11 |
+
import os, sys, io
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 15 |
+
|
| 16 |
+
tok = os.environ["HF_TOKEN"]
|
| 17 |
+
api = HfApi(token=tok)
|
| 18 |
+
ckpt = hf_hub_download("Tonic/challenge5-acoustic-squeezenet1_1-s7", "best.pt",
|
| 19 |
+
repo_type="model", token=tok)
|
| 20 |
+
print("ckpt:", os.path.getsize(ckpt) // 1024, "KB", flush=True)
|
| 21 |
+
|
| 22 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 23 |
+
print("step: torch.load", flush=True)
|
| 24 |
+
ck = torch.load(ckpt, map_location="cpu", weights_only=False)
|
| 25 |
+
print("step: ckpt loaded", flush=True)
|
| 26 |
+
sd = ck.get("state_dict", ck) if isinstance(ck, dict) else ck
|
| 27 |
+
arch = ck.get("arch", "squeezenet1_1") if isinstance(ck, dict) else "squeezenet1_1"
|
| 28 |
+
|
| 29 |
+
import importlib.util
|
| 30 |
+
jt_path = hf_hub_download("Tonic/challenge5-acoustic-code", "job_train.py", repo_type="model", token=tok)
|
| 31 |
+
spec = importlib.util.spec_from_file_location("job_train", jt_path)
|
| 32 |
+
jt = importlib.util.module_from_spec(spec)
|
| 33 |
+
print("step: exec job_train", flush=True)
|
| 34 |
+
spec.loader.exec_module(jt)
|
| 35 |
+
print("step: job_train imported", flush=True)
|
| 36 |
+
backbone, feat = jt.build_backbone(arch, pretrained=False)
|
| 37 |
+
class WakeCNN(torch.nn.Module):
|
| 38 |
+
def __init__(self, b, f):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.backbone = b
|
| 41 |
+
self.head_wake = torch.nn.Linear(f, 1)
|
| 42 |
+
self.head_class = torch.nn.Linear(f, 4)
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
f = self.backbone(x)
|
| 45 |
+
return self.head_wake(f).squeeze(-1), self.head_class(f)
|
| 46 |
+
model = WakeCNN(backbone, feat)
|
| 47 |
+
sd = {k: v for k, v in sd.items() if k.startswith("backbone.") or k.startswith("head_")}
|
| 48 |
+
print("step: load_state_dict", flush=True)
|
| 49 |
+
model.load_state_dict(sd, strict=True)
|
| 50 |
+
print("step: state loaded", flush=True)
|
| 51 |
+
model.eval()
|
| 52 |
+
print("arch:", arch, "params:", sum(p.numel() for p in model.parameters()), flush=True)
|
| 53 |
+
|
| 54 |
+
SIZE = 224
|
| 55 |
+
onnx_path = "/tmp/model_full_224.onnx"
|
| 56 |
+
torch.onnx.export(model, torch.zeros(1, 3, SIZE, SIZE), onnx_path, opset_version=17, dynamo=False,
|
| 57 |
+
input_names=["spectrogram"], output_names=["wake_logit", "sound_class_logits"],
|
| 58 |
+
dynamic_axes={"spectrogram": {0: "batch"}})
|
| 59 |
+
print("onnx exported", flush=True)
|
| 60 |
+
|
| 61 |
+
print("step: import onnx2tf", flush=True)
|
| 62 |
+
import onnx2tf
|
| 63 |
+
sm_dir = "/tmp/saved_model"
|
| 64 |
+
onnx2tf.convert(input_onnx_file_path=onnx_path, output_folder_path=sm_dir,
|
| 65 |
+
not_use_onnxsim=True, verbosity="error")
|
| 66 |
+
print("onnx2tf done", flush=True)
|
| 67 |
+
|
| 68 |
+
print("step: import tensorflow", flush=True)
|
| 69 |
+
import tensorflow as tf
|
| 70 |
+
print("step: tf imported", flush=True)
|
| 71 |
+
conv = tf.lite.TFLiteConverter.from_saved_model(sm_dir)
|
| 72 |
+
conv.optimizations = [tf.lite.Optimize.DEFAULT] # dynamic-range int8 weights
|
| 73 |
+
tfl = conv.convert()
|
| 74 |
+
out = "/tmp/model_full_224_dynamic_int8.tflite"
|
| 75 |
+
open(out, "wb").write(tfl)
|
| 76 |
+
print("tflite dynamic-int8:", os.path.getsize(out) // 1024, "KB", flush=True)
|
| 77 |
+
|
| 78 |
+
api.upload_file(path_or_fileobj=out, path_in_repo="esp32/model_full_224_dynamic_int8.tflite",
|
| 79 |
+
repo_id="Tonic/challenge5-acoustic-code", repo_type="model", token=tok,
|
| 80 |
+
commit_message=f"esp32: dynamic-int8 tflite of squeezenet1_1-s7 ({os.path.getsize(out)//1024} KB)")
|
| 81 |
+
api.upload_file(path_or_fileobj=onnx_path, path_in_repo="esp32/model_full_224.onnx",
|
| 82 |
+
repo_id="Tonic/challenge5-acoustic-code", repo_type="model", token=tok,
|
| 83 |
+
commit_message="esp32: onnx of squeezenet1_1-s7")
|
| 84 |
+
print("UPLOADED esp32/ artifacts", flush=True)
|