Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8185 - Refactor test #8231

Open
wants to merge 34 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
075ec11
Eliminates code repetition
garciadias Nov 20, 2024
e8d3e19
Replace relative import with absolute
garciadias Nov 20, 2024
d4b01e6
Directly tests export_ckpt function instead of using command_line_tests
garciadias Nov 21, 2024
bfc68a4
Style fix
garciadias Nov 21, 2024
10eb2af
Merge branch 'dev' into 8185-tests-refactor
garciadias Nov 21, 2024
55fcd22
Revert "Style fix"
garciadias Nov 23, 2024
ba16743
Revert "Replace relative import with absolute"
garciadias Nov 23, 2024
1667eb7
Revert "Directly tests export_ckpt function instead of using command_…
garciadias Nov 23, 2024
702e740
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 24, 2024
9a2c2f4
moves tests to their corresponding folder
garciadias Nov 28, 2024
f2cf158
replace relative imports with absolute import
garciadias Nov 28, 2024
b3fd8e9
Change locating integrations
garciadias Nov 28, 2024
114fc72
Corrects the download path for integration tests
garciadias Nov 28, 2024
626e050
Move array/* and dictionary/* files to parent directory
garciadias Dec 2, 2024
4c6b59c
Move single files on their parent folders
garciadias Dec 2, 2024
050e71b
Merge remote-tracking branch 'upstream/dev' into dev
garciadias Dec 2, 2024
7d68938
Merge branch 'dev' into 8185-tests-refactor
garciadias Dec 2, 2024
3508211
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Dec 2, 2024
2d55074
Recovers deleted file
garciadias Dec 3, 2024
6e9c66e
Merge remote-tracking branch 'upstream/dev' into 8185-tests-refactor
garciadias Dec 3, 2024
fa5c75c
Merge remote-tracking branch 'upstream/dev' into dev
garciadias Dec 4, 2024
dda65c4
Merge branch 'dev' into 8185-tests-refactor
garciadias Dec 4, 2024
bf82225
Start fixing path issues after moving files
garciadias Dec 6, 2024
56c2a48
Keep fixing data paths
garciadias Dec 9, 2024
98d3ab2
rerouting paths
garciadias Dec 11, 2024
6d1af88
Merge remote-tracking branch 'origin/8185-tests-refactor' into 8185-t…
garciadias Dec 11, 2024
a0d2395
Solve many more issues
garciadias Dec 11, 2024
9977e98
Merge remote-tracking branch 'origin/8185-tests-refactor' into 8185-t…
garciadias Dec 11, 2024
8831dc0
reorder imports
garciadias Dec 11, 2024
58c461c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Dec 11, 2024
bb85f53
Fix path issues
garciadias Dec 11, 2024
865dc22
Move utils inside utils to avoid coflict
garciadias Dec 12, 2024
cf1025a
Keep cleaning tests but reverting utils.utils change
Dec 16, 2024
d2e7a2e
Merge remote-tracking branch 'origin/8185-tests-refactor' into 8185-t…
garciadias Jan 8, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ temp/
.DS_Store

# temporary testing data MedNIST
tests/integration/testing_data/MedNIST*
tests/testing_data/MedNIST*
tests/testing_data/*Hippocampus*
tests/testing_data/*.tiff
Expand Down
2 changes: 1 addition & 1 deletion runtests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,7 @@ if [ $doNetTests = true ]
then
set +e # disable exit on failure so that diagnostics can be given on failure
echo "${separator}${blue}integration${noColor}"
for i in tests/*integration_*.py
for i in tests/integration/*.py
do
echo "$i"
${cmdPrefix}${cmd} "$i"
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need such a detailed folder structure for the tests, or would a simpler, flat structure at the top level suffice? Such as only apps/data/transforms...

Copy link
Author

@garciadias garciadias Dec 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the word 'need' is unhelpful here. It's certainly not needed. None of this refactoring is needed. The project survived until now without these.
I think the question is how helpful it is to have the folder separation.
In my opinion, mirroring the structure of the code is the best way for developers to intuitively find the tests related to the portion of the code they are touching. For example, if you are changing something at monai/transforms/lazy/functional.py, it would be helpful to find up to the folder lazy in the tests. In that case, you would find 2 tests there. If you get all tests inside "transforms," you will have 304 test files to go through. Which I think is quite paralyzing.
I understand that some simplification could be beneficial to avoid having super-deep trees. I think @ericspod's proposition so far is good, but we can make it shallower if people find the current state too deep.

If testing is difficult or finding tests is hard, people will tend to ignore the tests or write repeated code.

However, I am not very familiar with the project's code. I am just starting to work on this, and I am happy to follow the team's guidance.

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
108 changes: 108 additions & 0 deletions tests/bundle/test_bundle_ckpt_export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import json
import os
import tempfile
import unittest

from parameterized import parameterized

from monai.bundle import ConfigParser
from monai.data import load_net_with_metadata
from monai.networks import save_state
from tests.utils import command_line_tests, skip_if_windows

TEST_CASE_1 = [True, "", ""]

TEST_CASE_2 = [True, "model", ""]

TEST_CASE_3 = [True, "model", "True"]

TEST_CASE_4 = [False, "", ""]

TEST_CASE_5 = [False, "model", ""]

TEST_CASE_6 = [False, "model", "True"]


@skip_if_windows
class TestCKPTExport(unittest.TestCase):
def setUp(self):
self.device = os.environ.get("CUDA_VISIBLE_DEVICES")
if not self.device:
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # default
self.meta_file = os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json")
self.config_file = os.path.join(os.path.dirname(__file__), "testing_data", "inference.json")
self.tempdir_obj = tempfile.TemporaryDirectory()
tempdir = self.tempdir_obj.name
self.def_args = {"meta_file": "will be replaced by `meta_file` arg"}
self.def_args_file = os.path.join(tempdir, "def_args.yaml")

self.ckpt_file = os.path.join(tempdir, "model.pt")
self.ts_file = os.path.join(tempdir, "model.ts")

self.parser = ConfigParser()
self.parser.export_config_file(config=self.def_args, filepath=self.def_args_file)
self.parser.read_config(self.config_file)
self.net = self.parser.get_parsed_content("network_def")
self.cmd = ["coverage", "run", "-m", "monai.bundle", "ckpt_export", "network_def", "--filepath", self.ts_file]
self.cmd += [
"--meta_file",
self.meta_file,
"--config_file",
f"['{self.config_file}','{self.def_args_file}']",
"--ckpt_file",
]

def tearDown(self):
if self.device is not None:
os.environ["CUDA_VISIBLE_DEVICES"] = self.device
else:
del os.environ["CUDA_VISIBLE_DEVICES"] # previously unset
self.tempdir_obj.cleanup()

@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])
def test_export(self, key_in_ckpt, use_trace):
save_state(src=self.net if key_in_ckpt == "" else {key_in_ckpt: self.net}, path=self.ckpt_file)
full_cmd = self.cmd + [self.ckpt_file, "--key_in_ckpt", key_in_ckpt, "--args_file", self.def_args_file]
if use_trace == "True":
full_cmd += ["--use_trace", use_trace, "--input_shape", "[1, 1, 96, 96, 96]"]
command_line_tests(full_cmd)
self.assertTrue(os.path.exists(self.ts_file))

_, metadata, extra_files = load_net_with_metadata(
self.ts_file, more_extra_files=["inference.json", "def_args.json"]
)
self.assertIn("schema", metadata)
self.assertIn("meta_file", json.loads(extra_files["def_args.json"]))
self.assertIn("network_def", json.loads(extra_files["inference.json"]))

@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])
def test_default_value(self, key_in_ckpt, use_trace):
ckpt_file = os.path.join(self.tempdir_obj.name, "models/model.pt")
ts_file = os.path.join(self.tempdir_obj.name, "models/model.ts")

save_state(src=self.net if key_in_ckpt == "" else {key_in_ckpt: self.net}, path=ckpt_file)

# check with default value
cmd = ["coverage", "run", "-m", "monai.bundle", "ckpt_export", "--key_in_ckpt", key_in_ckpt]
cmd += ["--config_file", self.config_file, "--bundle_root", self.tempdir_obj.name]
if use_trace == "True":
cmd += ["--use_trace", use_trace, "--input_shape", "[1, 1, 96, 96, 96]"]
command_line_tests(cmd)
self.assertTrue(os.path.exists(ts_file))


if __name__ == "__main__":
unittest.main()
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def test_train(self):
data = ExchangeObject(weights=get_state_dict(network))
# test train
for i in range(2):
print(f"Testing round {i+1} of {2}...")
print(f"Testing round {i + 1} of {2}...")
# test evaluate
metric_eo = algo.evaluate(data=data, extra={})
self.assertIsInstance(metric_eo, ExchangeObject)
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def _all_gather(engine):
f_csv = csv.reader(f)
for i, row in enumerate(f_csv):
if i > 0:
expected = [f"{fnames[i-1]}\t{float(i):.4f}\t{float(i + 1):.4f}\t{i + 0.5:.4f}"]
expected = [f"{fnames[i - 1]}\t{float(i):.4f}\t{float(i + 1):.4f}\t{i + 0.5:.4f}"]
self.assertEqual(row, expected)
self.assertTrue(os.path.exists(os.path.join(tempdir, "metric3_summary.csv")))
# check the metric_summary.csv and content
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@


class MedNISTDataset(torch.utils.data.Dataset):

def __init__(self, image_files, labels, transforms):
self.image_files = image_files
self.labels = labels
Expand Down Expand Up @@ -95,7 +94,7 @@ def run_training_test(root_dir, train_x, train_y, val_x, val_y, device="cuda:0",
model = DenseNet121(spatial_dims=2, in_channels=1, out_channels=len(np.unique(train_y))).to(device)
loss_function = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), 1e-5)
epoch_num = 4
epoch_num = 1
val_interval = 1

# start training validation
Expand Down Expand Up @@ -149,7 +148,7 @@ def run_training_test(root_dir, train_x, train_y, val_x, val_y, device="cuda:0",
torch.save(model.state_dict(), model_filename)
print("saved new best metric model")
print(
f"current epoch {epoch +1} current AUC: {auc_value:0.4f} "
f"current epoch {epoch + 1} current AUC: {auc_value:0.4f} "
f"current accuracy: {acc_metric:0.4f} best AUC: {best_metric:0.4f} at epoch {best_metric_epoch}"
)
print(f"train completed, best_metric: {best_metric:0.4f} at epoch: {best_metric_epoch}")
Expand Down Expand Up @@ -183,10 +182,9 @@ def run_inference_test(root_dir, test_x, test_y, device="cuda:0", num_workers=10

@skip_if_quick
class IntegrationClassification2D(DistTestCase):

def setUp(self):
set_determinism(seed=0)
self.data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data")
self.data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../testing_data")
data_dir = os.path.join(self.data_dir, "MedNIST")
dataset_file = os.path.join(self.data_dir, "MedNIST.tar.gz")

Expand Down Expand Up @@ -214,7 +212,7 @@ def setUp(self):
image_classes.extend([i] * len(image_files[i]))

# split train, val, test
valid_frac, test_frac = 0.1, 0.1
valid_frac, test_frac = 0.01, 0.01
self.train_x, self.train_y = [], []
self.val_x, self.val_y = [], []
self.test_x, self.test_y = [], []
Expand Down Expand Up @@ -270,7 +268,7 @@ def train_and_infer(self, idx=0):

def test_training(self):
repeated = []
for i in range(2):
for i in range(1):
results = self.train_and_infer(i)
repeated.append(results)
np.testing.assert_allclose(repeated[0], repeated[1])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0, readers=(None,
writer.add_scalar("train_loss", loss.item(), epoch_len * epoch + step)
epoch_loss /= step
epoch_loss_values.append(epoch_loss)
print(f"epoch {epoch +1} average loss:{epoch_loss:0.4f}")
print(f"epoch {epoch + 1} average loss:{epoch_loss:0.4f}")

if (epoch + 1) % val_interval == 0:
with eval_mode(model):
Expand All @@ -164,7 +164,7 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0, readers=(None,
torch.save(model.state_dict(), model_filename)
print("saved new best metric model")
print(
f"current epoch {epoch +1} current mean dice: {metric:0.4f} "
f"current epoch {epoch + 1} current mean dice: {metric:0.4f} "
f"best mean dice: {best_metric:0.4f} at epoch {best_metric_epoch}"
)
writer.add_scalar("val_mean_dice", metric, epoch + 1)
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from __future__ import annotations

import unittest
from typing import List

import numpy as np
import torch
Expand Down Expand Up @@ -104,7 +103,7 @@ def test_value_class(self, input_params, y_pred, y_gt, expected_value):
metric = PanopticQualityMetric(**input_params)
metric(y_pred, y_gt)
outputs = metric.aggregate()
if isinstance(outputs, List):
if isinstance(outputs, list):
for output, value in zip(outputs, expected_value):
np.testing.assert_allclose(output.cpu().numpy(), np.asarray(value), atol=1e-4)
else:
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading
Loading