Caffe2 - Python API
A deep learning, cross platform ML framework
update-caffe2-models.py
1 #! /usr/bin/env python
2 
3 from __future__ import absolute_import
4 from __future__ import division
5 from __future__ import print_function
6 from __future__ import unicode_literals
7 
8 import os
9 import subprocess
10 import sys
11 import tarfile
12 import tempfile
13 
14 from six.moves.urllib.request import urlretrieve
15 
16 from caffe2.python.models.download import downloadFromURLToFile, getURLFromName, deleteDirectory
17 
18 class SomeClass:
19  # largely copied from
20  # https://github.com/onnx/onnx-caffe2/blob/master/tests/caffe2_ref_test.py
21  def _download(self, model):
22  model_dir = self._caffe2_model_dir(model)
23  assert not os.path.exists(model_dir)
24  os.makedirs(model_dir)
25  for f in ['predict_net.pb', 'init_net.pb', 'value_info.json']:
26  url = getURLFromName(model, f)
27  dest = os.path.join(model_dir, f)
28  try:
29  try:
30  downloadFromURLToFile(url, dest,
31  show_progress=False)
32  except TypeError:
33  # show_progress not supported prior to
34  # Caffe2 78c014e752a374d905ecfb465d44fa16e02a28f1
35  # (Sep 17, 2017)
36  downloadFromURLToFile(url, dest)
37  except Exception as e:
38  print("Abort: {reason}".format(reason=e))
39  print("Cleaning up...")
40  deleteDirectory(model_dir)
41  exit(1)
42 
43  def _caffe2_model_dir(self, model):
44  caffe2_home = os.path.expanduser('~/.caffe2')
45  models_dir = os.path.join(caffe2_home, 'models')
46  return os.path.join(models_dir, model)
47 
48  def _onnx_model_dir(self, model):
49  onnx_home = os.path.expanduser('~/.onnx')
50  models_dir = os.path.join(onnx_home, 'models')
51  model_dir = os.path.join(models_dir, model)
52  return model_dir, os.path.dirname(model_dir)
53 
54  # largely copied from
55  # https://github.com/onnx/onnx/blob/master/onnx/backend/test/runner/__init__.py
56  def _prepare_model_data(self, model):
57  model_dir, models_dir = self._onnx_model_dir(model)
58  if os.path.exists(model_dir):
59  return
60  os.makedirs(model_dir)
61  url = 'https://s3.amazonaws.com/download.onnx/models/{}.tar.gz'.format(model)
62 
63  # On Windows, NamedTemporaryFile cannot be opened for a
64  # second time
65  download_file = tempfile.NamedTemporaryFile(delete=False)
66  try:
67  download_file.close()
68  print('Start downloading model {} from {}'.format(model, url))
69  urlretrieve(url, download_file.name)
70  print('Done')
71  with tarfile.open(download_file.name) as t:
72  t.extractall(models_dir)
73  except Exception as e:
74  print('Failed to prepare data for model {}: {}'.format(model, e))
75  raise
76  finally:
77  os.remove(download_file.name)
78 
79 models = [
80  'bvlc_alexnet',
81  'densenet121',
82  'inception_v1',
83  'inception_v2',
84  'resnet50',
85 
86  # TODO currently onnx can't translate squeezenet :(
87  # 'squeezenet',
88 
89  'vgg16',
90 
91  # TODO currently vgg19 doesn't work in the CI environment,
92  # possibly due to OOM
93  # 'vgg19'
94 ]
95 
96 def download_models():
97  sc = SomeClass()
98  for model in models:
99  print('update-caffe2-models.py: downloading', model)
100  caffe2_model_dir = sc._caffe2_model_dir(model)
101  onnx_model_dir, onnx_models_dir = sc._onnx_model_dir(model)
102  if not os.path.exists(caffe2_model_dir):
103  sc._download(model)
104  if not os.path.exists(onnx_model_dir):
105  sc._prepare_model_data(model)
106 
107 def generate_models():
108  sc = SomeClass()
109  for model in models:
110  print('update-caffe2-models.py: generating', model)
111  caffe2_model_dir = sc._caffe2_model_dir(model)
112  onnx_model_dir, onnx_models_dir = sc._onnx_model_dir(model)
113  subprocess.check_call(['echo', model])
114  with open(os.path.join(caffe2_model_dir, 'value_info.json'), 'r') as f:
115  value_info = f.read()
116  subprocess.check_call([
117  'convert-caffe2-to-onnx',
118  '--caffe2-net-name', model,
119  '--caffe2-init-net', os.path.join(caffe2_model_dir, 'init_net.pb'),
120  '--value-info', value_info,
121  '-o', os.path.join(onnx_model_dir, 'model.pb'),
122  os.path.join(caffe2_model_dir, 'predict_net.pb')
123  ])
124  subprocess.check_call([
125  'tar',
126  '-czf',
127  model + '.tar.gz',
128  model
129  ], cwd=onnx_models_dir)
130 
131 def upload_models():
132  sc = SomeClass()
133  for model in models:
134  print('update-caffe2-models.py: uploading', model)
135  onnx_model_dir, onnx_models_dir = sc._onnx_model_dir(model)
136  subprocess.check_call([
137  'aws',
138  's3',
139  'cp',
140  model + '.tar.gz',
141  "s3://download.onnx/models/{}.tar.gz".format(model),
142  '--acl', 'public-read'
143  ], cwd=onnx_models_dir)
144 
145 def cleanup():
146  sc = SomeClass()
147  for model in models:
148  onnx_model_dir, onnx_models_dir = sc._onnx_model_dir(model)
149  os.remove(os.path.join(os.path.dirname(onnx_model_dir), model + '.tar.gz'))
150 
151 if __name__ == '__main__':
152  try:
153  subprocess.check_call(['aws', 'sts', 'get-caller-identity'])
154  except:
155  print('update-caffe2-models.py: please run `aws configure` manually to set up credentials')
156  sys.exit(1)
157  if sys.argv[1] == 'download':
158  download_models()
159  if sys.argv[1] == 'generate':
160  generate_models()
161  elif sys.argv[1] == 'upload':
162  upload_models()
163  elif sys.argv[1] == 'cleanup':
164  cleanup()