automl icon indicating copy to clipboard operation
automl copied to clipboard

How can I save it as an ONNX model?

Open WonTaeYeon opened this issue 6 years ago • 13 comments

hi, thx for your code...

How can I save it as an ONNX model?

WonTaeYeon avatar Mar 27 '20 00:03 WonTaeYeon

The only possible way to do this is to use tf2onnx opset 10 without the final nms layer. Because the original freeze mode will save the model with multilevel outputs of class_net and box_net results. I modefied the freeze runmode and apply postprocess.pre_nms at the build_model outputs to generate pre_nms outputs of boxes, scores, classes

Using:

tensorflow 2.4.0 tf2onnx 1.8.1 onnx 1.8.0

  def build_model_with_head(self, inputs: tf.Tensor) -> List[tf.Tensor]:
    """Build model with inputs and labels and print out model stats."""
    logging.info('start building model')
    
    cls_outputs, box_outputs = inference.build_model(
        self.model_name,
        inputs,
        **self.model_config)
    
    # Build postprocessing.
    params = copy.deepcopy(self.model_config.as_dict())
	
    # From det_model_fn eval mode
    params.update(dict(is_training_bn=False))
    params['nms_configs']['max_nms_inputs'] = 3000 #To apply topk ops with TopK Max num in TRT = 3840
	
    cls_outputs = postprocess.to_list(cls_outputs)
    box_outputs = postprocess.to_list(box_outputs)

    # Post process withuot pre nms
    boxes, scores, classes = postprocess.pre_nms(params, cls_outputs, box_outputs)

    # Write to tfevent for tensorboard.
    train_writer = tf.summary.FileWriter(self.logdir)
    train_writer.add_graph(tf.get_default_graph())
    train_writer.flush()

    return [boxes, scores, classes] 

Here is the result on TRT Engine

[01/20/2021-13:20:53] [I] Host latency [01/20/2021-13:20:53] [I] min: 6.29041 ms (end to end 6.38879 ms) [01/20/2021-13:20:53] [I] max: 6.41406 ms (end to end 11.5585 ms) [01/20/2021-13:20:53] [I] mean: 6.33285 ms (end to end 11.3116 ms) [01/20/2021-13:20:53] [I] median: 6.328 ms (end to end 11.3507 ms) [01/20/2021-13:20:53] [I] percentile: 6.39037 ms at 99% (end to end 11.4932 ms at 99%) [01/20/2021-13:20:53] [I] throughput: 172.432 qps [01/20/2021-13:20:53] [I] walltime: 3.00408 s [01/20/2021-13:20:53] [I] GPU Compute [01/20/2021-13:20:53] [I] min: 5.75745 ms [01/20/2021-13:20:53] [I] max: 5.86829 ms [01/20/2021-13:20:53] [I] mean: 5.79436 ms [01/20/2021-13:20:53] [I] median: 5.78723 ms [01/20/2021-13:20:53] [I] percentile: 5.84607 ms at 99% [01/20/2021-13:20:53] [I] total compute time: 3.00148 s

haritsahm avatar Jan 20 '21 13:01 haritsahm

@haritsahm Look like you are able to convert tf to tensorRT. Can you share the whole code/procedure?

hoangmt avatar Apr 08 '21 20:04 hoangmt

@haritsahm Look like you are able to convert tf to tensorRT. Can you share the whole code/procedure?

Sorry it's been a long time since I tried it and I lost the code due to storage error. Maybe you can try the new steps from PR#962 using tf2onnx.

But the idea is this:

  1. freeze the model without the pre-processing since ONNX/TensorRT doesn't support TF Image Placeholder etc.
  2. Use tf2onnx to export the freezed model and check the onnx model using Netron to see it is correctly exported and no pruned graphs
  3. Try to add the nms post-processing and export the model again using tf2onnx

The problem that I had before was the NMS post processing since it has some ops that aren't supported by TensorRT so the model was badly pruned. I notice that the TensorRT version wasn't the latest (7.0)

haritsahm avatar Apr 09 '21 13:04 haritsahm

@haritsahm Thank you so much for suggestion. I was able to convert the model without preprocessing and without postprocessing. The steps are (just in case other people also face the problem):

  1. Freeze the model without pre and post processing:
import sys
sys.path.append('automl/efficientdet')
from keras import inference
driver = inference.ServingDriver('efficientdet-d0','efficientdet-d0_checkpoint_folder',only_network=True, model_params={'num_classes': 90, 'moving_average_decay': 0})
driver.build()
driver.export('efficientdet-d0-saved_model_dir')
  1. Convert to ONNX: python3 -m tf2onnx.convert --saved-model efficientdet-d0-saved_model_dir --output efficientdet-d0_nwonly.onnx --opset 11 --fold_const --target tensorrt

  2. Convert to RT: trtexec --onnx=efficientdet-d0_nwonly.onnx --saveEngine=efficientdet-d0_nwonly.trt --fp16 --buildOnly --workspace=1000

