MCPcopy Create free account
hub / github.com/apache/singa / save_states

Method save_states

examples/cnn_ms/pkg_model_code/model.py:247–306  ·  view source on GitHub ↗

Save states. Args: fpath: output file path (without the extension) aux_states(dict): values are standard data types or Tensor, e.g., epoch ID, learning rate, optimizer states

(self, fpath, aux_states={})

Source from the content-addressed store, hash-verified

245 return self.forward(*input, **kwargs)
246
247 def save_states(self, fpath, aux_states={}):
248 """Save states.
249
250 Args:
251 fpath: output file path (without the extension)
252 aux_states(dict): values are standard data types or Tensor,
253 e.g., epoch ID, learning rate, optimizer states
254 """
255 assert not os.path.isfile(fpath), (
256 "Failed to save states, %s is already existed." % fpath)
257
258 states = self.get_states()
259
260 # save states data and attr
261 tensor_dict = {}
262 states_attr = {}
263 for k, v in states.items():
264 assert isinstance(v, tensor.Tensor), "Only tensor state is allowed"
265 tensor_dict[k] = tensor.to_numpy(v)
266 states_attr[k] = {
267 'state_type': self.MODEL_STATE_TYPE,
268 'shape': v.shape,
269 'dtype': v.dtype
270 }
271
272 for k, v in aux_states.items():
273 assert isinstance(v,
274 tensor.Tensor), "Only tensor aux state is allowed"
275 tensor_dict[k] = tensor.to_numpy(v)
276 states_attr[k] = {
277 'state_type': self.AUX_STATE_TYPE,
278 'shape': v.shape,
279 'dtype': v.dtype
280 }
281
282 # save to files
283 timestamp = time.time()
284 tmp_dir = '/tmp/singa_save_states_%s' % timestamp
285 os.mkdir(tmp_dir)
286 tensor_dict_fp = tmp_dir + self.TENSOR_DICT_FILENAME
287 states_attr_fp = tmp_dir + self.STATES_ATTR_FILENAME
288
289 np.savez(tensor_dict_fp, **tensor_dict)
290
291 with open(states_attr_fp, 'w') as fp:
292 json.dump(states_attr, fp)
293
294 compression = zipfile.ZIP_DEFLATED
295 with zipfile.ZipFile(fpath, mode="w") as zf:
296 zf.write(tensor_dict_fp,
297 os.path.basename(tensor_dict_fp),
298 compress_type=compression)
299 zf.write(states_attr_fp,
300 os.path.basename(states_attr_fp),
301 compress_type=compression)
302
303 # clean up tmp files
304 os.remove(tensor_dict_fp)

Callers 1

runFunction · 0.45

Calls 2

writeMethod · 0.80
get_statesMethod · 0.45

Tested by

no test coverage detected