11#!/usr/bin/env python3
22import argparse
3+ import inspect
34import json
45import shutil
56from dataclasses import dataclass
67from pathlib import Path
78from typing import Dict , List , Sequence , Tuple
89
10+ import onnx
911import torch
1012from huggingface_hub import snapshot_download
1113from onnxruntime .quantization import quantize_dynamic , QuantType
@@ -40,6 +42,7 @@ class ExportConfig:
4042 max_seq_len : int
4143 opset : int
4244 include_token_type_ids : bool
45+ fp16 : bool
4346 quantize : bool
4447 validate : bool
4548 validate_quantized : bool
@@ -151,6 +154,33 @@ def export_onnx(
151154 )
152155
153156
157+ def load_fp16_converter ():
158+ try :
159+ from onnxruntime .transformers .float16 import convert_float_to_float16
160+
161+ return convert_float_to_float16
162+ except ImportError :
163+ try :
164+ from onnxconverter_common .float16 import convert_float_to_float16
165+
166+ return convert_float_to_float16
167+ except ImportError as exc :
168+ raise RuntimeError (
169+ "FP16 conversion requires onnxruntime.transformers.float16 or onnxconverter-common."
170+ ) from exc
171+
172+
173+ def export_fp16 (onnx_path : Path , fp16_path : Path ) -> None :
174+ converter = load_fp16_converter ()
175+ model = onnx .load (onnx_path .as_posix ())
176+ params = inspect .signature (converter ).parameters
177+ kwargs = {}
178+ if "keep_io_types" in params :
179+ kwargs ["keep_io_types" ] = True
180+ fp16_model = converter (model , ** kwargs )
181+ onnx .save (fp16_model , fp16_path .as_posix ())
182+
183+
154184def export (config : ExportConfig ) -> None :
155185 config .output_dir .mkdir (parents = True , exist_ok = True )
156186
@@ -177,6 +207,9 @@ def export(config: ExportConfig) -> None:
177207 opset = config .opset ,
178208 )
179209
210+ if config .fp16 :
211+ export_fp16 (onnx_path , config .output_dir / "model_fp16.onnx" )
212+
180213 if config .quantize :
181214 quantize_dynamic (
182215 onnx_path .as_posix (),
@@ -243,6 +276,11 @@ def parse_args() -> ExportConfig:
243276 action = "store_true" ,
244277 help = "Include token_type_ids input in the ONNX graph." ,
245278 )
279+ parser .add_argument (
280+ "--no-fp16" ,
281+ action = "store_true" ,
282+ help = "Skip FP16 conversion step." ,
283+ )
246284 parser .add_argument (
247285 "--no-validate" ,
248286 action = "store_true" ,
@@ -270,6 +308,7 @@ def parse_args() -> ExportConfig:
270308 max_seq_len = args .max_seq_len ,
271309 opset = args .opset ,
272310 include_token_type_ids = args .include_token_type_ids ,
311+ fp16 = not args .no_fp16 ,
273312 quantize = not args .no_quantize ,
274313 validate = not args .no_validate ,
275314 validate_quantized = args .validate_quantized ,
0 commit comments