I need to work on adding preprocessing and postprocessing before and after running efficientdet-d0_nwonly.trt. Will update here for others to follow.

hoangmt avatar Apr 12 '21 18:04 hoangmt

A quick update. When running trt model, the output is different from running tf model, using tensor of shape (512,512,3) contains all 0. Most of the output from trt model are 0 while output from tf model are not. I am investigating. Might be a bug generated by trtexec? Did you try running trt model on some input @haritsahm ?

hoangmt avatar Apr 14 '21 18:04 hoangmt

A quick update. When running trt model, the output is different from running tf model, using tensor of shape (512,512,3) contains all 0. Most of the output from trt model are 0 while output from tf model are not. I am investigating. Might be a bug generated by trtexec? Did you try running trt model on some input @haritsahm ?

Yes the same thing also happened to me. Did you check the onnx graph before exporting it to TensorRT? I don't think it's a bug because trtexec will delete/prune/merge some useless nodes, graphs, ops (correct me if Im wrong) to optimize the engine.

haritsahm avatar Apr 15 '21 02:04 haritsahm

@haritsahm, Thank you so much for replying. I have checked onnx model, the graph is connected. I have also tried onnx model using onnxruntime. The result from tf and onnx are closed to each other but totally different from trt.

hoangmt avatar Apr 15 '21 06:04 hoangmt

@haritsahm, Thank you so much for replying. I have checked onnx model, the graph is connected. I have also tried onnx model using onnxruntime. The result from tf and onnx are closed to each other but totally different from trt.

Ah good to know! So the problem must be with TensorRT. I suggest to try debug the whole TensorRT process with Polygraphy. I will try it later on my spare time

maybe @mingxingtan or @fsx950223 can help with this issue. Thank you!

haritsahm avatar Apr 15 '21 06:04 haritsahm

@haritsahm Thank you. I posted an issue in tensorRT repo on detail how to replicate as well as the models. Just for reference: https://github.com/NVIDIA/TensorRT/issues/1194

hoangmt avatar Apr 15 '21 07:04 hoangmt

@hoangmt , looks like you converted original tpu EfficientDet model in your first step (freeze model without pre and post processing) and used automl APIs. Would you have any suggestions to apply for the custom model trained using tensorflow object detection API 2?. We use exporter_main_v2.py to create savedmodel from check point files. Do we need to modify this, so that we can skip the pre and post processing step while saving as savedmodel?

VeeranjaneyuluToka avatar Apr 15 '21 09:04 VeeranjaneyuluToka

I believe there is no difference. I will try it after fixing the above issue.

hoangmt avatar Apr 15 '21 09:04 hoangmt

Looks like inference that you used above is specific to automl. I am checking it and post here if i find a way.

VeeranjaneyuluToka avatar Apr 15 '21 09:04 VeeranjaneyuluToka

@haritsahm Polygraphy is a great tool. It confirms that the results are different. Output from polygraphy run efficientdet-d0_nwonly.onnx --trt --onnxrt


