|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Keras model parser. |
| 3 | +
|
| 4 | +@author: rbodo |
| 5 | +""" |
| 6 | + |
| 7 | +import os |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +import keras |
| 11 | +import torch |
| 12 | +import onnx |
| 13 | +from onnx2keras import onnx_to_keras |
| 14 | +import onnxruntime |
| 15 | + |
| 16 | +from snntoolbox.parsing.model_libs import keras_input_lib |
| 17 | +from snntoolbox.utils.utils import import_script |
| 18 | + |
| 19 | + |
| 20 | +def to_numpy(tensor): |
| 21 | + return tensor.detach().cpu().numpy() if tensor.requires_grad \ |
| 22 | + else tensor.cpu().numpy() |
| 23 | + |
| 24 | + |
| 25 | +class ModelParser(keras_input_lib.ModelParser): |
| 26 | + |
| 27 | + def try_insert_flatten(self, layer, idx, name_map): |
| 28 | + return False |
| 29 | + |
| 30 | + |
| 31 | +def load(path, filename): |
| 32 | + """Load network from file. |
| 33 | +
|
| 34 | + Parameters |
| 35 | + ---------- |
| 36 | +
|
| 37 | + path: str |
| 38 | + Path to directory where to load model from. |
| 39 | +
|
| 40 | + filename: str |
| 41 | + Name of file to load model from. |
| 42 | +
|
| 43 | + Returns |
| 44 | + ------- |
| 45 | +
|
| 46 | + : dict[str, Union[keras.models.Sequential, function]] |
| 47 | + A dictionary of objects that constitute the input model. It must |
| 48 | + contain the following two keys: |
| 49 | +
|
| 50 | + - 'model': keras.models.Sequential |
| 51 | + Keras model instance of the network. |
| 52 | + - 'val_fn': function |
| 53 | + Function that allows evaluating the original model. |
| 54 | + """ |
| 55 | + |
| 56 | + filepath = str(os.path.join(path, filename)) |
| 57 | + |
| 58 | + # Load the Pytorch model. |
| 59 | + mod = import_script(path, filename) |
| 60 | + model_pytorch = mod.Model() |
| 61 | + model_pytorch.load_state_dict(torch.load(filepath + '.pkl')) |
| 62 | + |
| 63 | + # Switch from train to eval mode to ensure Dropout / BatchNorm is handled |
| 64 | + # correctly. |
| 65 | + model_pytorch.eval() |
| 66 | + |
| 67 | + # Run on dummy input with correct shape to trace the Pytorch model. |
| 68 | + input_shape = [1] + list(model_pytorch.input_shape) |
| 69 | + input_numpy = np.random.random_sample(input_shape).astype(np.float32) |
| 70 | + input_torch = torch.from_numpy(input_numpy).float() |
| 71 | + output_torch = model_pytorch(input_torch) |
| 72 | + output_numpy = to_numpy(output_torch) |
| 73 | + |
| 74 | + # Export as onnx model, and then reload. |
| 75 | + input_names = ['input_0'] |
| 76 | + output_names = ['output_{}'.format(i) for i in range(len(output_torch))] |
| 77 | + dynamic_axes = {'input_0': {0: 'batch_size'}} |
| 78 | + dynamic_axes.update({name: {0: 'batch_size'} for name in output_names}) |
| 79 | + torch.onnx.export(model_pytorch, input_torch, filepath + '.onnx', |
| 80 | + input_names=input_names, |
| 81 | + output_names=output_names, |
| 82 | + dynamic_axes=dynamic_axes) |
| 83 | + model_onnx = onnx.load(filepath + '.onnx') |
| 84 | + # onnx.checker.check_model(model_onnx) # Crashes with segmentation fault. |
| 85 | + |
| 86 | + # Compute ONNX Runtime output prediction. |
| 87 | + ort_session = onnxruntime.InferenceSession(filepath + '.onnx') |
| 88 | + input_onnx = {ort_session.get_inputs()[0].name: input_numpy} |
| 89 | + output_onnx = ort_session.run(None, input_onnx) |
| 90 | + |
| 91 | + # Compare ONNX Runtime and PyTorch results. |
| 92 | + err_msg = "Pytorch model could not be ported to ONNX. Output difference: " |
| 93 | + np.testing.assert_allclose(output_numpy, output_onnx[0], |
| 94 | + rtol=1e-03, atol=1e-05, err_msg=err_msg) |
| 95 | + print("Pytorch model was successfully ported to ONNX.") |
| 96 | + |
| 97 | + # Port ONNX model to Keras. |
| 98 | + model_keras = onnx_to_keras(model_onnx, input_names, [input_shape[1:]]) |
| 99 | + |
| 100 | + # Save the keras model. |
| 101 | + keras.models.save_model(model_keras, filepath + '.h5') |
| 102 | + |
| 103 | + # Loading the model here is a workaround for version conflicts with |
| 104 | + # TF > 2.0.1 and keras > 2.2.5. Should be able to remove this later. |
| 105 | + model_keras = keras.models.load_model(filepath + '.h5') |
| 106 | + model_keras.compile('sgd', 'categorical_crossentropy', |
| 107 | + ['accuracy', keras.metrics.top_k_categorical_accuracy]) |
| 108 | + |
| 109 | + # Compute Keras output and compare against ONNX. |
| 110 | + output_keras = model_keras.predict(input_numpy) |
| 111 | + err_msg = "ONNX model could not be ported to Keras. Output difference: " |
| 112 | + np.testing.assert_allclose(output_numpy, output_keras, |
| 113 | + rtol=1e-03, atol=1e-05, err_msg=err_msg) |
| 114 | + print("ONNX model was successfully ported to Keras.") |
| 115 | + |
| 116 | + return {'model': model_keras, 'val_fn': model_keras.evaluate} |
| 117 | + |
| 118 | + |
| 119 | +def evaluate(*args, **kwargs): |
| 120 | + return keras_input_lib.evaluate(*args, **kwargs) |
0 commit comments