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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. """
  14. dependencies = ['torch', 'kamal'] # 依赖项
  15. import json
  16. import traceback
  17. import os
  18. import torch
  19. import web
  20. import kamal
  21. from PIL import Image
  22. from kamal.transferability import TransferabilityGraph
  23. from kamal.transferability.trans_metric import AttrMapMetric
  24. from torchvision.models import *
  25. urls = (
  26. '/model_measure/measure', 'Measure',
  27. '/model_measure/package', 'Package',
  28. )
  29. app = web.application(urls, globals())
  30. class Package:
  31. def POST(self):
  32. req = web.data()
  33. save_path_list = []
  34. for json_data in json.loads(req):
  35. try:
  36. metadata = json_data['metadata']
  37. except Exception as e:
  38. traceback.print_exc()
  39. return json.dumps(Response(506, 'Failed to package model, Error: %s'% (traceback.format_exc(limit=1)), save_path_list).__dict__)
  40. entry_name = json_data['entry_name']
  41. for name, fn in kamal.hub.list_entry(__file__):
  42. if entry_name in name:
  43. try:
  44. dataset = metadata['dataset']
  45. model = fn(pretrained=False, num_classes=metadata['entry_args']['num_classes'])
  46. num_params = sum( [ torch.numel(p) for p in model.parameters() ] )
  47. save_path_for_measure = '%sfinegraind_%s/' % (json_data['ckpt'], entry_name)
  48. save_path = save_path_for_measure+'%s' % (metadata['name'])
  49. ckpt = self.file_name(json_data['ckpt'])
  50. if ckpt == '':
  51. return json.dumps(
  52. Response(506, 'Failed to package model [%s]: No .pth file was found in directory ckpt' % (entry_name), save_path_list).__dict__)
  53. model.load_state_dict(torch.load(ckpt), False)
  54. kamal.hub.save( # 该调用将用户的pytorch模型打包成上述格式,并存储至指定位置
  55. model, # 需要保存的模型 nn.Module
  56. save_path=save_path,
  57. # 导出文件夹名称
  58. entry_name=entry_name, # 入口函数名,需要与上边的入口函数一致
  59. spec_name=None, # 具体的参数版本名,为空则自动用md5替代
  60. code_path=__file__, # 模型依赖的代码,可以是文件夹(必须包含hubconf.py文件),
  61. # 或者是当前hubconf.py, 例子中直接使用了依赖中的模型实现,故只需指定为本文件即可
  62. metadata=metadata,
  63. tags=dict(
  64. num_params=num_params,
  65. metadata=metadata,
  66. name=metadata['name'],
  67. url=metadata['url'],
  68. dataset=dataset,
  69. img_size=metadata['input']['size'],
  70. readme=json_data['readme'])
  71. )
  72. save_path_list.append(save_path_for_measure)
  73. return json.dumps(Response(200, 'Success', save_path_list).__dict__)
  74. except Exception:
  75. traceback.print_exc()
  76. return json.dumps(Response(506,'Failed to package model [%s], Error: %s' % (entry_name, traceback.format_exc(limit=1)), save_path_list).__dict__)
  77. return json.dumps(Response(506, 'Failed to package model [%s], Error: %s' % (entry_name, traceback.format_exc(limit=1)), save_path_list).__dict__)
  78. def file_name(self, file_dir):
  79. for root, dirs, files in os.walk(file_dir):
  80. for file in files:
  81. if file.endswith('pth'):
  82. return root + file
  83. return ''
  84. class Measure:
  85. def POST(self):
  86. req = web.data()
  87. json_data = json.loads(req)
  88. print(json_data)
  89. try:
  90. measure_name = 'measure'
  91. zoo_set = json_data['zoo_set']
  92. probe_set_root = json_data['probe_set_root']
  93. export_path = json_data['export_path']
  94. output_filename_list = []
  95. TG = TransferabilityGraph(zoo_set)
  96. print("Add %s" % (probe_set_root))
  97. imgs_set = list(os.listdir(os.path.join(probe_set_root)))
  98. images = [Image.open(os.path.join(probe_set_root, img)) for img in imgs_set]
  99. metric = AttrMapMetric(images, device=torch.device('cuda'))
  100. TG.add_metric(probe_set_root, metric)
  101. isExists = os.path.exists(export_path)
  102. if not isExists:
  103. # 如果不存在则创建目录
  104. os.makedirs(export_path)
  105. output_filename = export_path+'%s.json' % (measure_name)
  106. TG.export_to_json(probe_set_root, output_filename, topk=3, normalize=True)
  107. output_filename_list.append(output_filename)
  108. except Exception:
  109. traceback.print_exc()
  110. return json.dumps(Response(506, 'Failed to generate measurement file of [%s], Error: %s' % (probe_set_root, traceback.format_exc(limit=1)), output_filename_list).__dict__)
  111. return json.dumps(Response(200, 'Success', output_filename_list).__dict__)
  112. class Response:
  113. def __init__(self, code, msg, data):
  114. self.code = code
  115. self.msg = msg
  116. self.data = data
  117. if __name__ == "__main__":
  118. app.run()

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