[I] Runner: trt-runner-N0-04/20/21-20:43:57          | Activating and starting inference
[TensorRT] WARNING: [TRT]/home/jenkins/workspace/OSS/L0_MergeRequest/oss/parsers/onnx/onnx2trt_utils.cpp:220: Your ONNX model has been generated with INT64 weights, while TensorRT does not natively support INT64. Attempting to cast down to INT32.
[I] Building engine with configuration: max_workspace_size=16777216 bytes (16.00 MB) | tf32=False, fp16=False, int8=False, strict_types=False | 1 profiles
[I] Runner: trt-runner-N0-04/20/21-20:43:57          | Completed 1 iterations.
[I] Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Activating and starting inference
[I] Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Completed 1 iterations.
[I] Accuracy Comparison | trt-runner-N0-04/20/21-20:43:57 vs. onnxrt-runner-N0-04/20/21-20:43:57
[I]     Comparing Output: 'output_4' (dtype=float32, shape=(1, 4, 4, 810)) with 'output_4' (dtype=float32, shape=(1, 4, 4, 810))
[I]         Required tolerances: [atol=0.87389] OR [rtol=1e-05, atol=0.87383] OR [rtol=0.20267, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-6.5328, min=-9.6361 at (0, 1, 2, 664), max=-3.5694 at (0, 2, 2, 54)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-6.4176, min=-9.3779 at (0, 1, 2, 664), max=-3.2235 at (0, 1, 1, 324)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_9' (dtype=float32, shape=(1, 4, 4, 36)) with 'output_9' (dtype=float32, shape=(1, 4, 4, 36))
[I]         Required tolerances: [atol=0.17882] OR [rtol=1e-05, atol=0.17882] OR [rtol=7.0958, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-0.091448, min=-0.54466 at (0, 2, 2, 19), max=0.32343 at (0, 0, 0, 0)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-0.096405, min=-0.56071 at (0, 2, 2, 31), max=0.30159 at (0, 0, 0, 0)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_3' (dtype=float32, shape=(1, 8, 8, 810)) with 'output_3' (dtype=float32, shape=(1, 8, 8, 810))
[I]         Required tolerances: [atol=0.68331] OR [rtol=1e-05, atol=0.68324] OR [rtol=0.17018, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-6.8013, min=-9.7306 at (0, 3, 1, 162), max=-2.9203 at (0, 4, 3, 594)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-6.8167, min=-9.4594 at (0, 3, 3, 162), max=-2.7687 at (0, 4, 4, 594)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_8' (dtype=float32, shape=(1, 8, 8, 36)) with 'output_8' (dtype=float32, shape=(1, 8, 8, 36))
[I]         Required tolerances: [atol=0.20207] OR [rtol=1e-05, atol=0.20206] OR [rtol=119.12, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-0.0084417, min=-0.42068 at (0, 2, 0, 3), max=0.49135 at (0, 4, 4, 30)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-0.0094595, min=-0.42487 at (0, 3, 7, 11), max=0.54484 at (0, 4, 4, 30)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_2' (dtype=float32, shape=(1, 16, 16, 810)) with 'output_2' (dtype=float32, shape=(1, 16, 16, 810))
[I]         Required tolerances: [atol=0.92894] OR [rtol=1e-05, atol=0.92887] OR [rtol=0.16824, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-7.1851, min=-10.13 at (0, 7, 6, 72), max=-4.2356 at (0, 11, 5, 594)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-7.1618, min=-9.8995 at (0, 6, 5, 72), max=-4.3057 at (0, 10, 5, 594)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_7' (dtype=float32, shape=(1, 16, 16, 36)) with 'output_7' (dtype=float32, shape=(1, 16, 16, 36))
[I]         Required tolerances: [atol=0.40775] OR [rtol=1e-05, atol=0.40774] OR [rtol=14476, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-0.0096572, min=-1.2089 at (0, 0, 0, 3), max=1.4409 at (0, 0, 0, 0)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-0.011599, min=-0.80111 at (0, 0, 0, 3), max=1.0734 at (0, 0, 0, 0)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_1' (dtype=float32, shape=(1, 32, 32, 810)) with 'output_1' (dtype=float32, shape=(1, 32, 32, 810))
[I]         Required tolerances: [atol=3.3337] OR [rtol=1e-05, atol=3.3336] OR [rtol=0.48781, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-7.4557, min=-11.968 at (0, 1, 1, 683), max=-4.2842 at (0, 28, 28, 603)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-7.4016, min=-10.791 at (0, 15, 21, 72), max=-4.0198 at (0, 29, 29, 291)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_6' (dtype=float32, shape=(1, 32, 32, 36)) with 'output_6' (dtype=float32, shape=(1, 32, 32, 36))
[I]         Required tolerances: [atol=1.6836] OR [rtol=1e-05, atol=1.6835] OR [rtol=8588.9, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=0.0020516, min=-5.0281 at (0, 0, 0, 3), max=5.0922 at (0, 0, 0, 0)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-0.00058793, min=-3.3446 at (0, 0, 0, 3), max=3.5692 at (0, 0, 0, 0)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_0' (dtype=float32, shape=(1, 64, 64, 810)) with 'output_0' (dtype=float32, shape=(1, 64, 64, 810))
[I]         Required tolerances: [atol=4.199] OR [rtol=1e-05, atol=4.1989] OR [rtol=0.53565, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-7.9652, min=-13.541 at (0, 4, 1, 702), max=-2.5416 at (0, 0, 0, 0)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-7.9062, min=-13.093 at (0, 1, 1, 702), max=-2.4043 at (0, 0, 0, 0)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[I]     Comparing Output: 'output_5' (dtype=float32, shape=(1, 64, 64, 36)) with 'output_5' (dtype=float32, shape=(1, 64, 64, 36))
[I]         Required tolerances: [atol=11.113] OR [rtol=1e-05, atol=11.113] OR [rtol=21514, atol=1e-05]
        Runner: trt-runner-N0-04/20/21-20:43:57          | Stats: mean=-0.0075114, min=-11.986 at (0, 1, 0, 2), max=10.978 at (0, 0, 0, 1)
        Runner: onnxrt-runner-N0-04/20/21-20:43:57       | Stats: mean=-0.0072811, min=-19.534 at (0, 0, 0, 2), max=13.411 at (0, 1, 0, 1)
[E]         FAILED | Difference exceeds tolerance (rtol=1e-05, atol=1e-05)
[E]     FAILED | Mismatched outputs: ['output_4', 'output_9', 'output_3', 'output_8', 'output_2', 'output_7', 'output_1', 'output_6', 'output_0', 'output_5']
[E] FAILED | Command: /usr/local/bin/polygraphy run efficientdet-d0_nwonly.onnx --trt --onnxrt

I am trying to look for the part of the network I start to see the difference, however, this will take time and don't know how to fix the issue afterward.

We should closed the discussion here as it is now the same as https://github.com/NVIDIA/TensorRT/issues/1194

hoangmt avatar Apr 22 '21 08:04 hoangmt