MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / test_load_weights

Method test_load_weights

tests/bundle/test_bundle_download.py:313–361  ·  view source on GitHub ↗
(self, bundle_files, bundle_name, repo, device, model_file)

Source from the content-addressed store, hash-verified

311 @parameterized.expand([TEST_CASE_7])
312 @skip_if_quick
313 def test_load_weights(self, bundle_files, bundle_name, repo, device, model_file):
314 with skip_if_downloading_fails():
315 with tempfile.TemporaryDirectory() as tempdir:
316 bundle_root = os.path.join(tempdir, bundle_name)
317 # load weights
318 model_1 = load(
319 name=bundle_name,
320 model_file=model_file,
321 bundle_dir=tempdir,
322 repo=repo,
323 source="github",
324 progress=False,
325 device=device,
326 )
327 # prepare network
328 with open(os.path.join(bundle_root, bundle_files[2])) as f:
329 net_args = json.load(f)["network_def"]
330 model_name = net_args["_target_"]
331 del net_args["_target_"]
332 model = getattr(nets, model_name)(**net_args)
333 model.to(device)
334 model.load_state_dict(model_1)
335 model.eval()
336
337 # prepare data and test
338 input_tensor = torch.load(
339 os.path.join(bundle_root, bundle_files[4]), map_location=device, weights_only=True
340 )
341 output = model.forward(input_tensor)
342 expected_output = torch.load(
343 os.path.join(bundle_root, bundle_files[3]), map_location=device, weights_only=True
344 )
345 assert_allclose(output, expected_output, atol=1e-3, rtol=1e-3, type_test=False)
346
347 # load instantiated model directly and test, since the bundle has been downloaded,
348 # there is no need to input `repo`
349 _model_2 = getattr(nets, model_name)(**net_args)
350 model_2 = load(
351 name=bundle_name,
352 model=_model_2,
353 model_file=model_file,
354 bundle_dir=tempdir,
355 progress=False,
356 device=device,
357 source="github",
358 )
359 model_2.eval()
360 output_2 = model_2.forward(input_tensor)
361 assert_allclose(output_2, expected_output, atol=1e-3, rtol=1e-3, type_test=False)
362
363 @parameterized.expand([TEST_CASE_8])
364 @skip_if_quick

Callers

nothing calls this directly

Calls 6

loadFunction · 0.90
assert_allcloseFunction · 0.90
loadMethod · 0.80
load_state_dictMethod · 0.45
forwardMethod · 0.45

Tested by

no test coverage detected