You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

oneflow_inference_service.py 4.1 kB

4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. """
  2. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. """
  13. import oneflow as flow
  14. import oneflow.core.serving.saved_model_pb2 as saved_model_pb
  15. import numpy as np
  16. import requests
  17. from PIL import Image
  18. from io import BytesIO
  19. import google.protobuf.text_format as text_format
  20. import os
  21. from imagenet1000_clsidx_to_labels import clsidx_2_labels
  22. from logger import Logger
  23. from service.abstract_inference_service import AbstractInferenceService
  24. log = Logger().logger
  25. class OneFlowInferenceService(AbstractInferenceService):
  26. """
  27. oneflow 框架推理service
  28. """
  29. def __init__(self, args):
  30. super().__init__()
  31. self.args = args
  32. self.model_name = args.model_name
  33. self.model_path = args.model_path
  34. flow.clear_default_session()
  35. self.infer_session = flow.SimpleSession()
  36. self.load_model()
  37. def load_image(self, image_path):
  38. global im
  39. if image_path.startswith("http"):
  40. response = requests.get(image_path)
  41. response = response.content
  42. BytesIOObj = BytesIO()
  43. BytesIOObj.write(response)
  44. im = Image.open(BytesIOObj)
  45. else:
  46. im = Image.open(image_path)
  47. input_names = self.infer_session.list_inputs()
  48. batch_size, channel, height, width = self.infer_session.input_info(input_names[0])["shape"]
  49. im = im.resize((height, width))
  50. im = im.convert('RGB') # 有的图像是单通道的,不加转换会报错
  51. im = np.array(im).astype('float32')
  52. im = (im - [123.68, 116.779, 103.939]) / [58.393, 57.12, 57.375]
  53. im = np.transpose(im, (2, 0, 1))
  54. im = np.expand_dims(im, axis=0)
  55. log.info("===============> load image success <===============")
  56. im = np.ascontiguousarray(im, 'float32')
  57. images = np.repeat(im, batch_size, axis=0).astype(np.float32)
  58. return images
  59. def load_model(self):
  60. log.info("===============> start load oneflow model :" + self.model_path + " <===============")
  61. model_meta_file_path = os.path.join(
  62. self.model_path, "saved_model.prototxt"
  63. )
  64. # load saved model
  65. saved_model_proto = saved_model_pb.SavedModel()
  66. with open(model_meta_file_path, "rb") as f:
  67. text_format.Merge(f.read(), saved_model_proto)
  68. checkpoint_path = os.path.join(
  69. self.model_path, saved_model_proto.checkpoint_dir[0]
  70. )
  71. self.infer_session.set_checkpoint_path(checkpoint_path)
  72. for job_name, signature in saved_model_proto.signatures_v2.items():
  73. self.infer_session.setup_job_signature(job_name, signature)
  74. for job_name, net in saved_model_proto.graphs.items():
  75. with self.infer_session.open(job_name) as session:
  76. session.compile(net.op)
  77. self.infer_session.launch()
  78. log.info("===============> load oneflow model success <===============")
  79. return saved_model_proto
  80. def inference(self, image):
  81. data = {"data_name": image['data_name']}
  82. log.info("===============> start load " + image['data_name'] + " <===============")
  83. images = self.load_image(image['data_path'])
  84. predictions = self.infer_session.run('inference', image=images)
  85. top_k_idx = predictions[0][0]
  86. top_5_idx = top_k_idx.argsort()[::-1][0:5]
  87. data['predictions'] = list()
  88. for label_id in top_5_idx:
  89. result = {"label": clsidx_2_labels[label_id], "probability": "{:.3f}".format(top_k_idx[label_id])}
  90. data['predictions'].append(result)
  91. return data

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能