Datasets:
Download scripts/export.py from HuggingFaceM4/reachy-gestures-data: direct link, hf CLI and curl.
- Browser
- Download file 1.8 kB
-
https://huggingface.co/datasets/HuggingFaceM4/reachy-gestures-data/resolve/main/scripts/export.py
- Command line
-
hf download hf://datasets/HuggingFaceM4/reachy-gestures-data/scripts/export.py
-
curl -L -o export.py https://huggingface.co/datasets/HuggingFaceM4/reachy-gestures-data/resolve/main/scripts/export.py
1.8 kB
| """Export a trained run to ONNX and an 8-bit build for the robot: python export.py runs/<name> | |
| Writes model.onnx (float) and model_qint8.onnx next to gesture_heads.npz, keeping the encoder's inputs and its | |
| token-embedding output so the app's tokenizer and pooling code stay as they are. | |
| """ | |
| import sys | |
| from pathlib import Path | |
| import torch | |
| from transformers import AutoModel | |
| from onnxruntime.quantization import QuantType, quantize_dynamic | |
| run = Path(sys.argv[1]) | |
| model = AutoModel.from_pretrained(run, torch_dtype=torch.float32).eval() | |
| inputs = ["input_ids", "attention_mask"] + (["token_type_ids"] if model.config.model_type in ("bert", "xlm-roberta") else []) | |
| example = {"input_ids": torch.full((1, 8), 5, dtype=torch.int64), "attention_mask": torch.ones(1, 8, dtype=torch.int64), | |
| "token_type_ids": torch.zeros(1, 8, dtype=torch.int64)} # xlm-roberta has a single token type | |
| class Wrapper(torch.nn.Module): | |
| def __init__(self) -> None: | |
| super().__init__() | |
| self.model = model | |
| def forward(self, *args: torch.Tensor) -> torch.Tensor: | |
| return self.model(**dict(zip(inputs, args))).last_hidden_state | |
| axes = {name: {0: "batch", 1: "sequence"} for name in inputs} | {"token_embeddings": {0: "batch", 1: "sequence"}} | |
| torch.onnx.export(Wrapper(), tuple(example[n] for n in inputs), run / "model.onnx", input_names=inputs, | |
| output_names=["token_embeddings"], dynamic_axes=axes, opset_version=17, dynamo=False) | |
| quantize_dynamic(run / "model.onnx", run / "model_qint8.onnx", weight_type=QuantType.QInt8, per_channel=False, | |
| op_types_to_quantize=["MatMul", "Gemm", "Gather"]) | |
| for leftover in run.glob("*.onnx.data"): | |
| print("external data:", leftover) | |
| print({p.name: round(p.stat().st_size / 1e6) for p in run.glob("*.onnx")}) | |