Implements TensorFlow inference of a saved model, following the same API as the TensorRTInfer class.
| 25 | |
| 26 | |
| 27 | class TensorFlowInfer: |
| 28 | """ |
| 29 | Implements TensorFlow inference of a saved model, following the same API as the TensorRTInfer class. |
| 30 | """ |
| 31 | |
| 32 | def __init__(self, saved_model_path): |
| 33 | gpus = tf.config.experimental.list_physical_devices('GPU') |
| 34 | for gpu in gpus: |
| 35 | tf.config.experimental.set_memory_growth(gpu, True) |
| 36 | |
| 37 | self.model = tf.saved_model.load(saved_model_path) |
| 38 | self.pred_fn = self.model.signatures['serving_default'] |
| 39 | |
| 40 | # Setup I/O bindings |
| 41 | self.batch_size = 1 |
| 42 | self.inputs = [] |
| 43 | fn_inputs = self.pred_fn.structured_input_signature[1] |
| 44 | for i, input in enumerate(list(fn_inputs.values())): |
| 45 | self.inputs.append({ |
| 46 | 'index': i, |
| 47 | 'name': input.name, |
| 48 | 'dtype': np.dtype(input.dtype.as_numpy_dtype()), |
| 49 | 'shape': [1, 512, 512, 3], # This can be overridden later |
| 50 | }) |
| 51 | self.outputs = [] |
| 52 | fn_outputs = self.pred_fn.structured_outputs |
| 53 | for i, output in enumerate(list(fn_outputs.values())): |
| 54 | self.outputs.append({ |
| 55 | 'index': i, |
| 56 | 'name': output.name, |
| 57 | 'dtype': np.dtype(output.dtype.as_numpy_dtype()), |
| 58 | 'shape': output.shape.as_list(), |
| 59 | }) |
| 60 | |
| 61 | def override_input_shape(self, input, shape): |
| 62 | self.inputs[input]['shape'] = shape |
| 63 | self.batch_size = shape[0] |
| 64 | |
| 65 | def input_spec(self): |
| 66 | return self.inputs[0]['shape'], self.inputs[0]['dtype'] |
| 67 | |
| 68 | def output_spec(self): |
| 69 | return self.outputs[0]['shape'], self.outputs[0]['dtype'] |
| 70 | |
| 71 | def infer(self, batch): |
| 72 | # Process I/O and execute the network |
| 73 | input = {self.inputs[0]['name']: tf.convert_to_tensor(batch)} |
| 74 | output = self.pred_fn(**input) |
| 75 | return output |
| 76 | |
| 77 | def process(self, batch, scales=None, nms_threshold=None): |
| 78 | # Infer network |
| 79 | output = self.infer(batch) |
| 80 | |
| 81 | # Extract the results depending on what kind of saved model this is |
| 82 | boxes = None |
| 83 | scores = None |
| 84 | classes = None |