diff --git a/testbed/EleutherAI__lm-evaluation-harness/CODEOWNERS b/testbed/EleutherAI__lm-evaluation-harness/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..5a08ab244564ec729e87ec6a0603c5cfeef721c3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/CODEOWNERS @@ -0,0 +1 @@ +* @haileyschoelkopf @lintangsutawika @baberabb diff --git a/testbed/EleutherAI__lm-evaluation-harness/pyproject.toml b/testbed/EleutherAI__lm-evaluation-harness/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1bc0944ecfc17ecaa662862fc541497f497c6e4a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/pyproject.toml @@ -0,0 +1,107 @@ +[build-system] +requires = ["setuptools>=40.8.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "lm_eval" +version = "0.4.4" +authors = [ + {name="EleutherAI", email="contact@eleuther.ai"} +] +description = "A framework for evaluating language models" +readme = "README.md" +classifiers = [ + "Development Status :: 3 - Alpha", + "Programming Language :: Python :: 3", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", +] +requires-python = ">=3.8" +license = { "text" = "MIT" } +dependencies = [ + "accelerate>=0.26.0", + "evaluate", + "datasets>=2.16.0", + "evaluate>=0.4.0", + "jsonlines", + "numexpr", + "peft>=0.2.0", + "pybind11>=2.6.2", + "pytablewriter", + "rouge-score>=0.0.4", + "sacrebleu>=1.5.0", + "scikit-learn>=0.24.1", + "sqlitedict", + "torch>=1.8", + "tqdm-multiprocess", + "transformers>=4.1", + "zstandard", + "dill", + "word2number", + "more_itertools", +] + +[tool.setuptools.packages.find] +include = ["lm_eval*"] + +# required to include yaml files in pip installation +[tool.setuptools.package-data] +lm_eval = ["**/*.yaml", "tasks/**/*"] + +[project.scripts] +lm-eval = "lm_eval.__main__:cli_evaluate" +lm_eval = "lm_eval.__main__:cli_evaluate" + +[project.urls] +Homepage = "https://github.com/EleutherAI/lm-evaluation-harness" +Repository = "https://github.com/EleutherAI/lm-evaluation-harness" + +[project.optional-dependencies] +api = ["requests", "aiohttp", "tenacity", "tqdm", "tiktoken"] +dev = ["pytest", "pytest-cov", "pytest-xdist", "pre-commit", "mypy"] +deepsparse = ["deepsparse-nightly[llm]>=1.8.0.20240404"] +gptq = ["auto-gptq[triton]>=0.6.0"] +hf_transfer = ["hf_transfer"] +ifeval = ["langdetect", "immutabledict", "nltk>=3.9.1"] +neuronx = ["optimum[neuronx]"] +mamba = ["mamba_ssm", "causal-conv1d==1.0.2"] +math = ["sympy>=1.12", "antlr4-python3-runtime==4.11"] +multilingual = ["nagisa>=0.2.7", "jieba>=0.42.1", "pycountry"] +optimum = ["optimum[openvino]"] +promptsource = ["promptsource>=0.2.3"] +sentencepiece = ["sentencepiece>=0.1.98"] +sparseml = ["sparseml-nightly[llm]>=1.8.0.20240404"] +testing = ["pytest", "pytest-cov", "pytest-xdist"] +vllm = ["vllm>=0.4.2"] +zeno = ["pandas", "zeno-client"] +wandb = ["wandb>=0.16.3", "pandas", "numpy"] +all = [ + "lm_eval[anthropic]", + "lm_eval[dev]", + "lm_eval[deepsparse]", + "lm_eval[gptq]", + "lm_eval[hf_transfer]", + "lm_eval[ifeval]", + "lm_eval[mamba]", + "lm_eval[math]", + "lm_eval[multilingual]", + "lm_eval[openai]", + "lm_eval[promptsource]", + "lm_eval[sentencepiece]", + "lm_eval[sparseml]", + "lm_eval[testing]", + "lm_eval[vllm]", + "lm_eval[zeno]", + "lm_eval[wandb]", +] + +[tool.ruff.lint] +extend-select = ["I"] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["lm_eval"] + +[tool.ruff.lint.extend-per-file-ignores] +"__init__.py" = ["F401","F402","F403"] +"utils.py" = ["F401"] diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_utils.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dfa8741aefdc7a49eda07ae483e411be3e3ec2e1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_utils.py @@ -0,0 +1,398 @@ +import itertools + +import numpy as np +import pytest +import torch + +from lm_eval.api.metrics import ( + aggregate_subtask_metrics, + mean, + pooled_sample_stderr, + stderr_for_metric, +) +from lm_eval.models.utils import Collator +from lm_eval.utils import ( + get_rolling_token_windows, + make_disjoint_window, +) + + +# noinspection DuplicatedCode +def test_get_rolling_token_windows_v1(): + gold = [ + ([-100, 0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + ( + [9, 10, 11, 12, 13, 14, 15, 16, 17, 18], + [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], + ), + ( + [19, 20, 21, 22, 23, 24, 25, 26, 27, 28], + [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], + ), + ([23, 24, 25, 26, 27, 28, 29, 30, 31, 32], [30, 31, 32, 33]), + ] + x = list(range(34)) + generator = get_rolling_token_windows( + token_list=x, + prefix_token=-100, + max_seq_len=10, + context_len=1, + ) + pred_length = 0 + output = [] + for input_tokens, pred_tokens in generator: + output.extend([(input_tokens, pred_tokens)]) + pred_length += len(pred_tokens) + assert pred_length == len(x) + assert gold == output + + +# noinspection DuplicatedCode +def test_get_rolling_token_windows_v2(): + gold = [ + ([-100, 0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + ([2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [10, 11, 12]), + ([5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [13, 14, 15]), + ([8, 9, 10, 11, 12, 13, 14, 15, 16, 17], [16, 17, 18]), + ([11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [19, 20, 21]), + ([14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [22, 23, 24]), + ([17, 18, 19, 20, 21, 22, 23, 24, 25, 26], [25, 26, 27]), + ([20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [28, 29, 30]), + ([23, 24, 25, 26, 27, 28, 29, 30, 31, 32], [31, 32, 33]), + ] + x = list(range(34)) + generator = get_rolling_token_windows( + token_list=x, + prefix_token=-100, + max_seq_len=10, + context_len=8, + ) + pred_length = 0 + output = [] + for input_tokens, pred_tokens in generator: + output.extend([(input_tokens, pred_tokens)]) + pred_length += len(pred_tokens) + assert pred_length == len(x) + assert gold == output + + +# noinspection DuplicatedCode +def test_get_rolling_token_windows_v3(): + gold = [ + ([-100, 0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10]), + ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11]), + ([2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12]), + ([3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [13]), + ([4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [14]), + ([5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [15]), + ([6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [16]), + ([7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [17]), + ([8, 9, 10, 11, 12, 13, 14, 15, 16, 17], [18]), + ([9, 10, 11, 12, 13, 14, 15, 16, 17, 18], [19]), + ([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20]), + ([11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21]), + ([12, 13, 14, 15, 16, 17, 18, 19, 20, 21], [22]), + ([13, 14, 15, 16, 17, 18, 19, 20, 21, 22], [23]), + ([14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [24]), + ([15, 16, 17, 18, 19, 20, 21, 22, 23, 24], [25]), + ([16, 17, 18, 19, 20, 21, 22, 23, 24, 25], [26]), + ([17, 18, 19, 20, 21, 22, 23, 24, 25, 26], [27]), + ([18, 19, 20, 21, 22, 23, 24, 25, 26, 27], [28]), + ([19, 20, 21, 22, 23, 24, 25, 26, 27, 28], [29]), + ([20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30]), + ([21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [31]), + ([22, 23, 24, 25, 26, 27, 28, 29, 30, 31], [32]), + ([23, 24, 25, 26, 27, 28, 29, 30, 31, 32], [33]), + ] + x = list(range(34)) + generator = get_rolling_token_windows( + token_list=x, + prefix_token=-100, + max_seq_len=10, + context_len=10, + ) + pred_length = 0 + output = [] + for input_tokens, pred_tokens in generator: + output.extend([(input_tokens, pred_tokens)]) + pred_length += len(pred_tokens) + assert pred_length == len(x) + assert gold == output + + +# noinspection DuplicatedCode +def test_get_rolling_token_windows_v4(): + gold = [ + ([-100, 0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10]), + ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11]), + ([2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12]), + ([3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [13]), + ([4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [14]), + ([5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [15]), + ([6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [16]), + ([7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [17]), + ([8, 9, 10, 11, 12, 13, 14, 15, 16, 17], [18]), + ([9, 10, 11, 12, 13, 14, 15, 16, 17, 18], [19]), + ([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20]), + ([11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21]), + ([12, 13, 14, 15, 16, 17, 18, 19, 20, 21], [22]), + ([13, 14, 15, 16, 17, 18, 19, 20, 21, 22], [23]), + ([14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [24]), + ([15, 16, 17, 18, 19, 20, 21, 22, 23, 24], [25]), + ([16, 17, 18, 19, 20, 21, 22, 23, 24, 25], [26]), + ([17, 18, 19, 20, 21, 22, 23, 24, 25, 26], [27]), + ([18, 19, 20, 21, 22, 23, 24, 25, 26, 27], [28]), + ([19, 20, 21, 22, 23, 24, 25, 26, 27, 28], [29]), + ] + x = list(range(30)) + generator = get_rolling_token_windows( + token_list=x, + prefix_token=-100, + max_seq_len=10, + context_len=10, + ) + pred_length = 0 + output = [] + for input_tokens, pred_tokens in generator: + output.extend([(input_tokens, pred_tokens)]) + pred_length += len(pred_tokens) + assert pred_length == len(x) + assert gold == output + + +# noinspection DuplicatedCode +def test_get_rolling_token_windows_v5(): + gold = [ + ([-100, 0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + ( + [9, 10, 11, 12, 13, 14, 15, 16, 17, 18], + [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], + ), + ( + [19, 20, 21, 22, 23, 24, 25, 26, 27, 28], + [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], + ), + ] + x = list(range(30)) + generator = get_rolling_token_windows( + token_list=x, + prefix_token=-100, + max_seq_len=10, + context_len=1, + ) + pred_length = 0 + output = [] + for input_tokens, pred_tokens in generator: + output.extend([(input_tokens, pred_tokens)]) + pred_length += len(pred_tokens) + assert pred_length == len(x) + assert gold == output + + +# noinspection DuplicatedCode +def test_get_rolling_token_windows_v6(): + gold = [ + ([-100, 0], [0, 1]), + ([1, 2], [2, 3]), + ([3, 4], [4, 5]), + ([5, 6], [6, 7]), + ([6, 7], [8]), + ] + x = list(range(9)) + generator = get_rolling_token_windows( + token_list=x, + prefix_token=-100, + max_seq_len=2, + context_len=1, + ) + pred_length = 0 + output = [] + for input_tokens, pred_tokens in generator: + output.extend([(input_tokens, pred_tokens)]) + pred_length += len(pred_tokens) + assert pred_length == len(x) + assert gold == output + + +def test_get_rolling_token_windows_empty(): + generator = get_rolling_token_windows( + token_list=[], + prefix_token=-100, + max_seq_len=2, + context_len=1, + ) + n = 0 + for _ in generator: + n += 1 + assert n == 0 + + +def test_make_disjoint_window(): + assert make_disjoint_window(([1, 2, 3, 4, 5], [2, 3, 4, 5, 6])) == ( + [1], + [2, 3, 4, 5, 6], + ) + assert make_disjoint_window(([1, 2, 3, 4, 5], [4, 5, 6])) == ([1, 2, 3], [4, 5, 6]) + assert make_disjoint_window(([1, 2, 3, 4, 5], [6])) == ([1, 2, 3, 4, 5], [6]) + + +class TestCollator: + def make_generate_sample(self, end=10): + strings = ["x" * i for i in range(1, end + 1)] + gen_kwargs1, gen_kwargs2 = ( + {"temperature": 0}, + {"temperature": 0, "until": ["nn", "\n\n"]}, + ) + args = [ + (string, gen_kwargs1 if i < len(strings) // 2 else gen_kwargs2) + for i, string in enumerate(strings) + ] + + return args + + def make_loglikelihood_sample(self, end=11): + samples = [ + (("x", "x"), list(range(1, total_length + 1))) + for total_length in range(1, end + 1) + ] + return samples + + def make_loglikelihood_sample_group(self, end=11): + a = [(("x", "x"), [1, 2, 3, 4, 5, 6, 7, 8], [x]) for x in range(9)] + b = [ + (("x", "x"), [1, 2, 3, 4, 5, 6, 7, 8], [x, y, z]) + for x, y, z in zip(range(9), range(9, 18), range(18, 27)) + ] + return a + b + + @pytest.mark.parametrize("batch_size, end", [(17, 30), (8, 61), (12, 48), (0, 9)]) + def test_generations(self, batch_size, end): + _collate_gen = lambda x: (-len(x[0]), x[0]) # noqa: E731 + + generation_samples = self.make_generate_sample(int(end)) + gens = Collator(generation_samples, _collate_gen, group_by="gen_kwargs") + chunks_gen = gens.get_batched(n=int(batch_size), batch_fn=None) + output = [] + group_one = end // 2 + group_two = end - end // 2 + is_batch = batch_size != 0 + for chunks in chunks_gen: + # check batching + assert ( + len(chunks) <= batch_size + if is_batch + else len(chunks) in [group_one, group_two] + ) + # check if reorder-er is working correctly + chunk_lengths = [len(chunk[0]) for chunk in chunks] + assert chunk_lengths == sorted(chunk_lengths, reverse=True) + # check if grouping correctly + chunk_to_compare = chunks[0][1] + assert all(x[1] == chunk_to_compare for x in chunks) + for x in chunks: + output.extend([x]) + reordered_output = gens.get_original(output) + # check get original + assert reordered_output == generation_samples + + @pytest.mark.parametrize("batch_size, end", [(17, 30), (8, 61), (12, 48), (0, 3)]) + def test_loglikelihood(self, batch_size, end): + _collate_log = lambda x: (-len(x[1]), tuple(x[1])) # noqa: E731 + loglikelihood_samples = self.make_loglikelihood_sample(int(end)) + loglikelihoods = Collator( + loglikelihood_samples, + _collate_log, + ) + chunks_gen = loglikelihoods.get_batched(n=int(batch_size), batch_fn=None) + output = [] + is_batch = batch_size != 0 + for chunks in chunks_gen: + # check batching + assert len(chunks) <= batch_size if is_batch else len(chunks) == end + # check reorder + chunk_lengths = [len(chunk[1]) for chunk in chunks] + assert chunk_lengths == sorted(chunk_lengths, reverse=True) + for x in chunks: + output.extend([x[1]]) + # check indices + reordered_output = loglikelihoods.get_original(output) + assert reordered_output == [x[1] for x in loglikelihood_samples] + + @pytest.mark.parametrize("batch_size", [17, 8, 12, 0]) + def test_context_grouping(self, batch_size): + def _collate(x): + toks = x[1] + x[2] + return -len(toks), tuple(toks) + + _collate_log = _collate # noqa: E731 + loglikelihood_samples = self.make_loglikelihood_sample_group() + loglikelihoods = Collator( + loglikelihood_samples, + _collate_log, + group_fn=lambda a: a[-2] + a[-1][:-1], + group_by="contexts", + ) + chunks_gen = loglikelihoods.get_batched(n=int(batch_size), batch_fn=None) + output = [] + outputs_ = [] + is_batch = batch_size != 0 + for chunks in chunks_gen: + # check batching + if is_batch: + assert len(chunks) <= batch_size + # check reorder + chunk_lengths = [len(chunk[1]) for chunk in chunks] + assert chunk_lengths == sorted(chunk_lengths, reverse=True) + for x in chunks: + for request_str, cont_toks, logits in loglikelihoods.get_cache( + req_str="".join(x[0]), + cxt_toks=x[1], + cont_toks=x[2], + logits=torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) + .unsqueeze(0) + .unsqueeze(0), + ): + output.extend([x[1]]) + outputs_.extend([cont_toks]) + assert len(output) == len(outputs_) + # check indices + reordered_output = loglikelihoods.get_original(output) + assert reordered_output == [x[1] for x in loglikelihood_samples] + + +def test_aggregate_mean(): + # test weight_by_size is respected + assert ( + aggregate_subtask_metrics([0.3, 0.2, 0.4], [20, 40, 100], weight_by_size=False) + == 0.3 + ) + assert ( + aggregate_subtask_metrics([0.3, 0.2, 0.4], [20, 40, 100], weight_by_size=True) + == 0.3375 + ) + + +@pytest.mark.parametrize( + "samples", + [ + [40 * [1.0] + 60 * [0.0], 30 * [1.0] + 30 * [0.0], 20 * [1.0] + 60 * [0.0]], + [35 * [1.0] + 65 * [0.0], 20 * [1.0] + 20 * [0.0]], + ], +) +def test_aggregate_stderrs(samples): + # check that aggregating subtasks' bootstrap stderrs with our formula + # (using weight_by_size) is ~equiv. + # to just getting bootstrap stderr of the whole set of samples + mean_stderr = stderr_for_metric(metric=mean, bootstrap_iters=100000) + + stderrs = [mean_stderr(subtask) for subtask in samples] + + sizes = [len(subtask) for subtask in samples] + + assert np.allclose( + pooled_sample_stderr(stderrs, sizes), + mean_stderr(list(itertools.chain.from_iterable(samples))), + atol=1.0e-3, + ) diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_only_npi_scope-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_only_npi_scope-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..f1846d3e936ffc75f39f0776024014444a2879bb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_only_npi_scope-v0-loglikelihood @@ -0,0 +1 @@ +fc0be817478c212327050fa297ef61ad214f4847dbff61d4e0fe7914c06a1691 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_passive_2-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_passive_2-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5a4dd092c4a82b59d702c027e16c684c634649e1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_passive_2-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_passive_2": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_passive_2": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_case_1-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_case_1-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..f325c2e3e34f2d07f90e32517bf236339bd63b48 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_case_1-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_principle_A_case_1": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_principle_A_case_1": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_1-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_1-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..6b900d05f4ab0e4143324c919e684900299e9adc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_1-v0-loglikelihood @@ -0,0 +1 @@ +290e7eddacea4ec16989af697f2ee3373fdd9aef4b452bf887184c6e2f6e7d9d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_1-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_1-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9efbffb50fea7f1bca803438e9122ad3c9e953c0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_1-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_principle_A_domain_1": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_principle_A_domain_1": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_2-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_2-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1bda1a2aa9c1eeee68b3ca88f2de38cbb8e5d67b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_2-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_principle_A_domain_2": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_principle_A_domain_2": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_3-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_3-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..c37e9364012f74afc7b5dd493344a3d535a7c611 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_3-v0-loglikelihood @@ -0,0 +1 @@ +38454befedcf1f3f6ef27d3bef9ccfdfb3e94a7ab32d86a63493a920d2d50093 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_3-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_3-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..77c4bf916ab761be87f77618e41abe33d550d7c1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_domain_3-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_principle_A_domain_3": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_principle_A_domain_3": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..f8d1d1f87fb4347f4261920ccb2f12fdda14b7fb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-loglikelihood @@ -0,0 +1 @@ +894efedfd8750d5b8de6157f9b2ed2b51b5290d3a78ea9b041fc62d34e96efbc \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0e7d8db1e2ad279ed4bfcc094253f1fa7723b6ce --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_principle_A_reconstruction": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_principle_A_reconstruction": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_1-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_1-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..16fed715d4effd467e798c56399f0ed4729bd49c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_1-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_regular_plural_subject_verb_agreement_1": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_regular_plural_subject_verb_agreement_1": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_2-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_2-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..4b6525a10ebb7ed53b78dc1f18553ad5896b0691 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_2-v0-loglikelihood @@ -0,0 +1 @@ +f69d9891f59872538962221fccc425b07df7cfbd83cdc546ce83e6b0e9a93f7c \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_2-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_2-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..6d64b97e20bb4688afca5e708f7fc41243ecca14 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_regular_plural_subject_verb_agreement_2-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_regular_plural_subject_verb_agreement_2": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_regular_plural_subject_verb_agreement_2": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_negation_npi_licensor_present-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_negation_npi_licensor_present-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4305bb313c67880a0e4ebf7827c29a2aa2df6d66 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_negation_npi_licensor_present-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_sentential_negation_npi_licensor_present": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_sentential_negation_npi_licensor_present": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_negation_npi_scope-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_negation_npi_scope-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..fcaf915f36cfa6a15cb5cf52f786ad96adb8eecb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_negation_npi_scope-v0-res.json @@ -0,0 +1 @@ +{"results": {"blimp_sentential_negation_npi_scope": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_sentential_negation_npi_scope": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_subject_island-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_subject_island-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..6220172936ccbee00cc7d5420c30893109d366b2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_sentential_subject_island-v0-loglikelihood @@ -0,0 +1 @@ +80f5f98fad26240de2767fe58c4b18d864df41cbfa76f06c84c3fce9f14f4833 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_1-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_1-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b7d2819cb3b61b90bd5efee98e890b486fc02f39 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_1-v0-loglikelihood @@ -0,0 +1 @@ +8a01f6a5ea87a01c0c9b0c7b3bc4de4711bf0ff050976976651182b9ed34a0d4 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_2-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_2-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..4a8317f0b3ac61c3e677a5caa03bd47223a3fb7b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_2-v0-loglikelihood @@ -0,0 +1 @@ +59c20ff0f632cf42afc74ecc682cf92e5e740417b01e6cf9a610a3bc544d2ea5 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_tough_vs_raising_2-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_tough_vs_raising_2-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3b0f9763529ee45a97ab0abdfd18efc9fe991241 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_tough_vs_raising_2-v0-loglikelihood @@ -0,0 +1 @@ +d255a10a34f14d77d9526604a17b0f6747d32f62fc2e3a09e9ab10054535fd45 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_wh_vs_that_no_gap-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_wh_vs_that_no_gap-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..5f40ea63f1b31bfc83b5aa0385051fbcbc3574d8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/blimp_wh_vs_that_no_gap-v0-loglikelihood @@ -0,0 +1 @@ +d1d3e439b2020ef5ed232bfebbcc9634adc5117e9eb61e38fdbbe2c8ea128d54 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/drop-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/drop-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..3b2b697c91962eb160da3950bb22e45889c265e6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/drop-v1-greedy_until @@ -0,0 +1 @@ +a670f911ab2999d72db15f534b22703d19e7837edbda4f9f199ad587f7aae6b2 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_deontology-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_deontology-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..3af24f414a42803984877a710b95c037187984b9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_deontology-v0-res.json @@ -0,0 +1 @@ +{"results": {"ethics_deontology": {"acc": 0.503615127919911, "acc_stderr": 0.008338908432085105, "em": 0.07119021134593993}}, "versions": {"ethics_deontology": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_justice-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_justice-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..cc18a7e67b6f38aaf759bb9073314da42b86f992 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_justice-v0-loglikelihood @@ -0,0 +1 @@ +d7dfc44fea507b5c5c3a8218f79ed8197da8599ebb396d85feb91c25512126b6 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_justice-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_justice-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..39efbc506acfd90b86362185d28d43090aeb7d1c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_justice-v0-res.json @@ -0,0 +1 @@ +{"results": {"ethics_justice": {"acc": 0.49556213017751477, "acc_stderr": 0.009616784279885177, "em": 0.057692307692307696}}, "versions": {"ethics_justice": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_utilitarianism-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_utilitarianism-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..857af346b47d7ce11ee4192b928608a2111776f4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_utilitarianism-v0-res.json @@ -0,0 +1 @@ +{"results": {"ethics_utilitarianism": {"acc": 0.49771214642262895, "acc_stderr": 0.007211546310787838}}, "versions": {"ethics_utilitarianism": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_utilitarianism_original-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_utilitarianism_original-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..bd3ff6c459c5a5739b233dd86c5434f64bbc1b16 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_utilitarianism_original-v0-loglikelihood @@ -0,0 +1 @@ +5b42ba1faf5ece6a6ec9a3976ce79c1fac8df5b98272aab85457188c2142693c \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_virtue-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_virtue-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..48652c4689e2be24972881d0abff497d203ace9a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ethics_virtue-v0-loglikelihood @@ -0,0 +1 @@ +8021db8de46850090ddae6e6ec2d382029c3027b7c69884607503f916d09b709 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/gsm8k-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/gsm8k-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..fb6514a0e750d4e3737cf33766fcc851f79bfa48 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/gsm8k-v0-res.json @@ -0,0 +1 @@ +{"results": {"gsm8k": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"gsm8k": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..9129d834b6037cda3db655064d6c18bb3dccfb54 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa-v0-loglikelihood @@ -0,0 +1 @@ +767ca34d9714edd9fb030ddbcc35a64e5180d1e247b0cb557fbb22fdf971ad1f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..adc093cf62c2f807a0f413d0ecc200879931a5b7 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa-v0-res.json @@ -0,0 +1 @@ +{"results": {"headqa": {"acc": 0.23559445660102116, "acc_norm": 0.25018234865062, "acc_norm_stderr": 0.008272783230806014, "acc_stderr": 0.008105688874297972}}, "versions": {"headqa": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_en-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_en-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..11f07878fb5452ac334eaf0daf276aa8684124f6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_en-v0-loglikelihood @@ -0,0 +1 @@ +09da45119b12a0144e3081f8fb790c2a22af7b9c3aac42f54423d348a711fbf5 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..6ac5a9c0b8e70a47f2c985713a50336c68b11382 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_en-v0-res.json @@ -0,0 +1 @@ +{"results": {"headqa_en": {"acc": 0.23559445660102116, "acc_norm": 0.2447118891320204, "acc_norm_stderr": 0.008211629406841468, "acc_stderr": 0.008105688874297972}}, "versions": {"headqa_en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_es-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_es-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..9129d834b6037cda3db655064d6c18bb3dccfb54 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_es-v0-loglikelihood @@ -0,0 +1 @@ +767ca34d9714edd9fb030ddbcc35a64e5180d1e247b0cb557fbb22fdf971ad1f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_es-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_es-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0964db9bbb8a6b0ca129c3e069151f334558de54 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/headqa_es-v0-res.json @@ -0,0 +1 @@ +{"results": {"headqa_es": {"acc": 0.23559445660102116, "acc_norm": 0.25018234865062, "acc_norm_stderr": 0.008272783230806014, "acc_stderr": 0.008105688874297972}}, "versions": {"headqa_es": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hellaswag-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hellaswag-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..c679a3e311759f4a00707b7454e0e8be4bcdfff0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hellaswag-v0-loglikelihood @@ -0,0 +1 @@ +abb808c97d6529eda6c11067837a132c62d25cba0394d720f80cca6df9f7196e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hellaswag-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hellaswag-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..6be94a640950b2451775fddccbf80060c4a673b0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hellaswag-v0-res.json @@ -0,0 +1 @@ +{"results": {"hellaswag": {"acc": 0.24965146385182235, "acc_norm": 0.24756024696275641, "acc_norm_stderr": 0.004307128573285236, "acc_stderr": 0.004319267432460666}}, "versions": {"hellaswag": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-abstract_algebra-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-abstract_algebra-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d0d0fe872b24d1304c932ffde5546a70b125e100 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-abstract_algebra-v0-loglikelihood @@ -0,0 +1 @@ +e35d1eeb356ac1084d4e9773f028cb3c81ba1c6e5574d598ac4a78aa467cd797 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-abstract_algebra-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-abstract_algebra-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..dc2c9a0d7d4d4a18ee7c8cb0e266a29fa5bd48f6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-abstract_algebra-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-abstract_algebra": {"acc": 0.32, "acc_norm": 0.34, "acc_norm_stderr": 0.04760952285695235, "acc_stderr": 0.04688261722621504}}, "versions": {"hendrycksTest-abstract_algebra": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-anatomy-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-anatomy-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a7ae5fa705e58cf0e7c06ca0fe84a186d24b506f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-anatomy-v0-loglikelihood @@ -0,0 +1 @@ +bf05e04ed8cf61cf3aad294ed3f5a16137775ffdd20f1b129022ddffc1251768 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-anatomy-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-anatomy-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..67bc2e7be6de4ba9d6b9aa40c0d45cd60d7d506b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-anatomy-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-anatomy": {"acc": 0.2222222222222222, "acc_norm": 0.23703703703703705, "acc_norm_stderr": 0.03673731683969506, "acc_stderr": 0.0359144408419697}}, "versions": {"hendrycksTest-anatomy": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-astronomy-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-astronomy-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..8ecb637cfe4eaf6d3bbca863c7bab6188b85425b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-astronomy-v0-loglikelihood @@ -0,0 +1 @@ +bed1e47127cc2893c6aef63b9a0909cca31aa351a703da2a166b01cae03c3311 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-astronomy-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-astronomy-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..d3626ccf80f233702478886fffeede1f587ad2fb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-astronomy-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-astronomy": {"acc": 0.2565789473684211, "acc_norm": 0.29605263157894735, "acc_norm_stderr": 0.03715062154998904, "acc_stderr": 0.0355418036802569}}, "versions": {"hendrycksTest-astronomy": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-business_ethics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-business_ethics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a0f8b7c09b3b6307123f1328c51c1dcfb797aed2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-business_ethics-v0-loglikelihood @@ -0,0 +1 @@ +b3b27e9dbad587377d3c8cab1072782de883e245da93a563bd8b3099017b1fc0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-business_ethics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-business_ethics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..dcc5116204283941b74dfea97e3a1ce5edd9dc27 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-business_ethics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-business_ethics": {"acc": 0.29, "acc_norm": 0.27, "acc_norm_stderr": 0.044619604333847394, "acc_stderr": 0.045604802157206845}}, "versions": {"hendrycksTest-business_ethics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-clinical_knowledge-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-clinical_knowledge-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..86f54245d557e0091d1166b7ffb2029520e566e9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-clinical_knowledge-v0-loglikelihood @@ -0,0 +1 @@ +fbcb7ce507e0675d811e71e10a67c8d05a6605e29036f46776e04a6588cefbda \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-clinical_knowledge-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-clinical_knowledge-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..596bb28a93f52c857b6a39d416114c12c7ea9147 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-clinical_knowledge-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-clinical_knowledge": {"acc": 0.23773584905660378, "acc_norm": 0.27169811320754716, "acc_norm_stderr": 0.027377706624670713, "acc_stderr": 0.02619980880756191}}, "versions": {"hendrycksTest-clinical_knowledge": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_biology-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_biology-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..7f665ef4a1bd06ecfd30d999ae6880c00ba849cf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_biology-v0-loglikelihood @@ -0,0 +1 @@ +c29e4e67ff91af29b9434884874414d1b1b32ccc32903c6b1639469b19907419 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_biology-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_biology-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..6705b9cad27c7f1eb647b513861646faaccad584 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_biology-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-college_biology": {"acc": 0.24305555555555555, "acc_norm": 0.2361111111111111, "acc_norm_stderr": 0.03551446610810826, "acc_stderr": 0.03586879280080341}}, "versions": {"hendrycksTest-college_biology": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_chemistry-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_chemistry-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..52a255e82a35b8d084459e72140f30f26ef8c57f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_chemistry-v0-loglikelihood @@ -0,0 +1 @@ +044752b21540db95118b8cbe7e75c4c9b8758e27df56543deaeadec7f749a28d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_chemistry-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_chemistry-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4dc95a151ac2da73b3c5eb23e3fe24a7ccc8024d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_chemistry-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-college_chemistry": {"acc": 0.28, "acc_norm": 0.26, "acc_norm_stderr": 0.04408440022768078, "acc_stderr": 0.04512608598542127}}, "versions": {"hendrycksTest-college_chemistry": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_computer_science-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_computer_science-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..695bc8c31592a4c33d70d5d07a8c5b523d9bd3cc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_computer_science-v0-loglikelihood @@ -0,0 +1 @@ +4ea26ad780290429ac5a3317559c154848d662bd40532c966458ba6f2a32d0a3 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_computer_science-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_computer_science-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..aea595c09f5baf6d21867c47fd5e42152244f555 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_computer_science-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-college_computer_science": {"acc": 0.22, "acc_norm": 0.24, "acc_norm_stderr": 0.04292346959909282, "acc_stderr": 0.041633319989322695}}, "versions": {"hendrycksTest-college_computer_science": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_mathematics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_mathematics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a840b6b6420053c343787f08d8d723ab5ba5c1d3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_mathematics-v0-loglikelihood @@ -0,0 +1 @@ +e9fe80752686527281f834d2397875b4580581434b94799f9de6aaa450bd73ff \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_mathematics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_mathematics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..766b3388ed88d61e2c17ed2a35110879160c5f7f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_mathematics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-college_mathematics": {"acc": 0.18, "acc_norm": 0.2, "acc_norm_stderr": 0.04020151261036844, "acc_stderr": 0.038612291966536955}}, "versions": {"hendrycksTest-college_mathematics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_medicine-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_medicine-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..2fb96497d12f9b72dbbd38f0d64aa75615bfe14b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_medicine-v0-loglikelihood @@ -0,0 +1 @@ +dd6e0a9be1407890e9f8cd4434fb6aa4752ab3d2473837fd465ad99f60ad685e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_medicine-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_medicine-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..524552c9bb99335a9a7bee73076bc633b7eb10e3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_medicine-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-college_medicine": {"acc": 0.27167630057803466, "acc_norm": 0.2543352601156069, "acc_norm_stderr": 0.0332055644308557, "acc_stderr": 0.03391750322321659}}, "versions": {"hendrycksTest-college_medicine": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_physics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_physics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..7c2e2f4bf73266d532c7514c98defcba0133f231 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_physics-v0-loglikelihood @@ -0,0 +1 @@ +704a7671ef981fb95594782bc446dd632e87ebdbe89436a0603b714fb5786c75 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_physics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_physics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..97e56f2ae62e6b0012d49c6a7a55614a6d6eaf58 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-college_physics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-college_physics": {"acc": 0.23529411764705882, "acc_norm": 0.23529411764705882, "acc_norm_stderr": 0.04220773659171453, "acc_stderr": 0.04220773659171452}}, "versions": {"hendrycksTest-college_physics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-computer_security-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-computer_security-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d4c0ee2d78364c0275d984a4ef43cfcedbaf55ed --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-computer_security-v0-loglikelihood @@ -0,0 +1 @@ +a8a1892d1906cc3e7ffd321043f0a60f3b8b69ef76e5c6ff03c6ea41dc87d0cb \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-computer_security-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-computer_security-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..60f02eba9cb04602d8b67d67269d8b82e0930721 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-computer_security-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-computer_security": {"acc": 0.24, "acc_norm": 0.27, "acc_norm_stderr": 0.044619604333847394, "acc_stderr": 0.042923469599092816}}, "versions": {"hendrycksTest-computer_security": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-conceptual_physics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-conceptual_physics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..05c4db0e2290998cb650c11373f0947c3be8f297 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-conceptual_physics-v0-loglikelihood @@ -0,0 +1 @@ +622f191ccfc7a597d99f39897ebe3f95a9ddce0e662fcfb411aa554b289bb355 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-conceptual_physics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-conceptual_physics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1388bcdcd9a7283decbf3680283a2cc4cfc7cfde --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-conceptual_physics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-conceptual_physics": {"acc": 0.2680851063829787, "acc_norm": 0.2553191489361702, "acc_norm_stderr": 0.028504856470514185, "acc_stderr": 0.028957342788342347}}, "versions": {"hendrycksTest-conceptual_physics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-econometrics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-econometrics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ed3332eddaf041c82908352c43cf8d9187b8f381 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-econometrics-v0-loglikelihood @@ -0,0 +1 @@ +cde76ba2c7382b4876e17136c94f52aca2774e50342ab757b2a2d18da370dcb6 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-econometrics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-econometrics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4656fac3c3026ec7e137ce8f49e4796fefe5e24f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-econometrics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-econometrics": {"acc": 0.24561403508771928, "acc_norm": 0.24561403508771928, "acc_norm_stderr": 0.04049339297748142, "acc_stderr": 0.040493392977481425}}, "versions": {"hendrycksTest-econometrics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-electrical_engineering-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-electrical_engineering-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..9c9e72efdf98ed9afb4881647929246433e1f857 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-electrical_engineering-v0-loglikelihood @@ -0,0 +1 @@ +b9b5d8b8bb02696302ec6bc2a99bf987a5504d3bae0e529d2c8f263538c97518 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-electrical_engineering-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-electrical_engineering-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..13b76c1d5f94218128b2038d55bd300faf66ff44 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-electrical_engineering-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-electrical_engineering": {"acc": 0.2689655172413793, "acc_norm": 0.2827586206896552, "acc_norm_stderr": 0.037528339580033376, "acc_stderr": 0.036951833116502325}}, "versions": {"hendrycksTest-electrical_engineering": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-elementary_mathematics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-elementary_mathematics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..e281f72feb428451f27dbaba80408c468ef51bce --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-elementary_mathematics-v0-loglikelihood @@ -0,0 +1 @@ +6b21f5cd5606268421a667152ec989424b66905c02adbab8d4ff6bb9d21b77d1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-elementary_mathematics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-elementary_mathematics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..84cd983ee9d33f831ee397ffd8b11990b70a4b60 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-elementary_mathematics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-elementary_mathematics": {"acc": 0.2724867724867725, "acc_norm": 0.2830687830687831, "acc_norm_stderr": 0.023201392938194978, "acc_stderr": 0.022930973071633345}}, "versions": {"hendrycksTest-elementary_mathematics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-formal_logic-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-formal_logic-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ef6bec3f70adb9b8df43583cf76e6cd865831b0b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-formal_logic-v0-loglikelihood @@ -0,0 +1 @@ +c0d0f0c008a5f3faf2f6f4268d87bbc09c40bb66ae08cf38eea0bf2e519c5a59 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-formal_logic-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-formal_logic-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..acde01d4d7d45333322eaa4a07edf42ec414d08c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-formal_logic-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-formal_logic": {"acc": 0.25396825396825395, "acc_norm": 0.2698412698412698, "acc_norm_stderr": 0.03970158273235172, "acc_stderr": 0.03893259610604674}}, "versions": {"hendrycksTest-formal_logic": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-global_facts-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-global_facts-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a4751fdbfad7b614f9ec059a78130426e1d8a39c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-global_facts-v0-loglikelihood @@ -0,0 +1 @@ +9fdc85240b8170839278b1e883ee0868611d84dce202cb8aa037c841ec76d089 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-global_facts-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-global_facts-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..d2fff47bcbaaaead17eceef0ca09cd45014c5aac --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-global_facts-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-global_facts": {"acc": 0.23, "acc_norm": 0.23, "acc_norm_stderr": 0.04229525846816507, "acc_stderr": 0.04229525846816507}}, "versions": {"hendrycksTest-global_facts": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_biology-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_biology-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..1e2c01e2b19082144373a13ee25e3e68bf8df588 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_biology-v0-loglikelihood @@ -0,0 +1 @@ +d4dc051f37a49dc75c218741e87bc826fd44f31ee1309b55e0f33bd191c1bc78 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_biology-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_biology-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a666d9ce9c969f808ea84909730cee046ccc6294 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_biology-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_biology": {"acc": 0.23870967741935484, "acc_norm": 0.2709677419354839, "acc_norm_stderr": 0.025284416114900152, "acc_stderr": 0.024251071262208834}}, "versions": {"hendrycksTest-high_school_biology": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_chemistry-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_chemistry-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d0ca97d6a58d8dae225d36636ef21b0fd1e50fdf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_chemistry-v0-loglikelihood @@ -0,0 +1 @@ +f4f338e45415c4b5ee7f1d249155bcd910c8401bd1436760a5ec61cb6bb211b6 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_chemistry-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_chemistry-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2d81594963cefe41f139a813fcdc16c0f247f9ed --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_chemistry-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_chemistry": {"acc": 0.2857142857142857, "acc_norm": 0.2660098522167488, "acc_norm_stderr": 0.031089826002937523, "acc_stderr": 0.031785297106427496}}, "versions": {"hendrycksTest-high_school_chemistry": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_computer_science-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_computer_science-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a421564657975a25dedfd1c8cf38ef0e0ea4df9c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_computer_science-v0-loglikelihood @@ -0,0 +1 @@ +870d5a6300c527077aaf6baa3e750e75fa840b41657cf82549f39b768b14862d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_computer_science-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_computer_science-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..bbc2dacf5f5ac0b14327f0637b4b1aabea7a6167 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_computer_science-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_computer_science": {"acc": 0.2, "acc_norm": 0.22, "acc_norm_stderr": 0.04163331998932269, "acc_stderr": 0.04020151261036845}}, "versions": {"hendrycksTest-high_school_computer_science": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..eec5858ef9a22ba66ee0627646b5ce98f2b0326d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-loglikelihood @@ -0,0 +1 @@ +d8070e113be9d420fef5578cb69c70df4ea5118f9b18553023fd9efd5ff0b7f4 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b5cea9cbe310db37d488984f3ff6aa57921576d9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_european_history": {"acc": 0.23636363636363636, "acc_norm": 0.24242424242424243, "acc_norm_stderr": 0.03346409881055953, "acc_stderr": 0.033175059300091805}}, "versions": {"hendrycksTest-high_school_european_history": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_geography-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_geography-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ac80d178809ddbacc3aeb8ff368d8a68605a6430 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_geography-v0-loglikelihood @@ -0,0 +1 @@ +add45970ea3865be7c7a31f788a835949f6937ac73f699b122ca56a3431e95f8 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_geography-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_geography-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0fb76aa9ba10e63a931ec3707ac6d9f3d84292aa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_geography-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_geography": {"acc": 0.2474747474747475, "acc_norm": 0.2777777777777778, "acc_norm_stderr": 0.03191178226713547, "acc_stderr": 0.03074630074212452}}, "versions": {"hendrycksTest-high_school_geography": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_government_and_politics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_government_and_politics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..12ea726b4ba81f264017a7fd71d18a6ac318b0ab --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_government_and_politics-v0-loglikelihood @@ -0,0 +1 @@ +11f40d8f48ba5cd739e21d54c3c04d3761f81df5cb7ddd77df868d24ced44b49 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_government_and_politics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_government_and_politics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..16cc02ff0a897dda3a6c6dc97e9b7815ea120fc2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_government_and_politics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_government_and_politics": {"acc": 0.24352331606217617, "acc_norm": 0.23834196891191708, "acc_norm_stderr": 0.03074890536390988, "acc_stderr": 0.030975436386845436}}, "versions": {"hendrycksTest-high_school_government_and_politics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_macroeconomics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_macroeconomics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..c0106d373dcf6136b147bb3787fed6c9c8a3da8f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_macroeconomics-v0-loglikelihood @@ -0,0 +1 @@ +ce4faae2fb6628caa48f6fc74cbc848880db49e6ff51079392778a2322bcefef \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_macroeconomics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_macroeconomics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..fb6835039c9d68b5cf5d52244a349c1b8a964c5c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_macroeconomics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_macroeconomics": {"acc": 0.2230769230769231, "acc_norm": 0.22564102564102564, "acc_norm_stderr": 0.021193632525148522, "acc_stderr": 0.021107730127244}}, "versions": {"hendrycksTest-high_school_macroeconomics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_mathematics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_mathematics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..dc86769fa93781e03ca8f7e7b3493b39338bcdaa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_mathematics-v0-loglikelihood @@ -0,0 +1 @@ +ab368d16fc4648ad27940f71abd266366663f51db612f732a0b9b0eea28de9f8 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_mathematics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_mathematics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..cb3a3ec0688cdc4905ffad6e17c91d59c9330572 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_mathematics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_mathematics": {"acc": 0.22592592592592592, "acc_norm": 0.24814814814814815, "acc_norm_stderr": 0.0263357394040558, "acc_stderr": 0.025497532639609553}}, "versions": {"hendrycksTest-high_school_mathematics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..37962bf9fb93bc8f49fa83af34c30ac0ef49df09 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-loglikelihood @@ -0,0 +1 @@ +513b998585ebc1ebdefca6435b7c84fd73dc36fc80321a22503467f04efed23e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..cf698d181c95ef88e774204df6f92622116d690c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_microeconomics": {"acc": 0.24369747899159663, "acc_norm": 0.22268907563025211, "acc_norm_stderr": 0.027025433498882378, "acc_stderr": 0.027886828078380558}}, "versions": {"hendrycksTest-high_school_microeconomics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_physics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_physics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..49a780bc97953db32716ccc580390c5d21cfc252 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_physics-v0-loglikelihood @@ -0,0 +1 @@ +dae59e82d3d4d8dec82239d9620b72cc47bb6efbe2f1c2f9b9d23e849c9c5e32 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_physics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_physics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b6b3bb9d012756280cf8a0ba68d4011fe9089e39 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_physics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_physics": {"acc": 0.2582781456953642, "acc_norm": 0.271523178807947, "acc_norm_stderr": 0.03631329803969653, "acc_stderr": 0.035737053147634576}}, "versions": {"hendrycksTest-high_school_physics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_psychology-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_psychology-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..0f39ddfde7066ac8c577156336644c35a543afbb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_psychology-v0-loglikelihood @@ -0,0 +1 @@ +0e4c8d13806d3696167e40544d2d114c557c10c74bc61fcb9c51bbfced0266ef \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_psychology-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_psychology-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..42b781149bff323130b4491463168f03bdfbb9a9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_psychology-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_psychology": {"acc": 0.24587155963302754, "acc_norm": 0.23302752293577983, "acc_norm_stderr": 0.018125669180861493, "acc_stderr": 0.018461940968708436}}, "versions": {"hendrycksTest-high_school_psychology": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_statistics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_statistics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..8a915ef7fc0ab9a7c290867450265a7cadd40494 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_statistics-v0-loglikelihood @@ -0,0 +1 @@ +33d1d6eaaa2c3a944bf49d3f220a4efc328d7c3b3465b7cec40ae36d8984b75f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_statistics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_statistics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4c6a21d7dac4cd7b6fa217e8bebf34d959554a7a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_statistics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_statistics": {"acc": 0.2962962962962963, "acc_norm": 0.3055555555555556, "acc_norm_stderr": 0.03141554629402544, "acc_stderr": 0.03114144782353604}}, "versions": {"hendrycksTest-high_school_statistics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_us_history-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_us_history-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..e05b91503e0a2c2c8bb8ef34af16e87c902c31f9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_us_history-v0-loglikelihood @@ -0,0 +1 @@ +8c65c1a28330dd001d395ac11f1bb80c3b33f5935f503e74067aef6e9e1d9d9b \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_us_history-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_us_history-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5b7a76909c08ab9c47c5e1eb6c06945e990fb639 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_us_history-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_us_history": {"acc": 0.29901960784313725, "acc_norm": 0.28431372549019607, "acc_norm_stderr": 0.03166009679399814, "acc_stderr": 0.03213325717373618}}, "versions": {"hendrycksTest-high_school_us_history": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_world_history-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_world_history-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..228dfe072cd02f94bced495f271c5cc108850719 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_world_history-v0-loglikelihood @@ -0,0 +1 @@ +1c8b994bd9a63ec874fc8d0e3a27077118b7adc472306b2fd6c55635a78b9d52 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_world_history-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_world_history-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ca1bf95b9d2d37c2b9cbe75efd7f1e3fd88ecdcf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_world_history-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-high_school_world_history": {"acc": 0.23628691983122363, "acc_norm": 0.24472573839662448, "acc_norm_stderr": 0.02798569938703642, "acc_stderr": 0.027652153144159263}}, "versions": {"hendrycksTest-high_school_world_history": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_aging-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_aging-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d34fa529800590ecc8e199fdb9d141c99b8c6876 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_aging-v0-loglikelihood @@ -0,0 +1 @@ +0880b3a78f8d7b17ffc612031427b9085367cf65dabe2a68c4b64e3171d17e88 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_aging-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_aging-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..061678f2e4f30402e1c44da7c4a23cae0e57bedf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_aging-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-human_aging": {"acc": 0.21524663677130046, "acc_norm": 0.17937219730941703, "acc_norm_stderr": 0.025749819569192804, "acc_stderr": 0.02758406660220827}}, "versions": {"hendrycksTest-human_aging": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_sexuality-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_sexuality-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b3d3ae438c1fc59930d1d4ba053d73c38b6d9c07 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_sexuality-v0-loglikelihood @@ -0,0 +1 @@ +4b07922fa1d549b655c21440b13d869263ce7dd9771d8147c450f11c91d26c10 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_sexuality-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_sexuality-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..091d7352ce1b260f6acbd1338b7d54c5716d23ce --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-human_sexuality-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-human_sexuality": {"acc": 0.22137404580152673, "acc_norm": 0.22900763358778625, "acc_norm_stderr": 0.036853466317118506, "acc_stderr": 0.0364129708131373}}, "versions": {"hendrycksTest-human_sexuality": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-international_law-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-international_law-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..2b6aa8d605765b06a262877dec34cd156d0a66f9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-international_law-v0-loglikelihood @@ -0,0 +1 @@ +ea9b2cefd27959db564168f6ad1169a5eaa012fc5a5d5b8faf9e34d94e335dc1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-international_law-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-international_law-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..bd4edd2394a4ccaf2d75c578a9f45ad614657dd8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-international_law-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-international_law": {"acc": 0.2396694214876033, "acc_norm": 0.3140495867768595, "acc_norm_stderr": 0.042369647530410164, "acc_stderr": 0.03896878985070417}}, "versions": {"hendrycksTest-international_law": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-jurisprudence-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-jurisprudence-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3d55d21e0294d78ebb728920d0651ccf6f9150b7 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-jurisprudence-v0-loglikelihood @@ -0,0 +1 @@ +cac440189f1ec778e82f4975d88b74689553ecc5116aaa7f76587a50c1a610e0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-jurisprudence-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-jurisprudence-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4ef181974956e3f899121ac46dc5e192231d1a65 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-jurisprudence-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-jurisprudence": {"acc": 0.25, "acc_norm": 0.3148148148148148, "acc_norm_stderr": 0.04489931073591312, "acc_stderr": 0.04186091791394607}}, "versions": {"hendrycksTest-jurisprudence": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-logical_fallacies-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-logical_fallacies-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a5807b5831206a8cb29b2e99c02c7c6025dd6f25 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-logical_fallacies-v0-loglikelihood @@ -0,0 +1 @@ +2e9449dd803f9e2334dc562d9f04031fd013ed36b883b44ab500533a5dbbface \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-logical_fallacies-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-logical_fallacies-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..c5cf5cb467d80051cea569ab30ccc20d697e1e57 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-logical_fallacies-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-logical_fallacies": {"acc": 0.20245398773006135, "acc_norm": 0.2147239263803681, "acc_norm_stderr": 0.03226219377286774, "acc_stderr": 0.03157065078911902}}, "versions": {"hendrycksTest-logical_fallacies": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..53e498ddd480dfaf3994eba4069ead8a28694784 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-loglikelihood @@ -0,0 +1 @@ +7a7138821a66ef946e427b40344cf7f1a916a2926995a85ef731a3bee40cb7ce \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..26be724f2426d0a7b204b2f4dee509597e85ab41 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-machine_learning": {"acc": 0.23214285714285715, "acc_norm": 0.22321428571428573, "acc_norm_stderr": 0.039523019677025116, "acc_stderr": 0.04007341809755806}}, "versions": {"hendrycksTest-machine_learning": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-management-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-management-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..571873985758661a0feed74e164f606318e58d8c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-management-v0-loglikelihood @@ -0,0 +1 @@ +355489f4bd176ab84db5ef4c03d56ddeeeb1b0ad69827122b2d800e1cdc7e5f0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-management-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-management-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..7a84623fabf793b7748d34c18f4c358649f31a97 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-management-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-management": {"acc": 0.24271844660194175, "acc_norm": 0.2621359223300971, "acc_norm_stderr": 0.043546310772605956, "acc_stderr": 0.04245022486384495}}, "versions": {"hendrycksTest-management": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-marketing-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-marketing-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..1d241a97733c081a3f00280cfbedc411c0570001 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-marketing-v0-loglikelihood @@ -0,0 +1 @@ +b4fa0681fe54671a80509779d4338d744097a7206687f62977df7145dfa74a66 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-marketing-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-marketing-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2cc7a93f1c3c2b4747d4ce739ffbcd522fc50224 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-marketing-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-marketing": {"acc": 0.2863247863247863, "acc_norm": 0.2905982905982906, "acc_norm_stderr": 0.029745048572674043, "acc_stderr": 0.029614323690456648}}, "versions": {"hendrycksTest-marketing": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-medical_genetics-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-medical_genetics-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..48d49de8399fba6cfb50dd98d3cbcf8d39388ab2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-medical_genetics-v0-loglikelihood @@ -0,0 +1 @@ +db6141246889a19dd3f6b9109f314d49c1a70f7a98795858804378b095c4a2fe \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-medical_genetics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-medical_genetics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..eac53bcf4a7610934b697d6d19f53ecdf5d4a4ad --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-medical_genetics-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-medical_genetics": {"acc": 0.27, "acc_norm": 0.29, "acc_norm_stderr": 0.04560480215720684, "acc_stderr": 0.0446196043338474}}, "versions": {"hendrycksTest-medical_genetics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-miscellaneous-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-miscellaneous-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b09e99721b8ec71dc85c7ed0798d55a6e0274860 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-miscellaneous-v0-loglikelihood @@ -0,0 +1 @@ +972dd88dbbaf09d14766e243cfc233425e7c01a26dbc61bdb9eeefa788822331 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-miscellaneous-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-miscellaneous-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5c7859eb3a80a849deee7d67d37f71a84c8eeaf6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-miscellaneous-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-miscellaneous": {"acc": 0.23499361430395913, "acc_norm": 0.2515964240102171, "acc_norm_stderr": 0.015517322365529622, "acc_stderr": 0.015162024152278445}}, "versions": {"hendrycksTest-miscellaneous": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_disputes-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_disputes-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..953fc3be48759378aea33eb767cb7367514a5de9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_disputes-v0-loglikelihood @@ -0,0 +1 @@ +d6ef028022c02b69d1516973e08bebaa14d8debcf2589a2bb124823178202d20 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_disputes-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_disputes-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..26ea1c2a75ccfb96af880ee30eef11520e9ea39c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_disputes-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-moral_disputes": {"acc": 0.24855491329479767, "acc_norm": 0.27167630057803466, "acc_norm_stderr": 0.023948512905468365, "acc_stderr": 0.023267528432100174}}, "versions": {"hendrycksTest-moral_disputes": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_scenarios-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_scenarios-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d5ea0d8156ae4efaa0f7568ae8fd3a8ed3992d37 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_scenarios-v0-loglikelihood @@ -0,0 +1 @@ +a8e1882e77728b53c8b86312254d08320d8363fb606d746a8dd145b812f62cf5 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_scenarios-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_scenarios-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..62ec15971237e04f6c883c7369bbb50888494830 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-moral_scenarios-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-moral_scenarios": {"acc": 0.2547486033519553, "acc_norm": 0.25251396648044694, "acc_norm_stderr": 0.014530330201468654, "acc_stderr": 0.014572650383409158}}, "versions": {"hendrycksTest-moral_scenarios": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-nutrition-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-nutrition-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..2716bebe69e1c3884ba2e88056c87c5a5268b53e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-nutrition-v0-loglikelihood @@ -0,0 +1 @@ +19e49d218f55ed5ec4bd1a6cd3f3388c6f620b81484e7abe8b298e5481c3044d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-nutrition-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-nutrition-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..e2838f880581f7cf743d83ba99a26827c18a09de --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-nutrition-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-nutrition": {"acc": 0.24509803921568626, "acc_norm": 0.28104575163398693, "acc_norm_stderr": 0.025738854797818723, "acc_stderr": 0.02463004897982476}}, "versions": {"hendrycksTest-nutrition": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-philosophy-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-philosophy-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3ea8ef0a0e3ddf5cc42c6305e1885e163399f38c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-philosophy-v0-loglikelihood @@ -0,0 +1 @@ +a419204da36c2b7a70fa8909a3a804260cc3283c7e07917534dfb76216c77f46 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-philosophy-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-philosophy-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ec9c1e79c117c88246fa596ca90821025c9786af --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-philosophy-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-philosophy": {"acc": 0.26366559485530544, "acc_norm": 0.2733118971061093, "acc_norm_stderr": 0.02531176597542612, "acc_stderr": 0.02502553850053234}}, "versions": {"hendrycksTest-philosophy": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-prehistory-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-prehistory-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..4c01847ef594713fee284436be6fe8d20d602554 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-prehistory-v0-loglikelihood @@ -0,0 +1 @@ +6983c560a562749f4f702249a3a6ae51fa495acc0643a980bf2cf52c6c5d4b95 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-prehistory-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-prehistory-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..e0163dd555e6c510aa24c5da5ad187ef52ed7c4d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-prehistory-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-prehistory": {"acc": 0.2623456790123457, "acc_norm": 0.26851851851851855, "acc_norm_stderr": 0.024659685185967277, "acc_stderr": 0.02447722285613511}}, "versions": {"hendrycksTest-prehistory": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..fe5997427ef5df8be6d52709189b7baa8a410df9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-loglikelihood @@ -0,0 +1 @@ +847418f7b22cd9b499e95fd73c40a2fbc40076895280cc2c560199c0c4c4f433 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b665d57e234aa5b9f67f85da689bba952f930914 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-professional_accounting": {"acc": 0.2553191489361702, "acc_norm": 0.26595744680851063, "acc_norm_stderr": 0.026358065698880582, "acc_stderr": 0.026011992930902006}}, "versions": {"hendrycksTest-professional_accounting": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_law-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_law-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..23fbfcf78e79595a64037311668042a1ec7f637f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_law-v0-loglikelihood @@ -0,0 +1 @@ +c38c9d5d84eeb7a5f3c4a34d6e70d7e15847b3c38f26e4b119c982bb935e118f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_law-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_law-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..f15a9b34ff26e1382d04b4d6e41fdae6085b30c8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_law-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-professional_law": {"acc": 0.2561929595827901, "acc_norm": 0.2470664928292047, "acc_norm_stderr": 0.011015752255279352, "acc_stderr": 0.011149173153110582}}, "versions": {"hendrycksTest-professional_law": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_medicine-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_medicine-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..cc3c3be8c6c09ffccdf7dbfd318ea3928c87a769 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_medicine-v0-loglikelihood @@ -0,0 +1 @@ +7a30599858398169cde61430c18efdd7fb4dcd09c34aa9baba70f0f8cf17a9f1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_medicine-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_medicine-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..801ea2d224b7f4699c3a3defd7cde023e777a29e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_medicine-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-professional_medicine": {"acc": 0.23161764705882354, "acc_norm": 0.2536764705882353, "acc_norm_stderr": 0.02643132987078953, "acc_stderr": 0.025626533803777562}}, "versions": {"hendrycksTest-professional_medicine": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_psychology-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_psychology-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..9865854da311057c18f8a2571eedac2d02608df5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_psychology-v0-loglikelihood @@ -0,0 +1 @@ +92a5fad6e9ec700f84946faeccd399dda3569fb71837c9fb0c5c87f5ec29c43e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_psychology-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_psychology-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..c6b33f4be16f9bc1ed04502ed0f1c121c3a9d1be --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-professional_psychology-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-professional_psychology": {"acc": 0.27124183006535946, "acc_norm": 0.2826797385620915, "acc_norm_stderr": 0.01821726955205344, "acc_stderr": 0.01798661530403031}}, "versions": {"hendrycksTest-professional_psychology": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-public_relations-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-public_relations-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..8f7b30ba8823a0a0d8fc94f69ef64d362835e0db --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-public_relations-v0-loglikelihood @@ -0,0 +1 @@ +ab70f500cf24e876f6ae6bdc27525a1d6074fa9b6ea97770255d9fc2559b36ff \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-public_relations-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-public_relations-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9ba711cca75cfa5f22bb2dc52e68839ac3820b88 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-public_relations-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-public_relations": {"acc": 0.3090909090909091, "acc_norm": 0.2636363636363636, "acc_norm_stderr": 0.04220224692971987, "acc_stderr": 0.044262946482000985}}, "versions": {"hendrycksTest-public_relations": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-security_studies-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-security_studies-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..6aa9b5ec005a326616b812b816b95329ad9349a2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-security_studies-v0-loglikelihood @@ -0,0 +1 @@ +92dfffe2acf3278256486d3e1cf1edb5a739ad0a54c0f9c67695f7a411ed5f76 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-security_studies-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-security_studies-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2c9de8886a29e0479074513470594c9266c5d0ac --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-security_studies-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-security_studies": {"acc": 0.2979591836734694, "acc_norm": 0.2693877551020408, "acc_norm_stderr": 0.02840125202902294, "acc_stderr": 0.029279567411065674}}, "versions": {"hendrycksTest-security_studies": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-sociology-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-sociology-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d3f581c9f256191c2c0403a582fd72696150b34a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-sociology-v0-loglikelihood @@ -0,0 +1 @@ +f99a3caece11169f2a5cc951001f92027104afd25d29b2a399883bd4bf118605 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-sociology-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-sociology-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..8711cf195e4fa92606a47c1b7c701643f0ef483e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-sociology-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-sociology": {"acc": 0.23383084577114427, "acc_norm": 0.24875621890547264, "acc_norm_stderr": 0.030567675938916707, "acc_stderr": 0.02992941540834838}}, "versions": {"hendrycksTest-sociology": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-us_foreign_policy-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-us_foreign_policy-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..eed85dbaf98e67cc5cd0876bc5f73f3f9fb186fb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-us_foreign_policy-v0-loglikelihood @@ -0,0 +1 @@ +a1a338d0083a21054f74d36a296d6bd8e2e457327c0fd630bebcc61ed758044d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-us_foreign_policy-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-us_foreign_policy-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1077380de88cb9ce23894ce31fbbeceea90f2079 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-us_foreign_policy-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-us_foreign_policy": {"acc": 0.2, "acc_norm": 0.24, "acc_norm_stderr": 0.04292346959909283, "acc_stderr": 0.040201512610368445}}, "versions": {"hendrycksTest-us_foreign_policy": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-virology-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-virology-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3555c2c5351eb369bf0dc9cfedf93f0bbc3de7b4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-virology-v0-loglikelihood @@ -0,0 +1 @@ +0ffa491f7bad2abbb64ecd752a295729167599b3815238cab0ecf4cb08bba9b6 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-virology-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-virology-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0004b194049a5dce0266002b4a19882fbb8c6bfa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-virology-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-virology": {"acc": 0.27710843373493976, "acc_norm": 0.2710843373493976, "acc_norm_stderr": 0.03460579907553027, "acc_stderr": 0.034843315926805875}}, "versions": {"hendrycksTest-virology": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-world_religions-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-world_religions-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..118c9b7435cc72387017ba1811d4bb62a16846b5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-world_religions-v0-loglikelihood @@ -0,0 +1 @@ +97a0f68ba30ea3a6ef1db1a2925c964b09ecc54455a0a930da083e52677815bd \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-world_religions-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-world_religions-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0fff75a7eaf2e0773a7e3dcda446f59a59dad878 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/hendrycksTest-world_religions-v0-res.json @@ -0,0 +1 @@ +{"results": {"hendrycksTest-world_religions": {"acc": 0.21637426900584794, "acc_norm": 0.22807017543859648, "acc_norm_stderr": 0.03218093795602357, "acc_stderr": 0.03158149539338734}}, "versions": {"hendrycksTest-world_religions": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-ar-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-ar-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..82921d1db066020f53d61c21d46498a512144b37 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-ar-en-v0-greedy_until @@ -0,0 +1 @@ +e94d310de91fad7ce36f4cf3305552020221482c5588f2efcefaa019893504f1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-ar-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-ar-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0f414a928b62a8f8eefc939d693c944dd2521733 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-ar-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"iwslt17-ar-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.015049895477752772, "chrf_stderr": 0.0002940315671893584, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"iwslt17-ar-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-en-ar-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-en-ar-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..fc59546576857b7f52dd4bfbdfc661c8ce871a6a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-en-ar-v0-greedy_until @@ -0,0 +1 @@ +b20adbcd2c6d135e28600b427113532c5df624cb3a90e8c5e48715c09a3a38fa \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-en-ar-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-en-ar-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a22fa9036c790cb48e142bd05a59da7824a9c83f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/iwslt17-en-ar-v0-res.json @@ -0,0 +1 @@ +{"results": {"iwslt17-en-ar": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.0, "chrf_stderr": 0.0, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"iwslt17-en-ar": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..efd450a8f2a4ca067f7380af809fdda48d1ee465 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada-v0-loglikelihood @@ -0,0 +1 @@ +6829e6a8aa5922e6c92dd31403cc060f242dc0ede4a775e085a70da095ab2e20 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ead0e9ce5d9629dea9be37e521fb3a152ced8680 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_cloze-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_cloze-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b599a89f7af0c28e795e5c5dfc1961f34acde2fc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_cloze-v0-loglikelihood @@ -0,0 +1 @@ +7655e748b63ae7e9911411d2d2a2577221d6c861ca4448509992541294d689f3 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_cloze-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_cloze-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..f3f3f931ac7e066cbab7b6ff68732360c764324f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_cloze-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_cloze": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_cloze": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_de-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_de-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ae19de0e6951bd90cd1e713d14816767496044e8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_de-v0-loglikelihood @@ -0,0 +1 @@ +5ad125e1708499832b2cee8c3388f89f9c0277010fd96fbd3359039ce8105984 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_de-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_de-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..7267ea739a54f5fd165ef0011d27446faac04689 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_de-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_mt_de": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_mt_de": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_en-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_en-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..efd450a8f2a4ca067f7380af809fdda48d1ee465 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_en-v0-loglikelihood @@ -0,0 +1 @@ +6829e6a8aa5922e6c92dd31403cc060f242dc0ede4a775e085a70da095ab2e20 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..561b88ffe110684b7de34a84ac613d1d901c72e5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_en-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_mt_en": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_mt_en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_es-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_es-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..df895fe6d6bf04fc51c1633d26fb835941176534 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_es-v0-loglikelihood @@ -0,0 +1 @@ +4a88f4b316c72fe0396c382d6cbb33568ac4d0ad225150d3536635c085359fc9 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_es-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_es-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5f95957324e138bb424e71ff93f81a0c0a11f2cb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_es-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_mt_es": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_mt_es": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_fr-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_fr-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3c444f66611959e4c13451d306fba403261ecfbb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_fr-v0-loglikelihood @@ -0,0 +1 @@ +5d16f4a0c51dc6d7b6df2ebeba2bbfa51e700b843779b559b3d90183d7b02a11 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_fr-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_fr-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..637c23500b9c153fe74ad9cb0369bd57f22d80a0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_fr-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_mt_fr": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_mt_fr": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_it-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_it-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ca3fd80298aa1c565c978b26e992ccd42c7144f6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_it-v0-loglikelihood @@ -0,0 +1 @@ +fd87c6c5cf4e0499c5f9f80e5bd7ee6a4f3d2991902a0cc3ec9e6eaf22d6760a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_it-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_it-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b652210ae3df4694785f6bfe6543909435122dee --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_mt_it-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_mt_it": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_mt_it": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..efd450a8f2a4ca067f7380af809fdda48d1ee465 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v0-loglikelihood @@ -0,0 +1 @@ +6829e6a8aa5922e6c92dd31403cc060f242dc0ede4a775e085a70da095ab2e20 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..30fcb907b5dbbabb2af4cf3a156cf18c67d387df --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v2.0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v2.0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..688e67a5534f801d5b256905a0d05a60c0adf8fc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v2.0-loglikelihood @@ -0,0 +1 @@ +9ca5643bbaafed2f027eab5b68cc438e9e268f6df9a678e956e61726a985cf0b \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v2.0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v2.0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..12e7f527bde7683ea74111603618c1e99cdd93a6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai-v2.0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai": "2.0"}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_cloze-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_cloze-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b599a89f7af0c28e795e5c5dfc1961f34acde2fc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_cloze-v0-loglikelihood @@ -0,0 +1 @@ +7655e748b63ae7e9911411d2d2a2577221d6c861ca4448509992541294d689f3 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_cloze-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_cloze-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a52f2a9f1c83bcc119c95c05394f1bd2a86bf888 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_cloze-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai_cloze": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai_cloze": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ae19de0e6951bd90cd1e713d14816767496044e8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-loglikelihood @@ -0,0 +1 @@ +5ad125e1708499832b2cee8c3388f89f9c0277010fd96fbd3359039ce8105984 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..12f5d349ebd170ee5295656bc3907f872453eca6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai_mt_de": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai_mt_de": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_en-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_en-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..efd450a8f2a4ca067f7380af809fdda48d1ee465 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_en-v0-loglikelihood @@ -0,0 +1 @@ +6829e6a8aa5922e6c92dd31403cc060f242dc0ede4a775e085a70da095ab2e20 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..f7fdfc9c2d5c6d5d4abb7d6e932454615c095ea1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_en-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai_mt_en": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai_mt_en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_es-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_es-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..df895fe6d6bf04fc51c1633d26fb835941176534 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_es-v0-loglikelihood @@ -0,0 +1 @@ +4a88f4b316c72fe0396c382d6cbb33568ac4d0ad225150d3536635c085359fc9 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_es-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_es-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..684e35a4cf44f85a0dc5f82fc06fb2b4ebc90316 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_es-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai_mt_es": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai_mt_es": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_fr-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_fr-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3c444f66611959e4c13451d306fba403261ecfbb --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_fr-v0-loglikelihood @@ -0,0 +1 @@ +5d16f4a0c51dc6d7b6df2ebeba2bbfa51e700b843779b559b3d90183d7b02a11 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_fr-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_fr-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ab6217943ab5d8e7547655c90ec95553c9557ee8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_fr-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai_mt_fr": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai_mt_fr": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_it-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_it-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ca3fd80298aa1c565c978b26e992ccd42c7144f6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_it-v0-loglikelihood @@ -0,0 +1 @@ +fd87c6c5cf4e0499c5f9f80e5bd7ee6a4f3d2991902a0cc3ec9e6eaf22d6760a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_it-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_it-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2e7f6ef516e5e59af82f1768cfde132d57c1a1ec --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_mt_it-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_openai_mt_it": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai_mt_it": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..fcbd56f50425ca6e143ccc0dd88458c051b63fb2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard-v0-loglikelihood @@ -0,0 +1 @@ +8958d9f8d8145046b692fadd8a9cc9c8bad5617c10774280cf7c24c21d2be160 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1f15d0be56b5edf18ad7cc2bec4977fae99f060b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_standard": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_standard": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard_cloze-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard_cloze-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..0a7b76241f898374a3a75952e16fe15af9a6d48e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard_cloze-v0-loglikelihood @@ -0,0 +1 @@ +b604f00bc9f2a77ef41f8cfdb5a8509b3ae9266893b9e90abc665f5399ecba4e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard_cloze-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard_cloze-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5b3139fce60c4f456d1354e85f86f15657d63b85 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_standard_cloze-v0-res.json @@ -0,0 +1 @@ +{"results": {"lambada_standard_cloze": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_standard_cloze": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/logiqa-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/logiqa-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..9cd40fce0a7062ec6897a119d44b1de88f762d08 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/logiqa-v0-loglikelihood @@ -0,0 +1 @@ +12495c50454ba5e1ce0753bd18c09aaca516bebd27648d815e37b15229dbf198 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/logiqa-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/logiqa-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..7a80c24d1b3e57ffca8ca89252d3c9b01b506f49 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/logiqa-v0-res.json @@ -0,0 +1 @@ +{"results": {"logiqa": {"acc": 0.25806451612903225, "acc_norm": 0.2764976958525346, "acc_norm_stderr": 0.017543209075825194, "acc_stderr": 0.017162894755127077}}, "versions": {"logiqa": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..ce881a0232cff3f1025b746184ce8a0170e34303 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v0-greedy_until @@ -0,0 +1 @@ +f19182ce697a2c095d9e5b56ee6659dc38c93994b69ca75d7c3d3f5fd87572b4 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..192cb9d8529cd67cb47e6f90d76a4a9e98b12d97 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v0-res.json @@ -0,0 +1 @@ +{"results": {"math_algebra": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_algebra": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..ce881a0232cff3f1025b746184ce8a0170e34303 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v1-greedy_until @@ -0,0 +1 @@ +f19182ce697a2c095d9e5b56ee6659dc38c93994b69ca75d7c3d3f5fd87572b4 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..10d18c2f864117ae56fe56ba1191f6cde4bec7b3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_algebra-v1-res.json @@ -0,0 +1 @@ +{"results": {"math_algebra": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_algebra": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..6f49557ecf42758d64d1297c5569f3d4d95dd9c1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v0-greedy_until @@ -0,0 +1 @@ +2aa9ae43ee9dbb2457525247d7b65358632c5eaa9cbfc40cf95a4f17f5d942ad \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..8ee1d031de8ec7d2af61c83567d433f9116ba24d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v0-res.json @@ -0,0 +1 @@ +{"results": {"math_counting_and_prob": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_counting_and_prob": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..6f49557ecf42758d64d1297c5569f3d4d95dd9c1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v1-greedy_until @@ -0,0 +1 @@ +2aa9ae43ee9dbb2457525247d7b65358632c5eaa9cbfc40cf95a4f17f5d942ad \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..240f7b6b42b77b8e94c1ec2eab2df808181a2cb3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_counting_and_prob-v1-res.json @@ -0,0 +1 @@ +{"results": {"math_counting_and_prob": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_counting_and_prob": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..1c7362fe44e4432f56f18932b4b429d5cf573399 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v0-greedy_until @@ -0,0 +1 @@ +46bc4cb219b6903397da782699a684bdbb982c0c954ff82e6beeed5c84878f42 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1b25dc283c96c63d30df9f0ce3d04aadb8f93625 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v0-res.json @@ -0,0 +1 @@ +{"results": {"math_geometry": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_geometry": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..1c7362fe44e4432f56f18932b4b429d5cf573399 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v1-greedy_until @@ -0,0 +1 @@ +46bc4cb219b6903397da782699a684bdbb982c0c954ff82e6beeed5c84878f42 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..eb6851fc63ff08c657743ef6abf5073ba73144e5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_geometry-v1-res.json @@ -0,0 +1 @@ +{"results": {"math_geometry": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_geometry": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..3ab10de26a038019a18699e20887de6da66981c4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v0-greedy_until @@ -0,0 +1 @@ +d53c699de272d517ed7ad783b4e692302be9f9f97a8d4ac7a6541e538a7cabe0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..7a195d9ac43e6feb4a7fc354f5dc424a27b0bf7d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v0-res.json @@ -0,0 +1 @@ +{"results": {"math_intermediate_algebra": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_intermediate_algebra": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..3ab10de26a038019a18699e20887de6da66981c4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v1-greedy_until @@ -0,0 +1 @@ +d53c699de272d517ed7ad783b4e692302be9f9f97a8d4ac7a6541e538a7cabe0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..63ab45b9ff890a0ef7c2108133b23bf0043f13f8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_intermediate_algebra-v1-res.json @@ -0,0 +1 @@ +{"results": {"math_intermediate_algebra": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_intermediate_algebra": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..82febb9f5dfeefbd6dc5d244574ac5666c6b8bba --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v0-greedy_until @@ -0,0 +1 @@ +b920ccb507afdcf3ef6f4c04891913731e9f32ec914801791c6d9f8abf6e1897 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a27a38fa9d4f3a924828bdb4526953a35328c7e5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v0-res.json @@ -0,0 +1 @@ +{"results": {"math_num_theory": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_num_theory": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..82febb9f5dfeefbd6dc5d244574ac5666c6b8bba --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v1-greedy_until @@ -0,0 +1 @@ +b920ccb507afdcf3ef6f4c04891913731e9f32ec914801791c6d9f8abf6e1897 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..00917b90ddb0602c62c8a9fef959b9e91eb45c2e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_num_theory-v1-res.json @@ -0,0 +1 @@ +{"results": {"math_num_theory": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_num_theory": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..5200f4cfa9ed3a735661e987791bf1434555db6e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v0-greedy_until @@ -0,0 +1 @@ +752cdf343d7152e476b0273065024f6ea0e0f47ea385c6bdf9067736cb39724a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b3ada8a6be4d86b71a0c6b92c605d3c8a25a29a2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v0-res.json @@ -0,0 +1 @@ +{"results": {"math_prealgebra": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_prealgebra": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..5200f4cfa9ed3a735661e987791bf1434555db6e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v1-greedy_until @@ -0,0 +1 @@ +752cdf343d7152e476b0273065024f6ea0e0f47ea385c6bdf9067736cb39724a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..e3869faa8012568df2eae14e3774712960c4a544 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_prealgebra-v1-res.json @@ -0,0 +1 @@ +{"results": {"math_prealgebra": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_prealgebra": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..71bbd8d9c221ca484d517bda46c109b2610f79f6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v0-greedy_until @@ -0,0 +1 @@ +bc834b06fd79473ca6fe38a51b714aad0bf0478c1b0eec787eca34dbdf69cb71 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..699dc5fe38ea411d6d53c9e19d78ba6d96ddfb40 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v0-res.json @@ -0,0 +1 @@ +{"results": {"math_precalc": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_precalc": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..71bbd8d9c221ca484d517bda46c109b2610f79f6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v1-greedy_until @@ -0,0 +1 @@ +bc834b06fd79473ca6fe38a51b714aad0bf0478c1b0eec787eca34dbdf69cb71 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a5846590a3b28f2382d00a3400e1c46a9018adea --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/math_precalc-v1-res.json @@ -0,0 +1 @@ +{"results": {"math_precalc": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"math_precalc": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mathqa-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mathqa-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..9f33d79035cc7caf00704a8764aa0adf657c0b78 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mathqa-v0-loglikelihood @@ -0,0 +1 @@ +a45260e49f02c7cb8886b3746db4d388890860b202dd8a9f0267e3c324e0af13 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mathqa-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mathqa-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..dabd07c07cbbad2886b20acb25189b111676bbcd --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mathqa-v0-res.json @@ -0,0 +1 @@ +{"results": {"mathqa": {"acc": 0.20770519262981574, "acc_norm": 0.2050251256281407, "acc_norm_stderr": 0.007390619359738901, "acc_stderr": 0.007426217631188539}}, "versions": {"mathqa": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mc_taco-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mc_taco-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..f0ce5c64580d1132710e596cc287126ba77394e6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mc_taco-v0-loglikelihood @@ -0,0 +1 @@ +1811808ef05afd5f30ffc3471622a3dd7a1b681b17a2f7616695ad6b2a45943c \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mc_taco-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mc_taco-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..fc36d1ed3ff4d02330a13eb7431d5413b4c484e5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mc_taco-v0-res.json @@ -0,0 +1 @@ +{"results": {"mc_taco": {"em": 0.07732732732732733, "f1": 0.41600515965511614}}, "versions": {"mc_taco": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..433b76d01094a18991412513044f0933eb0bf3f5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli-v0-loglikelihood @@ -0,0 +1 @@ +4fc7b56b8f1e37e38f4a052b227baec2df914c898c3405d3e994726ba4fba976 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..d9dada7a0244534c35d86efb71a03fbd90217328 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli-v0-res.json @@ -0,0 +1 @@ +{"results": {"mnli": {"acc": 0.32868059093224655, "acc_stderr": 0.004741640290753859}}, "versions": {"mnli": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli_mismatched-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli_mismatched-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3fb242da3a2d274cbcc84bf86a6bb11f02df27ab --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli_mismatched-v0-loglikelihood @@ -0,0 +1 @@ +3784acf322e79f31702a7a0612030e4ba5c4fc466ad976a34ee3f3d7278c01f0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli_mismatched-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli_mismatched-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..261deed96275da1af0c8a0616b0af6247cfaf1c0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mnli_mismatched-v0-res.json @@ -0,0 +1 @@ +{"results": {"mnli_mismatched": {"acc": 0.3360455655004068, "acc_stderr": 0.004763973908606819}}, "versions": {"mnli_mismatched": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mrpc-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mrpc-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..95c849a153762819da1ce59c1b58a2013b97ef6a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mrpc-v0-loglikelihood @@ -0,0 +1 @@ +9f54cbff8d6accba99cfa2c4c4b359563313941018173d7dcf9e32dc28c06583 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mrpc-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mrpc-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..f141eaa0a49aceaae493aea7080eab4e8b1cec16 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mrpc-v0-res.json @@ -0,0 +1 @@ +{"results": {"mrpc": {"acc": 0.5392156862745098, "acc_stderr": 0.024707732873723128, "f1": 0.5982905982905982, "f1_stderr": 0.028928325246283727}}, "versions": {"mrpc": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b3681ec17595adc4c4541ded263add219912af58 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v0-loglikelihood @@ -0,0 +1 @@ +cdb026c027437a8b4653212d0944d36fc16f49921dcb8e4bef899d15a55e9f80 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..87e9c532eb7d7deb7d08635dd955df7a68ab9813 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v0-res.json @@ -0,0 +1 @@ +{"results": {"multirc": {"acc": 0.07450157397691501, "acc_stderr": 0.008510441526175931}}, "versions": {"multirc": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v1-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v1-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..52a89c6f9eaf1cece362cf2d4bd114f8ae3cbdda --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v1-loglikelihood @@ -0,0 +1 @@ +0e793bd6f637a70a04c6f2cda080188fc037961b2f909095fe63f7bdbc4a90c6 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..938141bbb888f55c3aa2786868c28925ac3fd123 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/multirc-v1-res.json @@ -0,0 +1 @@ +{"results": {"multirc": {"acc": 0.046169989506820566, "acc_stderr": 0.006801377886208738}}, "versions": {"multirc": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..0022f466d25f3e3a639720e4600732c9c0c1141d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v0-loglikelihood @@ -0,0 +1 @@ +f759213a28f0412510bf1a24c9cab0dae64bdee902d42a26225295445e7779db \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2d240576b3b8d891ff91a47770df9990edf34105 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v0-res.json @@ -0,0 +1 @@ +{"results": {"mutual": {"mrr": 0.5023513920240772, "mrr_stderr": 0.009501864812936679, "r@1": 0.22573363431151242, "r@1_stderr": 0.014053085820407457, "r@2": 0.4221218961625282, "r@2_stderr": 0.016602191705517556}}, "versions": {"mutual": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v1-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v1-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..0022f466d25f3e3a639720e4600732c9c0c1141d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v1-loglikelihood @@ -0,0 +1 @@ +f759213a28f0412510bf1a24c9cab0dae64bdee902d42a26225295445e7779db \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..42e97c6f1a1b65ef76cc3941c8b08e8ca836a59c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual-v1-res.json @@ -0,0 +1 @@ +{"results": {"mutual": {"mrr": 0.5023513920240772, "mrr_stderr": 0.009501864812936679, "r@1": 0.22460496613995484, "r@1_stderr": 0.014028122493992806, "r@2": 0.4706546275395034, "r@2_stderr": 0.016778343895001414}}, "versions": {"mutual": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..f4ba9d37310a19cc7928fd0d599776d8a9da8dba --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v0-loglikelihood @@ -0,0 +1 @@ +b846bb9db109535f59a93d1ce340cf09f68bdf4fed5b8decd168784220fe07fa \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9c0348826363dfe77e60cb28cf546110e25bab35 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v0-res.json @@ -0,0 +1 @@ +{"results": {"mutual_plus": {"mrr": 0.5275583145221953, "mrr_stderr": 0.009940894824430708, "r@1": 0.2595936794582393, "r@1_stderr": 0.014737047402750955, "r@2": 0.45372460496614, "r@2_stderr": 0.01673517854461967}}, "versions": {"mutual_plus": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v1-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v1-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..f4ba9d37310a19cc7928fd0d599776d8a9da8dba --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v1-loglikelihood @@ -0,0 +1 @@ +b846bb9db109535f59a93d1ce340cf09f68bdf4fed5b8decd168784220fe07fa \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..cdb6c85b65643b2214358d18b057d0737d53b9ba --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mutual_plus-v1-res.json @@ -0,0 +1 @@ +{"results": {"mutual_plus": {"mrr": 0.5275583145221953, "mrr_stderr": 0.009940894824430708, "r@1": 0.26297968397291194, "r@1_stderr": 0.01479889176605113, "r@2": 0.5, "r@2_stderr": 0.01680731613632036}}, "versions": {"mutual_plus": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/openbookqa-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/openbookqa-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b2cc5e9795fd1623bfc11e4d1cb53b0e1baa3dbf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/openbookqa-v0-loglikelihood @@ -0,0 +1 @@ +78a49a0ca1a47373adb33463b1d092e6bc0d8f4b01bcb380ada48065037849d7 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/openbookqa-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/openbookqa-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..04f4c25442e678a63d3f6213dc9364bfa25b1a7a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/openbookqa-v0-res.json @@ -0,0 +1 @@ +{"results": {"openbookqa": {"acc": 0.214, "acc_norm": 0.276, "acc_norm_stderr": 0.020011219298073517, "acc_stderr": 0.018359797502387046}}, "versions": {"openbookqa": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..3aa1d8c7349449271fbd81fbbc06fde47a116028 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v0-loglikelihood_rolling @@ -0,0 +1 @@ +814f9954e44368559602c00f7e85fa3971acdfd0315f508ec7df6318a79c55ec \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..d19d0c6fee7f47af1ad3f5af9ff1d7a1544e2e98 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_arxiv": {"bits_per_byte": 1.0750412350569374e-05, "byte_perplexity": 1.0000107504701365, "word_perplexity": 1.0000819333090385}}, "versions": {"pile_arxiv": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..3aa1d8c7349449271fbd81fbbc06fde47a116028 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v1-loglikelihood_rolling @@ -0,0 +1 @@ +814f9954e44368559602c00f7e85fa3971acdfd0315f508ec7df6318a79c55ec \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..05cbab38732c94665750aac31cd2c41688552a8d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_arxiv-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_arxiv": {"bits_per_byte": 1.55095665856779e-05, "byte_perplexity": 1.0000107504701365, "word_perplexity": 1.0000819333090385}}, "versions": {"pile_arxiv": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..b37a91cc2dea829e8dab7bb0fe934442c54b3a26 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v0-loglikelihood_rolling @@ -0,0 +1 @@ +5c17ddfebeab8c41dabadb6fc216ceda91e3fe5dc95aaf1b2c843d7f11828b03 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..698b03e8b3b437f94f22744ffe12ba2fff9285f6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_bookcorpus2": {"bits_per_byte": 1.1631037706429144e-06, "byte_perplexity": 1.000001163104447, "word_perplexity": 1.0000066499426599}}, "versions": {"pile_bookcorpus2": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..b37a91cc2dea829e8dab7bb0fe934442c54b3a26 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v1-loglikelihood_rolling @@ -0,0 +1 @@ +5c17ddfebeab8c41dabadb6fc216ceda91e3fe5dc95aaf1b2c843d7f11828b03 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..967c14934b81e0880063c4239593fb74cd99cd8d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_bookcorpus2-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_bookcorpus2": {"bits_per_byte": 1.6780040419457868e-06, "byte_perplexity": 1.000001163104447, "word_perplexity": 1.0000066499426599}}, "versions": {"pile_bookcorpus2": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..b483d3b45b43abddd6cbd169a8afda8d3f803d9c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v0-loglikelihood_rolling @@ -0,0 +1 @@ +0f8f36f705b999b6d55fa72ff89a82793dd1cb568ab1f8727a6a2086a12b9410 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..df19cd0a18f122d695f8aea4a717ab4dde79a987 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_books3": {"bits_per_byte": 8.942486206275221e-07, "byte_perplexity": 1.0000008942490204, "word_perplexity": 1.0000052870063607}}, "versions": {"pile_books3": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..b483d3b45b43abddd6cbd169a8afda8d3f803d9c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v1-loglikelihood_rolling @@ -0,0 +1 @@ +0f8f36f705b999b6d55fa72ff89a82793dd1cb568ab1f8727a6a2086a12b9410 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..6ff7a517112eba76e15e999e9974124e04f07a83 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_books3-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_books3": {"bits_per_byte": 1.2901280503011222e-06, "byte_perplexity": 1.0000008942490204, "word_perplexity": 1.0000052870063607}}, "versions": {"pile_books3": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..2fb27786c54abe6303683c0a247d4c689586a97c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v0-loglikelihood_rolling @@ -0,0 +1 @@ +d5b7967c0ece8b816f3921a8bd0fad23365349e935b491595e2ad1135af42da6 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..860aa06c974e58d03f54ab1d9cb14c7e98019d4e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_dm-mathematics": {"bits_per_byte": 6.176600873627999e-05, "byte_perplexity": 1.0000617679162955, "word_perplexity": 1.0002875035042451}}, "versions": {"pile_dm-mathematics": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..2fb27786c54abe6303683c0a247d4c689586a97c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v1-loglikelihood_rolling @@ -0,0 +1 @@ +d5b7967c0ece8b816f3921a8bd0fad23365349e935b491595e2ad1135af42da6 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..192e9066a42acf28436ae325a212b2a7c2ebf517 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_dm-mathematics-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_dm-mathematics": {"bits_per_byte": 8.910951449933553e-05, "byte_perplexity": 1.0000617679162955, "word_perplexity": 1.0002875035042451}}, "versions": {"pile_dm-mathematics": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..57dbe764605ef5e1e4578682549a001c851704c0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v0-loglikelihood_rolling @@ -0,0 +1 @@ +4baa6ccdc9e3aa9921675ab4400d5e89d7b546b844a8ea28f6461d649066418a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a4a49493d56db35c99b7e58ea66ebc21304184b2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_enron": {"bits_per_byte": 0.0003163902828673244, "byte_perplexity": 1.000316440339552, "word_perplexity": 1.00224668051869}}, "versions": {"pile_enron": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..57dbe764605ef5e1e4578682549a001c851704c0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v1-loglikelihood_rolling @@ -0,0 +1 @@ +4baa6ccdc9e3aa9921675ab4400d5e89d7b546b844a8ea28f6461d649066418a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..abe7b45f9aff9b6427068ceb1ba39977fa843c38 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_enron-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_enron": {"bits_per_byte": 0.0004564546920781453, "byte_perplexity": 1.000316440339552, "word_perplexity": 1.00224668051869}}, "versions": {"pile_enron": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..80272607557f6e0c97220efa30c8b9ad38f52aa8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v0-loglikelihood_rolling @@ -0,0 +1 @@ +e67d3dbccd47d308bfc5b0e66b76d0dfc5e386ebfa94e056562c2281c395543f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4c53edd2ce620475c056ccca5cde73380c246074 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_europarl": {"bits_per_byte": 8.648858203555344e-06, "byte_perplexity": 1.000008648895605, "word_perplexity": 1.000063506523818}}, "versions": {"pile_europarl": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..80272607557f6e0c97220efa30c8b9ad38f52aa8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v1-loglikelihood_rolling @@ -0,0 +1 @@ +e67d3dbccd47d308bfc5b0e66b76d0dfc5e386ebfa94e056562c2281c395543f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b948f0d3691443f50c9f9d5ae24804b0c7e79aaa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_europarl-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_europarl": {"bits_per_byte": 1.2477664839621123e-05, "byte_perplexity": 1.000008648895605, "word_perplexity": 1.000063506523818}}, "versions": {"pile_europarl": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..7b5771f4911f3069217d75d12cbdfa1a579b6663 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v0-loglikelihood_rolling @@ -0,0 +1 @@ +d77f3f68aadd6cbf1290c2f6737b2ed5d5c2a60e4c81a65c280f207783caabe1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0bda41ffb37dd04bebd9982faf464616dd82a31d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_freelaw": {"bits_per_byte": 3.16238943008513e-05, "byte_perplexity": 1.0000316243943415, "word_perplexity": 1.000203169094218}}, "versions": {"pile_freelaw": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..7b5771f4911f3069217d75d12cbdfa1a579b6663 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v1-loglikelihood_rolling @@ -0,0 +1 @@ +d77f3f68aadd6cbf1290c2f6737b2ed5d5c2a60e4c81a65c280f207783caabe1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..dd0e0bac36b116bddbcd70d4327c3cdb3e3630e9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_freelaw-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_freelaw": {"bits_per_byte": 4.5623635481434923e-05, "byte_perplexity": 1.0000316243943415, "word_perplexity": 1.000203169094218}}, "versions": {"pile_freelaw": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..cf8251e4f68e2e893624142031e80d4d5777f4f2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v0-loglikelihood_rolling @@ -0,0 +1 @@ +df384c3df3d8f53273e97127c5bb84c17e638acad7d6bc9c91f6dee96d43b639 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..bdabf399695d155026643eacca7954c5f87009d5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_github": {"bits_per_byte": 9.540627613754646e-05, "byte_perplexity": 1.0000954108274611, "word_perplexity": 1.0009643183931227}}, "versions": {"pile_github": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..cf8251e4f68e2e893624142031e80d4d5777f4f2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v1-loglikelihood_rolling @@ -0,0 +1 @@ +df384c3df3d8f53273e97127c5bb84c17e638acad7d6bc9c91f6dee96d43b639 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..cc06a45501fb498db32e56d0677ef01f10869cc9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_github-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_github": {"bits_per_byte": 0.00013764216145332133, "byte_perplexity": 1.0000954108274611, "word_perplexity": 1.0009643183931227}}, "versions": {"pile_github": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..bd7b15927f717baab5b7ce2e9d659dda6d681769 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-loglikelihood_rolling @@ -0,0 +1 @@ +02a559f74a9105145e7d4d9c5ddea372b5b4938f5368dc8ffafc39cbe3b4c7ef \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..757ef06f79c938e6968583eb58a135fad23c897e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_gutenberg": {"bits_per_byte": 1.2443606332351536e-06, "byte_perplexity": 1.0000012443614075, "word_perplexity": 1.0000072174665404}}, "versions": {"pile_gutenberg": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..bd7b15927f717baab5b7ce2e9d659dda6d681769 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v1-loglikelihood_rolling @@ -0,0 +1 @@ +02a559f74a9105145e7d4d9c5ddea372b5b4938f5368dc8ffafc39cbe3b4c7ef \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..6d22ed3ff50eaa5a68f8a5ad1ac4d3828f74f81f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_gutenberg-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_gutenberg": {"bits_per_byte": 1.7952329146458065e-06, "byte_perplexity": 1.0000012443614075, "word_perplexity": 1.0000072174665404}}, "versions": {"pile_gutenberg": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..48b767bfe706bb035e4553ea9c4119347303bab9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v0-loglikelihood_rolling @@ -0,0 +1 @@ +ec1082ee5a5326e0d57aa4e73b634937140c1de9af95f154e8ab57b05d9b422b \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..68578fe4c952b8bccb26700be82df67450c558dd --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_hackernews": {"bits_per_byte": 0.00010170276359193358, "byte_perplexity": 1.0001017079354932, "word_perplexity": 1.0006273924348839}}, "versions": {"pile_hackernews": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..48b767bfe706bb035e4553ea9c4119347303bab9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v1-loglikelihood_rolling @@ -0,0 +1 @@ +ec1082ee5a5326e0d57aa4e73b634937140c1de9af95f154e8ab57b05d9b422b \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ea135278b720703540187531afb0ef82e7d6a1ce --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_hackernews-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_hackernews": {"bits_per_byte": 0.00014672607267878518, "byte_perplexity": 1.0001017079354932, "word_perplexity": 1.0006273924348839}}, "versions": {"pile_hackernews": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..5f76588a813eebe7f0958a07253480d30de2ccf3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v0-loglikelihood_rolling @@ -0,0 +1 @@ +520ea6e04e8a39dc0b5f63a837429a78a40e63d39d109096101feb8c5b2cf8d8 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1c7bb56c6dc6cec7e2677317b3f9888293a65b92 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_nih-exporter": {"bits_per_byte": 0.00024394433346975716, "byte_perplexity": 1.0002439740903082, "word_perplexity": 1.0016712202288802}}, "versions": {"pile_nih-exporter": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..5f76588a813eebe7f0958a07253480d30de2ccf3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-loglikelihood_rolling @@ -0,0 +1 @@ +520ea6e04e8a39dc0b5f63a837429a78a40e63d39d109096101feb8c5b2cf8d8 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0e40fc8268a77618471344585bc1a1586fd69e0f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_nih-exporter": {"bits_per_byte": 0.00035193728014978225, "byte_perplexity": 1.0002439740903082, "word_perplexity": 1.0016712202288802}}, "versions": {"pile_nih-exporter": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..47805d3b5fe82555e4d61a90b43c157c974ddabc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v0-loglikelihood_rolling @@ -0,0 +1 @@ +0f1c23a1f4ddec0c2b1ff34de8d1505b0eb9e2868d8edbcc1b6de13d02f32036 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..f718e515ba0cedfa5156b3a260d50ed55efc32e4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_opensubtitles": {"bits_per_byte": 1.5213441136639177e-05, "byte_perplexity": 1.0000152135568616, "word_perplexity": 1.0000856162053249}}, "versions": {"pile_opensubtitles": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..47805d3b5fe82555e4d61a90b43c157c974ddabc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v1-loglikelihood_rolling @@ -0,0 +1 @@ +0f1c23a1f4ddec0c2b1ff34de8d1505b0eb9e2868d8edbcc1b6de13d02f32036 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1468294732b13576161fc3824a479028d5bdb0ba --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_opensubtitles-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_opensubtitles": {"bits_per_byte": 2.1948356082685497e-05, "byte_perplexity": 1.0000152135568616, "word_perplexity": 1.0000856162053249}}, "versions": {"pile_opensubtitles": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..22046e440584d0df85ceeed057ad2c0633273782 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v0-loglikelihood_rolling @@ -0,0 +1 @@ +5d6c19665f429ab1ccbe027da67f42bdaf219f819ab093673976eee55e015ff4 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ead8d0b0bffe2da65e2602c7f2f352eeb404ef26 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_openwebtext2": {"bits_per_byte": 0.00012809520662477846, "byte_perplexity": 1.000128103411166, "word_perplexity": 1.0007951516532847}}, "versions": {"pile_openwebtext2": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..22046e440584d0df85ceeed057ad2c0633273782 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-loglikelihood_rolling @@ -0,0 +1 @@ +5d6c19665f429ab1ccbe027da67f42bdaf219f819ab093673976eee55e015ff4 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ca433e3c854780d034839c8e4d029cb6b5bfca1a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_openwebtext2": {"bits_per_byte": 0.000184802319359215, "byte_perplexity": 1.000128103411166, "word_perplexity": 1.0007951516532847}}, "versions": {"pile_openwebtext2": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..4fbbc241ba9487c2513cdf46dbb76e004e401418 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v0-loglikelihood_rolling @@ -0,0 +1 @@ +339ba5d8c044c4a3ff9b9a8eaa24da1d6c01b72972074eb671a7da049eeb7047 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..be561fe2f8a6fe5eba08c4c1efd113075da42e1f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_philpapers": {"bits_per_byte": 6.241575895982095e-06, "byte_perplexity": 1.0000062415953748, "word_perplexity": 1.0000409888564146}}, "versions": {"pile_philpapers": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..4fbbc241ba9487c2513cdf46dbb76e004e401418 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v1-loglikelihood_rolling @@ -0,0 +1 @@ +339ba5d8c044c4a3ff9b9a8eaa24da1d6c01b72972074eb671a7da049eeb7047 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5a2f77678abc264edf433a4eb98da08fc20b1dfc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_philpapers-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_philpapers": {"bits_per_byte": 9.004690592465457e-06, "byte_perplexity": 1.0000062415953748, "word_perplexity": 1.0000409888564146}}, "versions": {"pile_philpapers": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..d5369ed3c97838d67c2900cfac4aaeb5881ec884 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v0-loglikelihood_rolling @@ -0,0 +1 @@ +731fdef4a43949b179ba0c540148ebc2fa41583dd583ef580dd812076c66a451 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..383233f259507dfdbc6556834185f1eb6161f9cd --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_pile-cc": {"bits_per_byte": 0.00011234131907228174, "byte_perplexity": 1.0001123476295946, "word_perplexity": 1.0006738958554477}}, "versions": {"pile_pile-cc": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..d5369ed3c97838d67c2900cfac4aaeb5881ec884 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v1-loglikelihood_rolling @@ -0,0 +1 @@ +731fdef4a43949b179ba0c540148ebc2fa41583dd583ef580dd812076c66a451 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..bd2772e32a91a6518ed2eb48ef880827f5246adf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pile-cc-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_pile-cc": {"bits_per_byte": 0.0001620742639125056, "byte_perplexity": 1.0001123476295946, "word_perplexity": 1.0006738958554477}}, "versions": {"pile_pile-cc": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..de5660d60a8d4f0d5e35d47008992befed318d28 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v0-loglikelihood_rolling @@ -0,0 +1 @@ +66436569a43163afb2caf422d32c5f329899e74c49865d4d13881fd465fd9976 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..333c2970fa21b0bd53b77bdc3880acad0c8d6459 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_pubmed-abstracts": {"bits_per_byte": 0.00037553733051528816, "byte_perplexity": 1.0003756078534862, "word_perplexity": 1.0025884332779}}, "versions": {"pile_pubmed-abstracts": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..de5660d60a8d4f0d5e35d47008992befed318d28 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v1-loglikelihood_rolling @@ -0,0 +1 @@ +66436569a43163afb2caf422d32c5f329899e74c49865d4d13881fd465fd9976 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..21b6bb451fe376e62899f22ea422b3ce9cada469 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-abstracts-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_pubmed-abstracts": {"bits_per_byte": 0.0005417858444030858, "byte_perplexity": 1.0003756078534862, "word_perplexity": 1.0025884332779}}, "versions": {"pile_pubmed-abstracts": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..283109f32e0aac45adcbc90c7c8fb41114e7771f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v0-loglikelihood_rolling @@ -0,0 +1 @@ +40b39d120d99a145690444e86acc3e3e24d41e6e0538a75e26929ad84926e5e0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..6e5f1efe495f7030764f96e45460a4d47315b1e3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_pubmed-central": {"bits_per_byte": 1.5812411832795375e-05, "byte_perplexity": 1.0000158125368497, "word_perplexity": 1.000123107107861}}, "versions": {"pile_pubmed-central": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..283109f32e0aac45adcbc90c7c8fb41114e7771f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v1-loglikelihood_rolling @@ -0,0 +1 @@ +40b39d120d99a145690444e86acc3e3e24d41e6e0538a75e26929ad84926e5e0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4d4a241ace01e28f15cd7bd88d3f855b1bf5372d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_pubmed-central-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_pubmed-central": {"bits_per_byte": 2.2812488135667854e-05, "byte_perplexity": 1.0000158125368497, "word_perplexity": 1.000123107107861}}, "versions": {"pile_pubmed-central": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..dcf0e64cf0d4bf4fe719b8d349c1d36484d2047f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v0-loglikelihood_rolling @@ -0,0 +1 @@ +e524bfb3e21cbdaddc117403a50df598520c7bf5b2c60ad8f2372cfa564e79be \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..76fdd0a6dd2f8ca39611601c5cb514664d5dccbc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_stackexchange": {"bits_per_byte": 0.0002288815898835956, "byte_perplexity": 1.0002289077852733, "word_perplexity": 1.0016993562258851}}, "versions": {"pile_stackexchange": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..dcf0e64cf0d4bf4fe719b8d349c1d36484d2047f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v1-loglikelihood_rolling @@ -0,0 +1 @@ +e524bfb3e21cbdaddc117403a50df598520c7bf5b2c60ad8f2372cfa564e79be \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2773302990f71e46f7f44f5d2e2b624a52ddb54d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_stackexchange-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_stackexchange": {"bits_per_byte": 0.0003302063346758449, "byte_perplexity": 1.0002289077852733, "word_perplexity": 1.0016993562258851}}, "versions": {"pile_stackexchange": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..ce041998635643ee17aace3105b227ef0746917e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v0-loglikelihood_rolling @@ -0,0 +1 @@ +4eb69e314f0864ec8890e2323d7e76f8a8309692c4f090e2b41bf4be681a811d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..dff51cba766a795077324ffe9bf71d786dbb695a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_ubuntu-irc": {"bits_per_byte": 1.6298315496830533e-06, "byte_perplexity": 1.0000016298328778, "word_perplexity": 1.0000108866656874}}, "versions": {"pile_ubuntu-irc": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..ce041998635643ee17aace3105b227ef0746917e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v1-loglikelihood_rolling @@ -0,0 +1 @@ +4eb69e314f0864ec8890e2323d7e76f8a8309692c4f090e2b41bf4be681a811d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..0e3b1b25977cc5c7eba81358df76e7ed45d1b04a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_ubuntu-irc-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_ubuntu-irc": {"bits_per_byte": 2.3513498942121155e-06, "byte_perplexity": 1.0000016298328778, "word_perplexity": 1.0000108866656874}}, "versions": {"pile_ubuntu-irc": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..4649d3b9b7f1f17e4731644d470fc0a2651a980d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v0-loglikelihood_rolling @@ -0,0 +1 @@ +789b2bdb31564d512b70f801316f49320a26c83ba361226bac0afb255341d477 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..c13dfc73f5927415055cf393fb16bd13ba6b1b56 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_uspto": {"bits_per_byte": 0.00012062434384130924, "byte_perplexity": 1.00012063161925, "word_perplexity": 1.0007716198916954}}, "versions": {"pile_uspto": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..4649d3b9b7f1f17e4731644d470fc0a2651a980d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v1-loglikelihood_rolling @@ -0,0 +1 @@ +789b2bdb31564d512b70f801316f49320a26c83ba361226bac0afb255341d477 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..599ae44ef430af958ab53c57d0b7900928ad243a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_uspto-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_uspto": {"bits_per_byte": 0.000174024142670342, "byte_perplexity": 1.00012063161925, "word_perplexity": 1.0007716198916954}}, "versions": {"pile_uspto": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..e44bd2762803a9b922febf4fe8bfd459e95174b9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v0-loglikelihood_rolling @@ -0,0 +1 @@ +ef9ec0dd408316ca6537228a6812e839f14b30608973081d41efc47c138338da \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..bfffde9938833ae29f5665130d844630c7fb9735 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_wikipedia": {"bits_per_byte": 0.00016834722287561703, "byte_perplexity": 1.0001683613940646, "word_perplexity": 1.001084677949439}}, "versions": {"pile_wikipedia": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..e44bd2762803a9b922febf4fe8bfd459e95174b9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v1-loglikelihood_rolling @@ -0,0 +1 @@ +ef9ec0dd408316ca6537228a6812e839f14b30608973081d41efc47c138338da \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4f2314e66b3a5dbd9ed3c25d9e9a97c7d1fbff3d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_wikipedia-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_wikipedia": {"bits_per_byte": 0.00024287370359008176, "byte_perplexity": 1.0001683613940646, "word_perplexity": 1.001084677949439}}, "versions": {"pile_wikipedia": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..81c2e5ed06321b250a08a4232b3720ea5b650156 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v0-loglikelihood_rolling @@ -0,0 +1 @@ +68263c52adc0086011e2220b619983935cabb1cc1f5f9f8ee1a74ab2a7457967 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b58ce148f0071707d5da39135aaeb92a2a1457a2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v0-res.json @@ -0,0 +1 @@ +{"results": {"pile_youtubesubtitles": {"bits_per_byte": 2.3447170928931888e-05, "byte_perplexity": 1.000023447445816, "word_perplexity": 1.0001529192262875}}, "versions": {"pile_youtubesubtitles": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..81c2e5ed06321b250a08a4232b3720ea5b650156 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v1-loglikelihood_rolling @@ -0,0 +1 @@ +68263c52adc0086011e2220b619983935cabb1cc1f5f9f8ee1a74ab2a7457967 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..fcf2faa8bc7927212fa7c55940849f64d3c48968 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pile_youtubesubtitles-v1-res.json @@ -0,0 +1 @@ +{"results": {"pile_youtubesubtitles": {"bits_per_byte": 3.3827117222045906e-05, "byte_perplexity": 1.000023447445816, "word_perplexity": 1.0001529192262875}}, "versions": {"pile_youtubesubtitles": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/piqa-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/piqa-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..b01b1fe5d8c699f855bff57061d6d63715c7f058 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/piqa-v0-loglikelihood @@ -0,0 +1 @@ +6048a3a2bb3ad1e6a3d98139618e06b4d7de766edd685bd38837596199c3f69f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/piqa-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/piqa-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..bb6ebfb9a268d8fcfd3dd35ecb26fee05a1b8090 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/piqa-v0-res.json @@ -0,0 +1 @@ +{"results": {"piqa": {"acc": 0.514145810663765, "acc_norm": 0.5114254624591947, "acc_norm_stderr": 0.01166277802645167, "acc_stderr": 0.011661154475524836}}, "versions": {"piqa": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/prost-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/prost-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a94b8cdec9e45e5b236703414fbcc6a3ed74f7ff --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/prost-v0-loglikelihood @@ -0,0 +1 @@ +7c475f5b36a8b79f94c2be035441e7fd59dac021b0713b1fc72d256424c70b0b \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/prost-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/prost-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ff99d83f40a966afe7df30661a3fc4d9dd09c4ca --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/prost-v0-res.json @@ -0,0 +1 @@ +{"results": {"prost": {"acc": 0.24631725021349274, "acc_norm": 0.2581127241673783, "acc_norm_stderr": 0.00319703079646546, "acc_stderr": 0.003147855968061357}}, "versions": {"prost": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pubmedqa-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pubmedqa-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..97db87ce2be9b3d2c08479ee73c7ba3923817795 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pubmedqa-v0-loglikelihood @@ -0,0 +1 @@ +7a04a1fb1d2b19db84fd15c224015d6c0306a41195a4e71fe6abd48fb4d53b9f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pubmedqa-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pubmedqa-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..bb39463a4ab7244109901cbbc06ded3192ee0480 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/pubmedqa-v0-res.json @@ -0,0 +1 @@ +{"results": {"pubmedqa": {"acc": 0.324, "acc_stderr": 0.01480686473373886}}, "versions": {"pubmedqa": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2011-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2011-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..049134c7a1eac7ba79fa86951526a4ca96ddd200 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2011-v0-loglikelihood @@ -0,0 +1 @@ +0d09f17c65768e797633494d2d218e4e46a26f718cab8b0bf3d156b073a8c437 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2011-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2011-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..601c4eb763d97500cfcd4e24ca6602986c49939c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2011-v0-res.json @@ -0,0 +1 @@ +{"results": {"qa4mre_2011": {"acc": 0.225, "acc_norm": 0.23333333333333334, "acc_norm_stderr": 0.03877199986918664, "acc_stderr": 0.0382797091741014}}, "versions": {"qa4mre_2011": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2012-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2012-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..0e67fac5f7d54c19e42cae4cfc850089c7c61187 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2012-v0-loglikelihood @@ -0,0 +1 @@ +7e17261820acb365966cb9431d93aec983b14393eaeefbc96e30a11cf58bc6df \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2012-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2012-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..91d8f3660413469e7ab00c3af1102392c3e26cc7 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2012-v0-res.json @@ -0,0 +1 @@ +{"results": {"qa4mre_2012": {"acc": 0.15625, "acc_norm": 0.16875, "acc_norm_stderr": 0.029702236908328808, "acc_stderr": 0.02879508360159146}}, "versions": {"qa4mre_2012": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2013-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2013-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..43243706d9b743cec2965545f3f4436a3e5d7551 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2013-v0-loglikelihood @@ -0,0 +1 @@ +52fc431e94c67f983e28ebc70cf45e6c14116b0ae77dc1bf22347c705a65d054 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2013-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2013-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..c87e487e9ac147c5a9ba8cb3a4b2a39048d1dcaa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qa4mre_2013-v0-res.json @@ -0,0 +1 @@ +{"results": {"qa4mre_2013": {"acc": 0.18309859154929578, "acc_norm": 0.22183098591549297, "acc_norm_stderr": 0.02469760575535269, "acc_stderr": 0.022989742475464973}}, "versions": {"qa4mre_2013": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qnli-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qnli-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..883202c385fdfcbdb3e362737691ee0343adc430 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qnli-v0-loglikelihood @@ -0,0 +1 @@ +4281d4ff5cf1244358b0ea0220c67863c69fbade850696b43e8ff05138e01e12 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qnli-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qnli-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..31c3097605f33c489d4f2552ce3060cd7a9155e3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qnli-v0-res.json @@ -0,0 +1 @@ +{"results": {"qnli": {"acc": 0.5108914515833791, "acc_stderr": 0.00676380528502966}}, "versions": {"qnli": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qqp-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qqp-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..ecc86dc396332c1aaa8e638e5413633a504e7206 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qqp-v0-loglikelihood @@ -0,0 +1 @@ +97b551b0fc3d239aad4929a2e8e79c986891aefd9fcd19441fea0382d507889e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qqp-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qqp-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b7b31355e644bd9d6d57758ee9a454598445f7c9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/qqp-v0-res.json @@ -0,0 +1 @@ +{"results": {"qqp": {"acc": 0.49782339846648527, "acc_stderr": 0.0024866770696239894, "f1": 0.42322661288031593, "f1_stderr": 0.002695903831328166}}, "versions": {"qqp": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/race-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/race-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..5fe1ce356b49f558ce758de50809109acd9c153c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/race-v0-loglikelihood @@ -0,0 +1 @@ +bdfdfab7fa1c7af0c1e161785e347b1b8071a15cbf971f6f2a9ae8c8e845199f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/race-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/race-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..017b00669b8b60dc06947e4e78428fb429734df5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/race-v0-res.json @@ -0,0 +1 @@ +{"results": {"race": {"acc": 0.23253588516746412, "acc_stderr": 0.013074460615265295}}, "versions": {"race": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/random_insertion-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/random_insertion-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..4844e5393b8358d225f516f1a948f1deccab7840 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/random_insertion-v0-greedy_until @@ -0,0 +1 @@ +6c48baa6924f3635120f33062251c4b571b3d4e9fe46b14d91f54ddd1c857997 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/random_insertion-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/random_insertion-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9b5f507f6745120414ba5cfd39fc92eac4e48424 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/random_insertion-v0-res.json @@ -0,0 +1 @@ +{"results": {"random_insertion": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"random_insertion": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/record-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/record-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..a54fa05cd1ac551a973ff8155ddca6d868a49b42 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/record-v0-loglikelihood @@ -0,0 +1 @@ +a3e378fbde4e28f375cac1561bbfc7d7673c2af193628a774ad012d5192393aa \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/record-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/record-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..006c381372178097b36bfac48795e6fbdc242b1a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/record-v0-res.json @@ -0,0 +1 @@ +{"results": {"record": {"em": 0.1521, "em_stderr": 0.0035913575128186616, "f1": 0.1581870634920636, "f1_stderr": 0.0036146895141474576}}, "versions": {"record": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/reversed_words-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/reversed_words-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..3f28488a9028fed32a088de9a2e8c0fac4fd12de --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/reversed_words-v0-greedy_until @@ -0,0 +1 @@ +1d79fc4f0177f9624a487b9973f4e0e1d3f8404993b419a7b807a690ebbbb290 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/reversed_words-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/reversed_words-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9285ff2694c140b120aca438098daa39fc282a87 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/reversed_words-v0-res.json @@ -0,0 +1 @@ +{"results": {"reversed_words": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"reversed_words": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/rte-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/rte-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..c239923e4f3ec676961da50b3823c09872edd36d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/rte-v0-loglikelihood @@ -0,0 +1 @@ +c80ce13c8c736087f1557f8736d5d318b540ff01e4bb7f55e568890dc8b0393e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/rte-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/rte-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..10314dd047e4d7202c755fe8cfc55bc9b1edd5f8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/rte-v0-res.json @@ -0,0 +1 @@ +{"results": {"rte": {"acc": 0.5379061371841155, "acc_stderr": 0.030009848912529117}}, "versions": {"rte": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sciq-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sciq-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..25ce988773df6dd27009a4ac47357dfb7d70748e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sciq-v0-loglikelihood @@ -0,0 +1 @@ +71cbb6e2a7ac4512c3761ea801d420eb3fac49d158c7e4deaa3ab8727bea923c \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sciq-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sciq-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..7071515827af18b10a7b3607e6249ed3e7c1929e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sciq-v0-res.json @@ -0,0 +1 @@ +{"results": {"sciq": {"acc": 0.234, "acc_norm": 0.239, "acc_norm_stderr": 0.01349300044693758, "acc_stderr": 0.01339490288966001}}, "versions": {"sciq": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..024652e0a39ed0298f8f6f67453f644a68f3a367 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-greedy_until @@ -0,0 +1 @@ +b261e8885c11750ce6911bb11e8693de03d53758297c26fb14cfc1ef508862cb \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..41300bc19fd3142bfd547bf21f2b28b3ce5b21c9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-loglikelihood @@ -0,0 +1 @@ +287e87cc6878debcc80d9b6df4e2d0a74ed29068e0e0a80906c8441843a17cee \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2b370553acca14706a39428146194fa9449e09f2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v0-res.json @@ -0,0 +1 @@ +{"results": {"squad2": {"HasAns_exact": 0.0, "HasAns_f1": 0.0, "NoAns_exact": 0.0, "NoAns_f1": 0.0, "best_exact": 50.07159100480081, "best_f1": 50.07159100480081, "exact": 0.0, "f1": 0.0}}, "versions": {"squad2": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..70df2fd6ae1f59de5b6f3f6712bc2331197400c8 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-greedy_until @@ -0,0 +1 @@ +e17e3d85c1d5adaf2d6b4b752c4babc2e0b3a6e144e6de70cb3b2287e85109b8 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..2c970f7583b3d8236d9ca2e802ce6e0403b36074 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-loglikelihood @@ -0,0 +1 @@ +f5da6173402b274dc89130755c222c6ca6b2a3bacaaa4e4ab07be9322b7bad65 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..dd69f00abb989ba3d254b9a6925087e10737b8d6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/squad2-v1-res.json @@ -0,0 +1 @@ +{"results": {"squad2": {"HasAns_exact": 0.0, "HasAns_f1": 0.0, "NoAns_exact": 0.0, "NoAns_f1": 0.0, "best_exact": 50.07159100480081, "best_f1": 50.07159100480081, "exact": 0.0, "f1": 0.0}}, "versions": {"squad2": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sst-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sst-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..52050de16b54b432bdd68fae780660a035b10c0a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sst-v0-loglikelihood @@ -0,0 +1 @@ +d2ebe3a63517d1d481aa1513bebe124c57a0904554a1e95f566979cfe67b1a7f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sst-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sst-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5fe3c62a205cdd7a57acaf082f671e9ba864e5f7 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/sst-v0-res.json @@ -0,0 +1 @@ +{"results": {"sst": {"acc": 0.5172018348623854, "acc_stderr": 0.016931824425903734}}, "versions": {"sst": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/swag-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/swag-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..c8152027dc2f15319676bc32d55f32ca0bec00b5 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/swag-v0-loglikelihood @@ -0,0 +1 @@ +be4fcbad876124c4ba3c71970538a97fec0e36a9cc677c70b6c9243a7bcee0ec \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/swag-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/swag-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a1aeee972e83a41dbb7301f5a98ad5c97486402f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/swag-v0-res.json @@ -0,0 +1 @@ +{"results": {"swag": {"acc": 0.2482255323402979, "acc_norm": 0.24882535239428172, "acc_norm_stderr": 0.00305666959496067, "acc_stderr": 0.003054201832644171}}, "versions": {"swag": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/toxigen-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/toxigen-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..3074e09e14cf0763aa58e8fe2801337da805b734 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/toxigen-v0-loglikelihood @@ -0,0 +1 @@ +7fedd930bafa92b9cca615a93ba92a4413244d2b77cf3f421a186815d721e0fa \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/toxigen-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/toxigen-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..65bb7cf4596c8973ae7dd2efc60e366c65bc4800 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/toxigen-v0-res.json @@ -0,0 +1 @@ +{"results": {"toxigen": {"acc": 0.5053191489361702, "acc_norm": 0.46808510638297873, "acc_norm_stderr": 0.016283609940023203, "acc_stderr": 0.016315959984563776}}, "versions": {"toxigen": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d576c4977fc769dc56c31340f07558fefc1f1459 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v0-loglikelihood @@ -0,0 +1 @@ +f8ec05b306b9f6187c0f8117cae441fb85a7a2e4670f4f9a1a3b632b1978421a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..ab98847da6985f5c9d1e650008367ba739a1147f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v0-res.json @@ -0,0 +1 @@ +{"results": {"triviaqa": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"triviaqa": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v1-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v1-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d576c4977fc769dc56c31340f07558fefc1f1459 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v1-loglikelihood @@ -0,0 +1 @@ +f8ec05b306b9f6187c0f8117cae441fb85a7a2e4670f4f9a1a3b632b1978421a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..985f64c8e0eb3bc1dd563becf0cdf186baa172cd --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/triviaqa-v1-res.json @@ -0,0 +1 @@ +{"results": {"triviaqa": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"triviaqa": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..52156c85072e4f1a829345a4b9eef7af2c2ca059 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v0-greedy_until @@ -0,0 +1 @@ +0d7c56e1aa71ffd8f94bde28f6e8dfdd35f7aaadffa0620bd2a27704253d6c14 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5e68fa8dc6ace5fd91322aacdc74de3814832d9a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v0-res.json @@ -0,0 +1 @@ +{"results": {"truthfulqa_gen": {"bleu_acc": 0.0, "bleu_acc_stderr": 0.0, "bleu_diff": 0.0, "bleu_diff_stderr": 0.0, "bleu_max": 0.0, "bleu_max_stderr": 0.0, "bleurt_acc": 0.8372093023255814, "bleurt_acc_stderr": 0.012923696051772253, "bleurt_diff": 0.13967358205134603, "bleurt_diff_stderr": 0.00532907098769571, "bleurt_max": -1.4402793981454072, "bleurt_max_stderr": 0.0021884846359458963, "rouge1_acc": 0.0, "rouge1_acc_stderr": 0.0, "rouge1_diff": 0.0, "rouge1_diff_stderr": 0.0, "rouge1_max": 0.0, "rouge1_max_stderr": 0.0, "rouge2_acc": 0.0, "rouge2_acc_stderr": 0.0, "rouge2_diff": 0.0, "rouge2_diff_stderr": 0.0, "rouge2_max": 0.0, "rouge2_max_stderr": 0.0, "rougeL_acc": 0.0, "rougeL_acc_stderr": 0.0, "rougeL_diff": 0.0, "rougeL_diff_stderr": 0.0, "rougeL_max": 0.0, "rougeL_max_stderr": 0.0}}, "versions": {"truthfulqa_gen": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..d5261f22133a65b6968881eeb87260c5a1fca3af --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v1-greedy_until @@ -0,0 +1 @@ +1a280973bbac2b7ac29dd64dddac474fb4749585f7de893483b4034814466c67 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..30aa72f2bafd0788837ca50fa9d5c75f954daef0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_gen-v1-res.json @@ -0,0 +1 @@ +{"results": {"truthfulqa_gen": {"bleu_acc": 0.0, "bleu_acc_stderr": 0.0, "bleu_diff": 0.0, "bleu_diff_stderr": 0.0, "bleu_max": 0.0, "bleu_max_stderr": 0.0, "bleurt_acc": 0.835985312117503, "bleurt_acc_stderr": 0.012962704327492454, "bleurt_diff": 0.14077322143090107, "bleurt_diff_stderr": 0.005459888909582694, "bleurt_max": -1.4399358725752065, "bleurt_max_stderr": 0.0022126992369197133, "rouge1_acc": 0.0, "rouge1_acc_stderr": 0.0, "rouge1_diff": 0.0, "rouge1_diff_stderr": 0.0, "rouge1_max": 0.0, "rouge1_max_stderr": 0.0, "rouge2_acc": 0.0, "rouge2_acc_stderr": 0.0, "rouge2_diff": 0.0, "rouge2_diff_stderr": 0.0, "rouge2_max": 0.0, "rouge2_max_stderr": 0.0, "rougeL_acc": 0.0, "rougeL_acc_stderr": 0.0, "rougeL_diff": 0.0, "rougeL_diff_stderr": 0.0, "rougeL_max": 0.0, "rougeL_max_stderr": 0.0}}, "versions": {"truthfulqa_gen": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..51303977a9cbb311433a840af6ce636728bdb118 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v0-loglikelihood @@ -0,0 +1 @@ +226a6783976177dc9ceda5688623ff37023242eff30ddf270b886bf7b9b32228 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b12b4765cce2e95398697685a9ebb0cdada833bf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v0-res.json @@ -0,0 +1 @@ +{"results": {"truthfulqa_mc": {"mc1": 0.2141982864137087, "mc1_stderr": 0.01436214815569045, "mc2": 0.465436996173817, "mc2_stderr": 0.0048422530880316405}}, "versions": {"truthfulqa_mc": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v1-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v1-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..4bab2d1f4df241fe0cf47f22bf185d52f9b783ef --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v1-loglikelihood @@ -0,0 +1 @@ +1e07020e9cf41d46ed65312eb39d2b8e6599673d4f0d6b67c0d0eba0efb493bb \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..c1b1854c2e0abc9c4fe8096b4d45004bcc1a381b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/truthfulqa_mc-v1-res.json @@ -0,0 +1 @@ +{"results": {"truthfulqa_mc": {"mc1": 0.23255813953488372, "mc1_stderr": 0.01478915753108052, "mc2": 0.4462325560722362, "mc2_stderr": 0.004986523944692003}}, "versions": {"truthfulqa_mc": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/webqs-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/webqs-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..4d604d438db6c4cc77a43aca8d2a7f605aef6b1c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/webqs-v0-loglikelihood @@ -0,0 +1 @@ +96b218173468cc94552a0b946193bda89faba51f1bfc3e7945531f9dff8d6fe9 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/webqs-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/webqs-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9f0fdc76cab096c80a87295773054510803ba218 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/webqs-v0-res.json @@ -0,0 +1 @@ +{"results": {"webqs": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"webqs": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wic-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wic-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d27430a9a2eab0a6a5e265e249237201a4a56061 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wic-v0-loglikelihood @@ -0,0 +1 @@ +403a08da05e4c44d7e3dd3358382a7ba489c41d223e24cd1a9ed82ef1a2d004b \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wic-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wic-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..eadc573ed3d6a9b8b9bd924896ef5d719a53d5d1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wic-v0-res.json @@ -0,0 +1 @@ +{"results": {"wic": {"acc": 0.49216300940438873, "acc_stderr": 0.01980828765781383}}, "versions": {"wic": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v0-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v0-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..f09af45a38c0de097358c587420858c7a53a10aa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v0-loglikelihood_rolling @@ -0,0 +1 @@ +b6f83e6cf7535ee41b0057c3e2ec2cf7f2fa5a9119b305c479a83091d1142b2c \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9ac0c37bb5aa8cdde37bf84c61a0d020c8a03900 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v0-res.json @@ -0,0 +1 @@ +{"results": {"wikitext": {"bits_per_byte": 2.219817611605802e-05, "byte_perplexity": 1.0000221984224973, "word_perplexity": 1.000118710696617}}, "versions": {"wikitext": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v1-loglikelihood_rolling b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v1-loglikelihood_rolling new file mode 100644 index 0000000000000000000000000000000000000000..f09af45a38c0de097358c587420858c7a53a10aa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v1-loglikelihood_rolling @@ -0,0 +1 @@ +b6f83e6cf7535ee41b0057c3e2ec2cf7f2fa5a9119b305c479a83091d1142b2c \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..122098aec22e39599f1d3bffbb4bf619131d2335 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext-v1-res.json @@ -0,0 +1 @@ +{"results": {"wikitext": {"bits_per_byte": 3.202519859941674e-05, "byte_perplexity": 1.0000221984224973, "word_perplexity": 1.000118710696617}}, "versions": {"wikitext": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/winogrande-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/winogrande-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..97866f6ce45cb9a213d27310a78b7cdeab23bc9a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/winogrande-v0-loglikelihood @@ -0,0 +1 @@ +90a3eff49de9173964d46f5ed57bcf9a78a72dd1bfe0e5323b25cebb40b49ea9 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/winogrande-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/winogrande-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..9fa7903a56d2fb48abcd215bb587bc69c00f4aa6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/winogrande-v0-res.json @@ -0,0 +1 @@ +{"results": {"winogrande": {"acc": 0.516179952644041, "acc_stderr": 0.014045126130978606}}, "versions": {"winogrande": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-en-fr-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-en-fr-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..6d48d5579e95eb72bdc6c4dc8b4149e5f495b55e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-en-fr-v0-greedy_until @@ -0,0 +1 @@ +368ae7eec0f902b5123f2d5197caa5109a23942011c53fe68d9eaeee20180e46 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-en-fr-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-en-fr-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..1aa13f02854c8eec0591be980486afe48d7f97a9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-en-fr-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt14-en-fr": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.011284118461117099, "chrf_stderr": 7.340651275964445e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt14-en-fr": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..7249d39990f9aea60634b07c975f735983bade89 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-greedy_until @@ -0,0 +1 @@ +c1d9f7283755fbdd7ecd6cc4278b0ac25a80ac256b7071ea5f839ccd038e5974 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..5261876f55a69dcaf33b3842690f81c12eb42f3a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt14-fr-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.01275083169440515, "chrf_stderr": 8.45474998563806e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt14-fr-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-de-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-de-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..75f1072b6e7f2bdd9ecd98987c86fefd3375fb6d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-de-en-v0-greedy_until @@ -0,0 +1 @@ +d30e23e38d9a45b9c31e1dfd14b58d0b7020df4b9c8a1c697aa6bc5fba8ce08a \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-de-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-de-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..826e0382abb32da67ac0dd0b271527b40fd3b6ae --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-de-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt16-de-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.013700416764482968, "chrf_stderr": 0.00016071651360909355, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt16-de-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-de-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-de-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..45eaaaca8c5892944b1b9c9af0c469e3c63e4881 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-de-v0-greedy_until @@ -0,0 +1 @@ +d71e2074af3770e9b29ac561caf2e1c29ad6b0dc50ec2e7bcc5501747b11f0da \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-de-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-de-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..88bee7ffa69b1bf7accdd56a3870f61d4c0453da --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-de-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt16-en-de": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.010909486120840577, "chrf_stderr": 0.000122611124711072, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt16-en-de": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-ro-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-ro-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..291492556e5182600291565c640a463da7f00616 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-ro-v0-greedy_until @@ -0,0 +1 @@ +4be7fdda313394f19b5995b00ada1dfa3bb158ee1f020ef8d07ecea260fa60b2 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-ro-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-ro-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..babb8d2d74fb5585cf9578f8b1dc8be3dde43f63 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-en-ro-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt16-en-ro": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.012004814364156886, "chrf_stderr": 6.424423961332661e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt16-en-ro": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..fbcac1b7e3887c6ffa8fd6da6e21595fb0c49a4f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-greedy_until @@ -0,0 +1 @@ +d1b7c50751b0d5d7470b7f49f2bab9d09792c91460fc92cc34f06617013d7c65 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..267763793d5fa5a16c41cbcdd9eb7b134cd34cea --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt16-ro-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.01262029828861831, "chrf_stderr": 0.00014507496111350828, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt16-ro-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-cs-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-cs-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..7bcf240b7090e406259d4bfc090d1eb22ec6e291 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-cs-en-v0-greedy_until @@ -0,0 +1 @@ +bfead9efdb1b2402a414c55929c8d8f956585f938a35466931d44e81d89cfe00 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-cs-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-cs-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..70c80afe5bd10baabdcb507faa385db124c1f42e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-cs-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-cs-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.006212086270964023, "chrf_stderr": 0.0001119165191795531, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-cs-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..c02fb9875d5354fdb0892b7493a822ee4af9d6c2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-en-v0-greedy_until @@ -0,0 +1 @@ +d13b5a6915ca86ac6c6ebc50d9be0d0be3dfca600c12e896df53190d875de74d \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..790424fe4f226224642530ba7fd53a59eec4caa0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-de-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.006703243310670055, "chrf_stderr": 0.0001292711927988445, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-de-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-fr-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-fr-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..7cb9424082836f0d56afe809cf44c78fc844d993 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-fr-v0-greedy_until @@ -0,0 +1 @@ +7f197bc281d6dbf9425900ef0dee7175021c43e355050f149f43b161c52bf0b0 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-fr-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-fr-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..79a0d12fe6f5750749e56dc3919283f71d021fa0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-de-fr-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-de-fr": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.011897164096796364, "chrf_stderr": 0.00010158164726118333, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-de-fr": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..d14fc4939aecb7bb40458c34954c1242d9f20501 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-greedy_until @@ -0,0 +1 @@ +5a34e6863bf6965afd31653de50bac5fecf58db65dbaba46921504a2b7463786 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..2ba9db70d3579ff23ee70c3b16eb92d7d87144e6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-cs": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.009879653442394573, "chrf_stderr": 8.210293331159994e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-cs": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-de-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-de-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..c4078efd996d010eac102fe23de50fdbbe0310d9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-de-v0-greedy_until @@ -0,0 +1 @@ +b6e9c305766ea23ce1027309f83c6d4c2ce8948d70b63a7858586ca34050d7fb \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-iu-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-iu-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..d26bb4f92a03612cf3a4170733973e39870164b7 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-iu-v0-greedy_until @@ -0,0 +1 @@ +f5688199890a48f73f2cc04a2152e35190f0e0ddd40e629fa24ee39d423ea389 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-iu-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-iu-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..22f042eb4eba6e6e662e46807232679782f7b6b9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-iu-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-iu": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.00011803644548940443, "chrf_stderr": 2.175287038623409e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-iu": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..9777002c79830918a3939ec6978d606ae967ffe6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v1-greedy_until @@ -0,0 +1 @@ +7fe61f5847a51e93e97c84b39f4420978727754e4b6cf636a27851c615857530 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..be5e56abcf2253276d405dae64758b9cab09f3e4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v1-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-ja": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 4.1305928226819116e-05, "chrf_stderr": 2.0455354158878388e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-ja": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-km-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-km-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..ddce46a79fdcb08c3eee1a534c11fc4dd796be53 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-km-v0-greedy_until @@ -0,0 +1 @@ +eb5365c46f22ffec9a157991627d6e1fd1117fccffaedfc73619e93bafb5a408 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-km-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-km-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..e5ee2e9be911cda88b6445715b833e1a0dbf92dd --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-km-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-km": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 1.9008351315007364e-05, "chrf_stderr": 7.136657625458525e-06, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-km": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-pl-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-pl-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..bd431d61c479beb686d39be21905fdb0beb7781e --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-pl-v0-greedy_until @@ -0,0 +1 @@ +952f02575d4936d93c4d2808d86c4bf5f1f3a0901212acee6cbc1f9cbd30d39e \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-pl-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-pl-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..13bfd5b552b92b771266666dd5fe5b9496064051 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-pl-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-pl": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.009006977773147825, "chrf_stderr": 0.00023387733367766675, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-pl": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ps-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ps-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..fcfb51f05320490d089cc8fbd4127a987bc868c0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ps-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-ps": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 2.1193813610582323e-06, "chrf_stderr": 2.113911466119111e-06, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-ps": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ru-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ru-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..d21d39ac9f9616bda1e21d1ba5bd63fdb542a7aa --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ru-v0-greedy_until @@ -0,0 +1 @@ +a1613831f69c1679a54670092af40ce76617b79d7cc837984803b0fc52bb8bde \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-fr-de-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-fr-de-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..7353ad4475b3d292bfd64e6dcb41972d697c34da --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-fr-de-v0-greedy_until @@ -0,0 +1 @@ +8a4b65c59dcac6591d46261909ee92ebcf41c19ee7442b12842302b2d8aeb36f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-iu-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-iu-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..e94cac8876d9d04c883b5ad5810884af7faa436c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-iu-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-iu-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.012204628007572778, "chrf_stderr": 8.944407532175802e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-iu-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-km-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-km-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4f6dc98604bdeed7b87806094a6ffc3b0cbbfec4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-km-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-km-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.015142474534585969, "chrf_stderr": 0.0001518735048829897, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-km-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ps-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ps-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..7776c5952383a6254943869dad8fddb50e50e987 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ps-en-v0-greedy_until @@ -0,0 +1 @@ +c3976465e3709b4bc371175cc1494c69fe096ea4ba7d114da779d2baa0a47466 \ No newline at end of file diff --git a/testbed/Project-MONAI__MONAI/.github/ISSUE_TEMPLATE/bug_report.md b/testbed/Project-MONAI__MONAI/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..d57bfd1a6ebf7b88cdcf8022032a59f8944b4767 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Install '....' +3. Run commands '....' + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Environment (please complete the following information):** + - OS + - Python version + - MONAI version [e.g. git commit hash] + - CUDA/cuDNN version + - GPU models and configuration + +**Additional context** +Add any other context about the problem here. diff --git a/testbed/Project-MONAI__MONAI/.github/ISSUE_TEMPLATE/feature_request.md b/testbed/Project-MONAI__MONAI/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..bbcbbe7d61558adde3cbfd0c7a63a67c27ed6d30 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/testbed/Project-MONAI__MONAI/.github/workflows/pythonapp.yml b/testbed/Project-MONAI__MONAI/.github/workflows/pythonapp.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea43b66fe15eb1e17a54dd5534ea294722fa906b --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/workflows/pythonapp.yml @@ -0,0 +1,270 @@ +name: build + +on: + # quick tests for every pull request + push: + branches: + - master + pull_request: + +jobs: + # caching of these jobs: + # - docker-20-03-py3-pip- (shared) + # - ubuntu py37 pip- + # - os-latest-pip- (shared) + flake8-py3: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-${{ steps.pip-cache.outputs.datew }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip wheel + python -m pip install -r requirements-dev.txt + - name: Lint and type check + run: | + # clean up temporary files + $(pwd)/runtests.sh --clean + # Git hub actions have 2 cores, so parallize pytype + $(pwd)/runtests.sh --nounittests --codeformat -j 2 + + quick-py3: # full dependencies installed + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, macOS-latest, ubuntu-latest] + timeout-minutes: 20 + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.x + uses: actions/setup-python@v1 + with: + python-version: '3.x' + - name: Prepare pip wheel + run: | + which python + python -m pip install --upgrade pip wheel + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + echo "::set-output name=dir::$(pip cache dir)" + shell: bash + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ${{ steps.pip-cache.outputs.dir }} + key: ${{ matrix.os }}-latest-pip-${{ steps.pip-cache.outputs.datew }} + - if: runner.os == 'windows' + name: Install torch cpu from pytorch.org (Windows only) + run: | + python -m pip install torch==1.4 -f https://download.pytorch.org/whl/cpu/torch_stable.html + python -m pip install torchvision==0.5.0 + # min. requirements for windows instances + python -c "f=open('requirements-dev.txt', 'r'); txt=f.readlines(); f.close(); print(txt); f=open('requirements-dev.txt', 'w'); f.writelines(txt[1:12]); f.close()" + - name: Install the dependencies + run: | + python -m pip install torch==1.4 + python -m pip install torchvision==0.5.0 + cat "requirements-dev.txt" + python -m pip install -r requirements-dev.txt + python -m pip list + python setup.py develop # compile the cpp extensions + - name: Run quick tests (CPU ${{ runner.os }}) + run: | + python -c 'import torch; print(torch.__version__); print(torch.rand(5,3))' + python -m unittest -v + env: + QUICKTEST: True + + GPU-quick-py3: # GPU with full dependencies + strategy: + matrix: + environment: + - "PT15+CUDA101" + - "PT16+CUDA101" + - "PT15+CUDA102" + - "PT16+CUDA102" + - "PT16+CUDA110" + include: + - environment: PT15+CUDA101 + pytorch: "torch==1.5.0+cu101 torchvision==0.6.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html" + base: "nvcr.io/nvidia/cuda:10.1-devel-ubuntu18.04" + - environment: PT16+CUDA101 + pytorch: "torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html" + base: "nvcr.io/nvidia/cuda:10.1-devel-ubuntu18.04" + - environment: PT15+CUDA102 + pytorch: "torch==1.5.0 torchvision==0.6.0" + base: "nvcr.io/nvidia/cuda:10.2-devel-ubuntu18.04" + - environment: PT16+CUDA102 + pytorch: "torch torchvision" + base: "nvcr.io/nvidia/cuda:10.2-devel-ubuntu18.04" + - environment: PT16+CUDA110 + # we explicitly set pytorch to -h to avoid pip install error + pytorch: "-h" + base: "nvcr.io/nvidia/pytorch:20.07-py3" + container: + image: ${{ matrix.base }} + options: --gpus all + runs-on: [self-hosted, linux, x64] + steps: + - uses: actions/checkout@v2 + - name: apt install + run: | + if [ ${{ matrix.environment }} != "PT16+CUDA110" ]; then \ + PYVER=3.6 PYSFX=3 DISTUTILS=python3-distutils && \ + apt-get update && apt-get install -y --no-install-recommends \ + curl \ + pkg-config \ + python$PYVER \ + python$PYVER-dev \ + python$PYSFX-pip \ + $DISTUTILS \ + rsync \ + swig \ + unzip \ + zip \ + zlib1g-dev \ + libboost-locale-dev \ + libboost-program-options-dev \ + libboost-system-dev \ + libboost-thread-dev \ + libboost-test-dev \ + libgoogle-glog-dev \ + libjsoncpp-dev \ + cmake && \ + rm -rf /var/lib/apt/lists/* && \ + export PYTHONIOENCODING=utf-8 LC_ALL=C.UTF-8 && \ + rm -f /usr/bin/python && \ + rm -f /usr/bin/python`echo $PYVER | cut -c1-1` && \ + ln -s /usr/bin/python$PYVER /usr/bin/python && \ + ln -s /usr/bin/python$PYVER /usr/bin/python`echo $PYVER | cut -c1-1` && + curl -O https://bootstrap.pypa.io/get-pip.py && \ + python get-pip.py && \ + rm get-pip.py ; fi + - name: Install dependencies + run: | + which python + python -m pip install --upgrade pip wheel + python -m pip install ${{ matrix.pytorch }} + python -m pip install -r requirements-dev.txt + - name: Run quick tests (GPU) + run: | + python -m pip list + nvidia-smi + export CUDA_VISIBLE_DEVICES=$(python -m tests.utils) + echo $CUDA_VISIBLE_DEVICES + python -c "import torch; print(torch.__version__); print('{} of GPUs available'.format(torch.cuda.device_count()))" + python -c 'import torch; print(torch.rand(5,3, device=torch.device("cuda:0")))' + ./runtests.sh --quick + coverage xml + - name: Upload coverage + uses: codecov/codecov-action@v1 + with: + file: ./coverage.xml + + packaging: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Set up Python 3.x + uses: actions/setup-python@v1 + with: + python-version: '3.x' + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-${{ steps.pip-cache.outputs.datew }} + - name: Install dependencies + run: | + python -m pip install --user --upgrade pip setuptools wheel twine + # install the latest pytorch for testing + # however, "pip install monai*.tar.gz" will build cpp/cuda with an isolated + # fresh torch installation according to pyproject.toml + python -m pip install torch>=1.4 torchvision + - name: Test source archive and wheel file + run: | + git fetch --depth=1 origin +refs/tags/*:refs/tags/* + root_dir=$PWD + echo "$root_dir" + set -e + + # build tar.gz and wheel + python setup.py check -m -s + python setup.py sdist bdist_wheel + python -m twine check dist/* + + # move packages to a temp dir + tmp_dir=$(mktemp -d) + cp dist/monai* "$tmp_dir" + rm -r build dist monai.egg-info + cd "$tmp_dir" + ls -al + + # install from wheel + python -m pip install monai*.whl + python -c 'import monai; monai.config.print_config()' 2>&1 | grep -iv "unknown" + python -c 'import monai; print(monai.__file__)' + python -m pip uninstall -y monai + rm monai*.whl + + # install from tar.gz + python -m pip install monai*.tar.gz + python -c 'import monai; monai.config.print_config()' 2>&1 | grep -iv "unknown" + python -c 'import monai; print(monai.__file__)' + python -m pip uninstall -y monai + rm monai*.tar.gz + + # clean up + cd "$root_dir" + rm -r "$tmp_dir" + + build-docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-${{ steps.pip-cache.outputs.datew }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip wheel + python -m pip install -r docs/requirements.txt + - name: Make html + run: | + cd docs/ + make html diff --git a/testbed/Project-MONAI__MONAI/.github/workflows/release.yml b/testbed/Project-MONAI__MONAI/.github/workflows/release.yml new file mode 100644 index 0000000000000000000000000000000000000000..2058be8aec05f534f4e66e5c537f814b158b9ea4 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/workflows/release.yml @@ -0,0 +1,79 @@ +name: release + +on: + push: + branches: + - 'releases/*' + tags: + - '*' + +jobs: + packaging: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.6, 3.7, 3.8] + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + - name: Install setuptools + run: | + python -m pip install --user --upgrade setuptools wheel + - name: Build and test source archive and wheel file + run: | + git fetch --depth=1 origin +refs/tags/*:refs/tags/* + root_dir=$PWD + echo "$root_dir" + set -e + + # build tar.gz and wheel + python setup.py sdist bdist_wheel --build-number $(date +'%Y%m%d%H%M') + tmp_dir=$(mktemp -d) + cp dist/monai* "$tmp_dir" + cd "$tmp_dir" + ls -al + + # install from wheel + python -m pip install monai*.whl + python -c 'import monai; monai.config.print_config()' 2>&1 | grep -iv "unknown" + python -c 'import monai; print(monai.__file__)' + python -m pip uninstall -y monai + rm monai*.whl + + # install from tar.gz + python -m pip install monai*.tar.gz + python -c 'import monai; monai.config.print_config()' 2>&1 | grep -iv "unknown" + python -c 'import monai; print(monai.__file__)' + python -m pip uninstall -y monai + rm monai*.tar.gz + + # clean up + cd "$root_dir" + rm -r "$tmp_dir" + + - if: matrix.python-version == '3.8' && startsWith(github.ref, 'refs/tags/') + name: Upload artifacts + uses: actions/upload-artifact@v1 + with: + name: dist + path: dist/ + + - if: matrix.python-version == '3.8' && startsWith(github.ref, 'refs/tags/') + name: Check artifacts + run: | + ls -al dist/ + rm dist/monai*.tar.gz + ls -al dist/ + + - if: matrix.python-version == '3.8' && startsWith(github.ref, 'refs/tags/') + name: Publish to Test PyPI + uses: pypa/gh-action-pypi-publish@master + with: + password: ${{ secrets.TEST_PYPI }} + repository_url: https://test.pypi.org/legacy/ + diff --git a/testbed/Project-MONAI__MONAI/.github/workflows/setupapp.yml b/testbed/Project-MONAI__MONAI/.github/workflows/setupapp.yml new file mode 100644 index 0000000000000000000000000000000000000000..aa6e72074a7af4a388aaf10ea499a3fede582cfd --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/workflows/setupapp.yml @@ -0,0 +1,181 @@ +name: deploy + +on: + # master only tests + push: + branches: + - master + +jobs: + # caching of these jobs: + # - docker-20-03-py3-pip- (shared) + # - ubuntu py36 37 38-pip- + # - os-latest-pip (shared) + coverage-py3: + container: + image: nvcr.io/nvidia/pytorch:20.03-py3 + options: --gpus all + runs-on: [self-hosted, linux, x64] + steps: + - uses: actions/checkout@v2 + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ~/.cache/pip + key: docker-20-03-py3-pip-${{ steps.pip-cache.outputs.datew }} + - name: Install the dependencies + run: | + which python + python -m pip install --upgrade pip wheel + python -m pip uninstall -y torch torchvision + python -m pip install torch==1.4 torchvision==0.5.0 + python -m pip install -r requirements-dev.txt + - name: Run unit tests report coverage + run: | + python -m pip list + nvidia-smi + export CUDA_VISIBLE_DEVICES=$(python -m tests.utils) + echo $CUDA_VISIBLE_DEVICES + python -c "import torch; print(torch.__version__); print('{} of GPUs available'.format(torch.cuda.device_count()))" + python -c 'import torch; print(torch.rand(5,3, device=torch.device("cuda:0")))' + ./runtests.sh --coverage + coverage xml + - name: Upload coverage + uses: codecov/codecov-action@v1 + with: + fail_ci_if_error: true + file: ./coverage.xml + + test-py3x: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.6, 3.7, 3.8] + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ~/.cache/pip + key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ steps.pip-cache.outputs.datew }} + - name: Install the dependencies + run: | + python -m pip install --upgrade pip wheel + python -m pip install torch==1.4 torchvision==0.5.0 + python -m pip install -r requirements-dev.txt + - name: Run quick tests CPU ubuntu + run: | + python -m pip list + python -c 'import torch; print(torch.__version__); print(torch.rand(5,3))' + ./runtests.sh --quick + coverage xml + - name: Upload coverage + uses: codecov/codecov-action@v1 + with: + fail_ci_if_error: false + file: ./coverage.xml + + min-dep-py3: # min dependencies installed + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, macOS-latest, ubuntu-latest] + timeout-minutes: 20 + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.x + uses: actions/setup-python@v1 + with: + python-version: '3.x' + - name: Prepare pip wheel + run: | + which python + python -m pip install --upgrade pip wheel + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + echo "::set-output name=dir::$(pip cache dir)" + shell: bash + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ${{ steps.pip-cache.outputs.dir }} + key: ${{ matrix.os }}-latest-pip-${{ steps.pip-cache.outputs.datew }} + - if: runner.os == 'windows' + name: Install torch cpu from pytorch.org (Windows only) + run: | + python -m pip install torch==1.4 -f https://download.pytorch.org/whl/cpu/torch_stable.html + python -m pip install torchvision==0.5.0 + - name: Install the dependencies + run: | + # min. requirements for windows instances + python -m pip install torch==1.4 torchvision==0.5.0 + python -c "f=open('requirements-dev.txt', 'r'); txt=f.readlines(); f.close(); print(txt); f=open('requirements-dev.txt', 'w'); f.writelines(txt[1:5]); f.close()" + cat "requirements-dev.txt" + python -m pip install -r requirements-dev.txt + python -m pip list + python setup.py develop # to compile extensions using the system native torch + - name: Run quick tests (CPU ${{ runner.os }}) + run: | + python -c 'import torch; print(torch.__version__); print(torch.rand(5,3))' + python -m tests.min_tests + env: + QUICKTEST: True + + install: + runs-on: ubuntu-latest + steps: + - name: Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: cache weekly timestamp + id: pip-cache + run: | + echo "::set-output name=datew::$(date '+%Y-%V')" + - name: cache for pip + uses: actions/cache@v2 + id: cache + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-${{ steps.pip-cache.outputs.datew }} + - name: Install the default branch + run: | + pip install git+https://github.com/Project-MONAI/MONAI#egg=MONAI + - name: Import + run: | + python -c 'import monai; monai.config.print_config()' + - name: Uninstall + run: | + pip uninstall -y monai + + docker: + container: + image: docker://projectmonai/monai:latest + runs-on: [self-hosted, linux, x64] + steps: + - name: Import + run: | + python -c 'import monai; monai.config.print_config()' + cd /opt/monai + ls -al + ngc --version diff --git a/testbed/Project-MONAI__MONAI/docs/Makefile b/testbed/Project-MONAI__MONAI/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..1a3b22d020a7767e1edfde0c6710d69b658788af --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/Makefile @@ -0,0 +1,23 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +clean: + rm -rf build/ diff --git a/testbed/Project-MONAI__MONAI/docs/_static/custom.css b/testbed/Project-MONAI__MONAI/docs/_static/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..45875841f8545e6f17dc1569fc2a5fbc885c6d15 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/_static/custom.css @@ -0,0 +1,2 @@ +@import url('https://fonts.googleapis.com/css?family=Lekton:700|Roboto&display=swap'); +body{font-family:'Roboto',sans-serif;}.wy-side-nav-search>div.version{color:#222;}a:visited{color:#0285b0;}.wy-menu-vertical a:visited{color:#d9d9d9;}.wy-menu-vertical p.caption{color:#7cccc7;} diff --git a/testbed/Project-MONAI__MONAI/docs/requirements.txt b/testbed/Project-MONAI__MONAI/docs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3969823f8cbffe36bdf2447f2a698392d693161d --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/requirements.txt @@ -0,0 +1,20 @@ +-f https://download.pytorch.org/whl/cpu/torch-1.4.0%2Bcpu-cp37-cp37m-linux_x86_64.whl +torch>=1.4.0 +pytorch-ignite==0.3.0 +numpy>=1.17 +itk +nibabel +parameterized +scikit-image>=0.14.2 +tensorboard +commonmark==0.9.1 +recommonmark==0.6.0 +Sphinx==2.3.1 +sphinx-rtd-theme==0.4.3 +sphinxcontrib-applehelp==1.0.1 +sphinxcontrib-devhelp==1.0.1 +sphinxcontrib-htmlhelp==1.0.2 +sphinxcontrib-jsmath==1.0.1 +sphinxcontrib-qthelp==1.0.2 +sphinxcontrib-serializinghtml==1.1.3 +sphinx-autodoc-typehints==1.10.3 diff --git a/testbed/Project-MONAI__MONAI/docs/source/apidocs/modules.rst b/testbed/Project-MONAI__MONAI/docs/source/apidocs/modules.rst new file mode 100644 index 0000000000000000000000000000000000000000..b8373368ecf4e9a373ec269284a8793737e6fc26 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/apidocs/modules.rst @@ -0,0 +1,9 @@ +:orphan: + +monai +===== + +.. toctree:: + :maxdepth: 4 + + monai diff --git a/testbed/Project-MONAI__MONAI/docs/source/apidocs/monai.rst b/testbed/Project-MONAI__MONAI/docs/source/apidocs/monai.rst new file mode 100644 index 0000000000000000000000000000000000000000..de36f29e4a147df40d5f44e6aa6e9a248fbbaff4 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/apidocs/monai.rst @@ -0,0 +1,10 @@ +monai package +============= + +Module contents +--------------- + +.. automodule:: monai + :members: + :undoc-members: + :show-inheritance: diff --git a/testbed/Project-MONAI__MONAI/docs/source/apps.rst b/testbed/Project-MONAI__MONAI/docs/source/apps.rst new file mode 100644 index 0000000000000000000000000000000000000000..8b02598343902c51167545b0f2537312cd3c1e34 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/apps.rst @@ -0,0 +1,27 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _apps: + +Applications +============ +.. currentmodule:: monai.apps + +`Datasets` +---------- + +.. autoclass:: MedNISTDataset + :members: + +.. autoclass:: DecathlonDataset + :members: + +`Utilities` +----------- + +.. autofunction:: check_md5 + +.. autofunction:: download_url + +.. autofunction:: extractall + +.. autofunction:: download_and_extract diff --git a/testbed/Project-MONAI__MONAI/docs/source/conf.py b/testbed/Project-MONAI__MONAI/docs/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..6272379039d53234d9b81cac65c4227a0844c34c --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/conf.py @@ -0,0 +1,133 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +import subprocess + +sys.path.insert(0, os.path.abspath("..")) +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) +print(sys.path) + +import monai # noqa: E402 + +# -- Project information ----------------------------------------------------- +project = "MONAI" +copyright = "2020 MONAI Consortium" +author = "MONAI Contributors" + +# The full version, including alpha/beta/rc tags +short_version = monai.__version__.split("+")[0] +release = short_version +version = short_version + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [ + "transforms", + "networks", + "metrics", + "engines", + "data", + "apps", + "config", + "handlers", + "losses", + "visualize", + "utils", + "inferers", +] + + +def generate_apidocs(*args): + """Generate API docs automatically by trawling the available modules""" + module_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "monai")) + output_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "apidocs")) + apidoc_command_path = "sphinx-apidoc" + if hasattr(sys, "real_prefix"): # called from a virtualenv + apidoc_command_path = os.path.join(sys.prefix, "bin", "sphinx-apidoc") + apidoc_command_path = os.path.abspath(apidoc_command_path) + print(f"output_path {output_path}") + print(f"module_path {module_path}") + subprocess.check_call( + [apidoc_command_path, "-e"] + + ["-o", output_path] + + [module_path] + + [os.path.join(module_path, p) for p in exclude_patterns] + ) + + +def setup(app): + # Hook to allow for automatic generation of API docs + # before doc deployment begins. + app.connect("builder-inited", generate_apidocs) + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +source_suffix = {".rst": "restructuredtext", ".txt": "restructuredtext", ".md": "markdown"} + +extensions = [ + "recommonmark", + "sphinx.ext.intersphinx", + "sphinx.ext.mathjax", + "sphinx.ext.napoleon", + "sphinx.ext.autodoc", + "sphinx.ext.viewcode", + "sphinx.ext.autosectionlabel", + "sphinx_autodoc_typehints", +] + +autoclass_content = "both" +add_module_names = True +autosectionlabel_prefix_document = True +napoleon_use_param = True +set_type_checking_flag = True + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "sphinx_rtd_theme" +# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] +html_theme_options = { + "collapse_navigation": True, + "display_version": True, + "sticky_navigation": True, # Set to False to disable the sticky nav while scrolling. + "logo_only": True, # if we have a html_logo below, this shows /only/ the logo with no title text + "style_nav_header_background": "#FBFBFB", +} +html_context = { + "display_github": True, + "github_user": "Project-MONAI", + "github_repo": "MONAI", + "github_version": "master", + "conf_py_path": "/docs/", +} +html_scaled_image_link = False +html_show_sourcelink = True +html_favicon = "../images/favicon.ico" +html_logo = "../images/MONAI-logo-color.png" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["../_static"] +html_css_files = ["custom.css"] diff --git a/testbed/Project-MONAI__MONAI/docs/source/data.rst b/testbed/Project-MONAI__MONAI/docs/source/data.rst new file mode 100644 index 0000000000000000000000000000000000000000..ef05c4c0e49e516a49a09d3ab10c2f85d7507c18 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/data.rst @@ -0,0 +1,118 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _data: + +Data +==== + +Generic Interfaces +------------------ +.. currentmodule:: monai.data + +`Dataset` +~~~~~~~~~ +.. autoclass:: Dataset + :members: + :special-members: __getitem__ + +`PersistentDataset` +~~~~~~~~~~~~~~~~~~~ +.. autoclass:: PersistentDataset + :members: + :special-members: __getitem__ + +`CacheDataset` +~~~~~~~~~~~~~~ +.. autoclass:: CacheDataset + :members: + :special-members: __getitem__ + +`SmartCacheDataset` +~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SmartCacheDataset + :members: + :special-members: __getitem__ + +`ZipDataset` +~~~~~~~~~~~~ +.. autoclass:: ZipDataset + :members: + :special-members: __getitem__ + +`ArrayDataset` +~~~~~~~~~~~~~~ +.. autoclass:: ArrayDataset + :members: + :special-members: __getitem__ + + +Patch-based dataset +------------------- + +`GridPatchDataset` +~~~~~~~~~~~~~~~~~~ +.. autoclass:: GridPatchDataset + :members: + + +Image reader +------------ + +ITKReader +~~~~~~~~~ +.. autoclass:: ITKReader + :members: + +NibabelReader +~~~~~~~~~~~~~ +.. autoclass:: NibabelReader + :members: + + +Nifti format handling +--------------------- + +Reading +~~~~~~~ +.. autoclass:: monai.data.NiftiDataset + :members: + +Writing Nifti +~~~~~~~~~~~~~ +.. autoclass:: monai.data.NiftiSaver + :members: + +.. autofunction:: monai.data.write_nifti + + +PNG format handling +------------------- + +Writing PNG +~~~~~~~~~~~ +.. autoclass:: monai.data.PNGSaver + :members: + +.. autofunction:: monai.data.write_png + + +Synthetic +--------- +.. automodule:: monai.data.synthetic + :members: + + +Utilities +--------- +.. automodule:: monai.data.utils + :members: + + +Decathalon Datalist +~~~~~~~~~~~~~~~~~~~ +.. autofunction:: monai.data.load_decathalon_datalist + + +DataLoader +~~~~~~~~~~ +.. autofunction:: monai.data.DataLoader diff --git a/testbed/Project-MONAI__MONAI/docs/source/engines.rst b/testbed/Project-MONAI__MONAI/docs/source/engines.rst new file mode 100644 index 0000000000000000000000000000000000000000..cc0ec3c6594f51a5a82edc54382f2900a3a72b9a --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/engines.rst @@ -0,0 +1,56 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _engines: + +Engines +======= + +Multi-GPU data parallel +----------------------- + +.. automodule:: monai.engines.multi_gpu_supervised_trainer + :members: + + +Workflows +--------- + +.. automodule:: monai.engines.workflow +.. currentmodule:: monai.engines.workflow + +`Workflow` +~~~~~~~~~~ +.. autoclass:: Workflow + :members: + +.. currentmodule:: monai.engines + +`Trainer` +~~~~~~~~~ +.. autoclass:: Trainer + :members: + +`SupervisedTrainer` +~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SupervisedTrainer + :members: + +`GanTrainer` +~~~~~~~~~~~~ +.. autoclass:: GanTrainer + :members: + +`Evaluator` +~~~~~~~~~~~ +.. autoclass:: Evaluator + :members: + +`SupervisedEvaluator` +~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SupervisedEvaluator + :members: + +`EnsembleEvaluator` +~~~~~~~~~~~~~~~~~~~ +.. autoclass:: EnsembleEvaluator + :members: diff --git a/testbed/Project-MONAI__MONAI/docs/source/handlers.rst b/testbed/Project-MONAI__MONAI/docs/source/handlers.rst new file mode 100644 index 0000000000000000000000000000000000000000..915b1db91ad1cf3e2634d96c318aa0e2e4346bc4 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/handlers.rst @@ -0,0 +1,75 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _handlers: + +Event handlers +============== +.. currentmodule:: monai.handlers + +Model checkpoint loader +----------------------- +.. autoclass:: CheckpointLoader + :members: + +Model checkpoint saver +---------------------- +.. autoclass:: CheckpointSaver + :members: + +CSV saver +--------- +.. autoclass:: ClassificationSaver + :members: + + +Mean Dice metrics handler +------------------------- +.. autoclass:: MeanDice + :members: + + +ROC AUC metrics handler +----------------------- +.. autoclass:: ROCAUC + :members: + + +Metric logger +------------- +.. autoclass:: MetricLogger + :members: + + +Segmentation saver +------------------ +.. autoclass:: SegmentationSaver + :members: + + +Training stats handler +---------------------- +.. autoclass:: StatsHandler + :members: + + +Tensorboard handler +------------------- +.. autoclass:: TensorBoardStatsHandler + :members: + + +LR Schedule handler +------------------- +.. autoclass:: LrScheduleHandler + :members: + + +Validation handler +------------------ +.. autoclass:: ValidationHandler + :members: + +SmartCache handler +------------------ +.. autoclass:: SmartCacheHandler + :members: diff --git a/testbed/Project-MONAI__MONAI/docs/source/highlights.md b/testbed/Project-MONAI__MONAI/docs/source/highlights.md new file mode 100644 index 0000000000000000000000000000000000000000..28eb18580fa06353480bc64f98aa96b6e768e64c --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/highlights.md @@ -0,0 +1,229 @@ +# Modules in v0.2.0 + +MONAI aims at supporting deep learning in medical image analysis at multiple granularities. +This figure shows a typical example of the end-to-end workflow in medical deep learning area: +![image](../images/end_to_end.png) + +## MONAI architecture +The design principle of MONAI is to provide flexible and light APIs for users with varying expertise. +1. All the core components are independent modules, which can be easily integrated into any existing PyTorch programs. +2. Users can leverage the workflows in MONAI to quickly set up a robust training or evaluation program for research experiments. +3. Rich examples and demos are provided to demonstrate the key features. +4. Researchers contribute implementations based on the state-of-the-art for the latest research challenges, including COVID-19 image analysis, Model Parallel, etc. + +The overall architecture and modules are shown in the following figure: +![image](../images/arch_modules_v0.2.png) +The rest of this page provides more details for each module. + +* [Data I/O, processing and augmentation](#medical-image-data-io-processing-and-augmentation) +* [Datasets](#datasets) +* [Loss functions](#losses) +* [Network architectures](#network-architectures) +* [Evaluation](#evaluation) +* [Visualization](#visualization) +* [Result writing](#result-writing) +* [Workflows](#workflows) +* [Research](#research) + +## Medical image data I/O, processing and augmentation +Medical images require highly specialized methods for I/O, preprocessing, and augmentation. Medical images are often in specialized formats with rich meta-information, and the data volumes are often high-dimensional. These require carefully designed manipulation procedures. The medical imaging focus of MONAI is enabled by powerful and flexible image transformations that facilitate user-friendly, reproducible, optimized medical data pre-processing pipelines. + +### 1. Transforms support both Dictionary and Array format data +- The widely used computer vision packages (such as ``torchvision``) focus on spatially 2D array image processing. MONAI provides more domain-specific transformations for both spatially 2D and 3D and retains the flexible transformation "compose" feature. +- As medical image preprocessing often requires additional fine-grained system parameters, MONAI provides transforms for input data encapsulated in python dictionaries. Users can specify the keys corresponding to the expected data fields and system parameters to compose complex transformations. + +There is a rich set of transforms in six categories: Crop & Pad, Intensity, IO, Post-processing, Spatial, and Utilities. For more details, please visit [all the transforms in MONAI](https://docs.monai.io/en/latest/transforms.html). + +### 2. Medical specific transforms +MONAI aims at providing a comprehensive medical image specific +transformations. These currently include, for example: +- `LoadNifti`: Load Nifti format file from provided path +- `Spacing`: Resample input image into the specified `pixdim` +- `Orientation`: Change the image's orientation into the specified `axcodes` +- `RandGaussianNoise`: Perturb image intensities by adding statistical noises +- `NormalizeIntensity`: Intensity Normalization based on mean and standard deviation +- `Affine`: Transform image based on the affine parameters +- `Rand2DElastic`: Random elastic deformation and affine in 2D +- `Rand3DElastic`: Random elastic deformation and affine in 3D + +[2D transforms tutorial](https://github.com/Project-MONAI/Tutorials/blob/master/transforms_demo_2d.ipynb) shows the detailed usage of several MONAI medical image specific transforms. +![image](../images/medical_transforms.png) + +### 3. Fused spatial transforms and GPU acceleration +As medical image volumes are usually large (in multi-dimensional arrays), pre-processing performance affects the overall pipeline speed. MONAI provides affine transforms to execute fused spatial operations, supports GPU acceleration via native PyTorch for high performance. + +For example: +```py +# create an Affine transform +affine = Affine( + rotate_params=np.pi/4, + scale_params=(1.2, 1.2), + translate_params=(200, 40), + padding_mode='zeros', + device=torch.device('cuda:0') +) +# convert the image using bilinear interpolation +new_img = affine(image, spatial_size=(300, 400), mode='bilinear') +``` +Experiments and test results are available at [Fused transforms test](https://github.com/Project-MONAI/Tutorials/blob/master/transform_speed.ipynb). + +Currently all the geometric image transforms (Spacing, Zoom, Rotate, Resize, etc.) are designed based on the PyTorch native interfaces. [Geometric transforms tutorial](https://github.com/Project-MONAI/Tutorials/blob/master/3d_image_transforms.ipynb) indicates the usage of affine transforms with 3D medical images. +![image](../images/affine.png) + +### 4. Randomly crop out batch images based on positive/negative ratio +Medical image data volume may be too large to fit into GPU memory. A widely-used approach is to randomly draw small size data samples during training and run a “sliding window” routine for inference. MONAI currently provides general random sampling strategies including class-balanced fixed ratio sampling which may help stabilize the patch-based training process. A typical example is in [Spleen 3D segmentation tutorial](https://github.com/Project-MONAI/Tutorials/blob/master/spleen_segmentation_3d.ipynb), which achieves the class-balanced sampling with `RandCropByPosNegLabel` transform. + +### 5. Deterministic training for reproducibility +Deterministic training support is necessary and important for deep learning research, especially in the medical field. Users can easily set the random seed to all the random transforms in MONAI locally and will not affect other non-deterministic modules in the user's program. + +For example: +```py +# define a transform chain for pre-processing +train_transforms = monai.transforms.Compose([ + LoadNiftid(keys=['image', 'label']), + RandRotate90d(keys=['image', 'label'], prob=0.2, spatial_axes=[0, 2]), + ... ... +]) +# set determinism for reproducibility +train_transforms.set_random_state(seed=0) +``` +Users can also enable/disable deterministic at the beginning of training program: +```py +monai.utils.set_determinism(seed=0, additional_settings=None) +``` + +### 6. Multiple transform chains +To apply different transforms on the same data and concatenate the results, MONAI provides `CopyItems` transform to make copies of specified items in the data dictionary and `ConcatItems` transform to combine specified items on the expected dimension, and also provides `DeleteItems` transform to delete unnecessary items to save memory. + +Typical usage is to scale the intensity of the same image into different ranges and concatenate the results together. +![image](../images/multi_transform_chains.png) + +### 7. Debug transforms with DataStats +When transforms are combined with the "compose" function, it's not easy to track the output of specific transform. To help debug errors in the composed transforms, MONAI provides utility transforms such as `DataStats` to print out intermediate data properties such as `data shape`, `value range`, `data value`, `Additional information`, etc. It's a self-contained transform and can be integrated into any transform chain. + +### 8. Post-processing transforms for model output +MONAI also provides post-processing transforms for handling the model outputs. Currently, the transforms include: +- Adding activation layer (Sigmoid, Softmax, etc.). +- Converting to discrete values (Argmax, One-Hot, Threshold value, etc), as below figure (b). +- Splitting multi-channel data into multiple single channels. +- Removing segmentation noise based on Connected Component Analysis, as below figure (c). +- Extracting contour of segmentation result, which can be used to map to original image and evaluate the model, as below figure (d) and (e). + +After applying the post-processing transforms, it's easier to compute metrics, save model output into files or visualize data in the TensorBoard. [Post transforms tutorial](https://github.com/Project-MONAI/Tutorials/blob/master/post_transforms.ipynb) shows an example with several main post transforms. +![image](../images/post_transforms.png) + +### 9. Integrate third-party transforms +The design of MONAI transforms emphasis code readability and usability. It works for array data or dictionary-based data. MONAI also provides `Adaptor` tools to accommodate different data format for 3rd party transforms. To convert the data shapes or types, utility transforms such as `ToTensor`, `ToNumpy`, `SqueezeDim` are also provided. So it's easy to enhance the transform chain by seamlessly integrating transforms from external packages, including: `ITK`, `BatchGenerator`, `TorchIO` and `Rising`. + +For more details, please check out the tutorial: [integrate 3rd party transforms into MONAI program](https://github.com/Project-MONAI/Tutorials/blob/master/integrate_3rd_party_transforms.ipynb). + +## Datasets +### 1. Cache IO and transforms data to accelerate training +Users often need to train the model with many (potentially thousands of) epochs over the data to achieve the desired model quality. A native PyTorch implementation may repeatedly load data and run the same preprocessing steps for every epoch during training, which can be time-consuming and unnecessary, especially when the medical image volumes are large. + +MONAI provides a multi-threads `CacheDataset` to accelerate these transformation steps during training by storing the intermediate outcomes before the first randomized transform in the transform chain. Enabling this feature could potentially give 10x training speedups in the [CacheDataset experiment](https://github.com/Project-MONAI/Tutorials/blob/master/cache_dataset_speed.ipynb). +![image](../images/cache_dataset.png) + +### 2. Cache intermediate outcomes into persistent storage +The `PersistentDataset` is similar to the CacheDataset, where the intermediate cache values are persisted to disk storage for rapid retrieval between experimental runs (as is the case when tuning hyperparameters), or when the entire data set size exceeds available memory. The `PersistentDataset` could achieve similar performance when comparing to `CacheDataset` in [PersistentDataset experiment](https://github.com/Project-MONAI/Tutorials/blob/master/persistent_dataset_speed.ipynb). +![image](../images/datasets_speed.png) + +### 3. Zip multiple PyTorch datasets and fuse the output +MONAI provides `ZipDataset` to associate multiple PyTorch datasets and combine the output data (with the same corresponding batch index) into a tuple, which can be helpful to execute complex training processes based on various data sources. + +For example: +```py +class DatasetA(Dataset): + def __getitem__(self, index: int): + return image_data[index] + +class DatasetB(Dataset): + def __getitem__(self, index: int): + return extra_data[index] + +dataset = ZipDataset([DatasetA(), DatasetB()], transform) +``` + +### 4. Predefined Datasets for public medical data +To quickly get started with popular training data in the medical domain, MONAI provides several data-specific Datasets(like: `MedNISTDataset`, `DecathlonDataset`, etc.), which include downloading, extracting data files and support generation of training/evaluation items with transforms. And they are flexible that users can easily modify the JSON config file to change the default behaviors. + +MONAI always welcome new contributions of public datasets, please refer to existing Datasets and leverage the download and extracting APIs, etc. [Public datasets tutorial](https://github.com/Project-MONAI/Tutorials/blob/master/public_datasets.ipynb) indicates how to quickly set up training workflows with `MedNISTDataset` and `DecathlonDataset` and how to create a new `Dataset` for public data. + +The common workflow of predefined datasets: +![image](../images/dataset_progress.png) + +## Losses +There are domain-specific loss functions in the medical imaging research which are not typically used in the generic computer vision tasks. As an important module of MONAI, these loss functions are implemented in PyTorch, such as `DiceLoss`, `GeneralizedDiceLoss`, `MaskedDiceLoss`, `TverskyLoss` and `FocalLoss`, etc. + +## Network architectures +Some deep neural network architectures have shown to be particularly effective for medical imaging analysis tasks. MONAI implements reference networks with the aims of both flexibility and code readability. + +To leverage the common network layers and blocks, MONAI provides several predefined layers and blocks which are compatible with 1D, 2D and 3D networks. Users can easily integrate the layer factories in their own networks. + +For example: +```py +# import MONAI’s layer factory +from monai.networks.layers import Conv + +# adds a transposed convolution layer to the network +# which is compatible with different spatial dimensions. +name, dimension = Conv.CONVTRANS, 3 +conv_type = Conv[name, dimension] +add_module('conv1', conv_type(in_channels, out_channels, kernel_size=1, bias=False)) +``` +And there are several 1D/2D/3D-compatible implementations of intermediate blocks and generic networks, such as UNet, DenseNet, GAN. + +## Evaluation +To run model inferences and evaluate the model quality, MONAI provides reference implementations for the relevant widely-used approaches. Currently, several popular evaluation metrics and inference patterns are included: + +### 1. Sliding window inference +For model inferences on large volumes, the sliding window approach is a popular choice to achieve high performance while having flexible memory requirements (_alternatively, please check out the latest research on [model parallel training](#lamp-large-deep-nets-with-automated-model-parallelism-for-image-segmentation) using MONAI_). It also supports `overlap` and `blending_mode` configurations to handle the overlapped windows for better performances. + +A typical process is: +1. Select continuous windows on the original image. +2. Iteratively run batched window inferences until all windows are analyzed. +3. Aggregate the inference outputs to a single segmentation map. +4. Save the results to file or compute some evaluation metrics. +![image](../images/sliding_window.png) + +The [Spleen 3D segmentation tutorial](https://github.com/Project-MONAI/Tutorials/blob/master/spleen_segmentation_3d.ipynb) leverages `SlidingWindow` inference for validation. + +### 2. Metrics for medical tasks +Various useful evaluation metrics have been used to measure the quality of medical image specific models. MONAI already implemented mean Dice score for segmentation tasks and the area under the ROC curve for classification tasks. We continue to integrate more options. + +## Visualization +Beyond the simple point and curve plotting, MONAI provides intuitive interfaces to visualize multidimensional data as GIF animations in TensorBoard. This could provide a quick qualitative assessment of the model by visualizing, for example, the volumetric inputs, segmentation maps, and intermediate feature maps. A runnable example with visualization is available at [UNet training example](https://github.com/Project-MONAI/MONAI/blob/master/examples/segmentation_3d/unet_training_dict.py). + +## Result writing +Currently MONAI supports writing the model outputs as NIfTI files or PNG files for segmentation tasks, and as CSV files for classification tasks. And the writers can restore the data spacing, orientation or shape according to the `original_shape` or `original_affine` information from the input image. + +A rich set of formats will be supported soon, along with relevant statistics and evaluation metrics automatically computed from the outputs. + +## Workflows +To quickly set up training and evaluation experiments, MONAI provides a set of workflows to significantly simplify the modules and allow for fast prototyping. + +These features decouple the domain-specific components and the generic machine learning processes. They also provide a set of unify APIs for higher level applications (such as AutoML, Federated Learning). +The trainers and evaluators of the workflows are compatible with pytorch-ignite `Engine` and `Event-Handler` mechanism. There are rich event handlers in MONAI to independently attach to the trainer or evaluator. + +The workflow and event handlers are shown as below: +![image](../images/workflows.png) + +The end-to-end training and evaluation examples are available at [Workflow examples](https://github.com/Project-MONAI/MONAI/tree/master/examples/workflows). + +## Research +There are several research prototypes in MONAI corresponding to the recently published papers that address advanced research problems. +We always welcome contributions in forms of comments, suggestions, and code implementations. + +The generic patterns/modules identified from the research prototypes will be integrated into MONAI core functionality. + +### COPLE-Net for COVID-19 Pneumonia Lesion Segmentation +[A reimplementation](https://github.com/Project-MONAI/MONAI/tree/master/research/coplenet-pneumonia-lesion-segmentation) of the COPLE-Net originally proposed by: + +G. Wang, X. Liu, C. Li, Z. Xu, J. Ruan, H. Zhu, T. Meng, K. Li, N. Huang, S. Zhang. (2020) "A Noise-robust Framework for Automatic Segmentation of COVID-19 Pneumonia Lesions from CT Images." IEEE Transactions on Medical Imaging. 2020. [DOI: 10.1109/TMI.2020.3000314](https://doi.org/10.1109/TMI.2020.3000314) +![image](../images/coplenet.png) + +### LAMP: Large Deep Nets with Automated Model Parallelism for Image Segmentation +[A reimplementation](https://github.com/Project-MONAI/MONAI/tree/master/research/lamp-automated-model-parallelism) of the LAMP system originally proposed by: + +Wentao Zhu, Can Zhao, Wenqi Li, Holger Roth, Ziyue Xu, and Daguang Xu (2020) "LAMP: Large Deep Nets with Automated Model Parallelism for Image Segmentation." MICCAI 2020 (Early Accept, paper link: https://arxiv.org/abs/2006.12575) +![image](../images/unet-pipe.png) diff --git a/testbed/Project-MONAI__MONAI/docs/source/index.rst b/testbed/Project-MONAI__MONAI/docs/source/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..955c25dec91eec561036cb2f0fad0ce20f73b02c --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/index.rst @@ -0,0 +1,102 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. MONAI documentation master file, created by + sphinx-quickstart on Wed Feb 5 09:40:29 2020. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Project MONAI +============= + + +*Medical Open Network for AI* + +MONAI is a `PyTorch `_-based, `open-source `_ framework +for deep learning in healthcare imaging, part of `PyTorch Ecosystem `_. + +Its ambitions are: + +- developing a community of academic, industrial and clinical researchers collaborating on a common foundation; +- creating state-of-the-art, end-to-end training workflows for healthcare imaging; +- providing researchers with the optimized and standardized way to create and evaluate deep learning models. + +Features +-------- + +*The codebase is currently under active development* + +- flexible pre-processing for multi-dimensional medical imaging data; +- compositional & portable APIs for ease of integration in existing workflows; +- domain-specific implementations for networks, losses, evaluation metrics and more; +- customizable design for varying user expertise; +- multi-GPU data parallelism support. + + +Getting started +--------------- + +`MedNIST demo `_ and `MONAI for PyTorch Users `_ are available on Colab. + +Tutorials & examples are located at `monai/examples `_. + +Technical documentation is available at `docs.monai.io `_. + +.. toctree:: + :maxdepth: 1 + :caption: Feature highlights + + highlights.md + +.. toctree:: + :maxdepth: 1 + :caption: APIs + + apps + transforms + losses + networks + metrics + data + engines + inferers + handlers + visualize + utils + +.. toctree:: + :maxdepth: 1 + :caption: Installation + + installation + + +Contributing +------------ + +For guidance on making a contribution to MONAI, see the `contributing guidelines +`_. + + +Links +----- + +- Website: https://monai.io/ +- API documentation: https://docs.monai.io +- Code: https://github.com/Project-MONAI/MONAI +- Project tracker: https://github.com/Project-MONAI/MONAI/projects +- Issue tracker: https://github.com/Project-MONAI/MONAI/issues +- Changelog: https://github.com/Project-MONAI/MONAI/blob/master/CHANGELOG.md +- Wiki: https://github.com/Project-MONAI/MONAI/wiki +- FAQ: https://github.com/Project-MONAI/MONAI/wiki/Frequently-asked-questions-and-answers +- Test status: https://github.com/Project-MONAI/MONAI/actions +- PyPI package: https://pypi.org/project/monai/ +- Docker Hub: https://hub.docker.com/r/projectmonai/monai +- Google Group: https://groups.google.com/forum/#!forum/project-monai +- Reddit: https://www.reddit.com/r/projectmonai/ + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` diff --git a/testbed/Project-MONAI__MONAI/docs/source/inferers.rst b/testbed/Project-MONAI__MONAI/docs/source/inferers.rst new file mode 100644 index 0000000000000000000000000000000000000000..8b113390946eae6edf174265c9c66d1d2c0dff2d --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/inferers.rst @@ -0,0 +1,29 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _inferers: + +Inference methods +================= + +Sliding Window Inference +------------------------ + +.. autofunction:: monai.inferers.sliding_window_inference + + +Inferers +-------- + +.. currentmodule:: monai.inferers +.. autoclass:: Inferer + :members: + +`SimpleInferer` +~~~~~~~~~~~~~~~ +.. autoclass:: SimpleInferer + :members: + +`SlidingWindowInferer` +~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SlidingWindowInferer + :members: diff --git a/testbed/Project-MONAI__MONAI/docs/source/installation.md b/testbed/Project-MONAI__MONAI/docs/source/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..fb19f09eb25bc56a0981bdf41aed452321fca55b --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/installation.md @@ -0,0 +1,137 @@ +# Installation guide + +MONAI's core functionality is written in Python 3 (>= 3.6) and only requires [Numpy](https://numpy.org/) and [Pytorch](https://pytorch.org/). + +The package is currently distributed via Github as the primary source code repository, +and the Python package index (PyPI). The pre-built Docker images are made available on DockerHub. + +This page provides steps to: +- [Install MONAI from PyPI](#from-pypi) +- [Install MONAI from GitHub](#from-github) +- [Validate the install](#validating-the-install) +- [Understand MONAI version string](#monai-version-string) +- [Run MONAI From DockerHub](#from-dockerhub) + +To install optional features such as handling the NIfTI files using +[Nibabel](https://nipy.org/nibabel/), or building workflows using [Pytorch +Ignite](https://pytorch.org/ignite/), please follow the instructions: +- [Installing the recommended dependencies](#installing-the-recommended-dependencies) + +--- + + +## From PyPI +To install the [current milestone release](https://pypi.org/project/monai/): +```bash +pip install monai +``` + +## From GitHub +(_If you have installed the +PyPI release version using ``pip install monai``, please run ``pip uninstall +monai`` before using the commands from this section. Because ``pip`` by +default prefers the milestone release_.) + +The milestone versions are currently planned and released every few months. As the +codebase is under active development, you may want to install MONAI from GitHub +for the latest features: + +### Option 1 (as a part of your system-wide module): +```bash +pip install git+https://github.com/Project-MONAI/MONAI#egg=MONAI +``` +this command will download and install the current master branch of [MONAI from +GitHub](https://github.com/Project-MONAI/MONAI). + +This documentation website by default shows the information for the latest version. + +### Option 2 (editable installation): +To install an editable version of MONAI, it is recommended to clone the codebase directly: +```bash +git clone https://github.com/Project-MONAI/MONAI.git +``` +This command will create a ``MONAI/`` folder in your current directory. +You can install it by running: +```bash +cd MONAI/ +python setup.py develop + +# to uninstall the package please run: +python setup.py develop --uninstall +``` +or simply adding the root directory of the cloned source code (e.g., ``/workspace/Documents/MONAI``) to your ``$PYTHONPATH`` +and the codebase is ready to use (without the additional features of MONAI C++/CUDA extensions). + + +## Validating the install +You can verify the installation by: +```bash +python -c 'import monai; monai.config.print_config()' +``` +If the installation is successful, this command will print out the MONAI version information, and this confirms the core +modules of MONAI are ready-to-use. + + +## MONAI version string +The MONAI version string shows the current status of your local installation. For example: +``` +MONAI version: 0.1.0+144.g52c763d.dirty +``` +- ``0.1.0`` indicates that your installation is based on the ``0.1.0`` milestone release. +- ``+144`` indicates that your installation is 144 git commits ahead of the milestone release. +- ``g52c763d`` indicates that your installation corresponds to the git commit hash ``52c763d``. +- ``dirty`` indicates that you have modified the codebase locally, and the codebase is inconsistent with ``52c763d``. + + +## From DockerHub +Make sure you have installed the NVIDIA driver and Docker 19.03+ for your Linux distribution. +Note that you do not need to install the CUDA toolkit on the host, but the driver needs to be installed. +Please find out more information on [nvidia-docker](https://github.com/NVIDIA/nvidia-docker). + +Assuming that you have the Nvidia driver and Docker 19.03+ installed, running the following command will +download and start a container with the latest version of MONAI. The latest master branch of MONAI from GitHub +is included in the image. +```bash +docker run --gpus all --rm -ti --ipc=host projectmonai/monai:latest +``` + +You can also run a milestone release docker image by specifying the image tag, for example: +``` +docker run --gpus all --rm -ti --ipc=host projectmonai/monai:0.1.0 +``` + +## Installing the recommended dependencies +By default, the installation steps will only download and install the minimal requirements of MONAI. +Optional dependencies can be installed using [the extras syntax](https://packaging.python.org/tutorials/installing-packages/#installing-setuptools-extras) to support additional features. + +For example, to install MONAI with Nibabel and Scikit-image support: +```bash +git clone https://github.com/Project-MONAI/MONAI.git +cd MONAI/ +pip install -e '.[nibabel,skimage]' +``` + +Alternatively, to install all optional dependencies: +```bash +git clone https://github.com/Project-MONAI/MONAI.git +cd MONAI/ +pip install -e '.[all]' +``` + +To install all optional dependencies for MONAI development: +```bash +git clone https://github.com/Project-MONAI/MONAI.git +cd MONAI/ +pip install -r requirements-dev.txt +``` + +Since MONAI v0.2.0, the extras syntax such as `pip install 'monai[nibabel]'` is available via PyPI. + +- The options are +``` +[nibabel, skimage, pillow, tensorboard, gdown, ignite, torchvision, itk] +``` +which correspond to `nibabel`, `scikit-image`, `pillow`, `tensorboard`, +`gdown`, `pytorch-ignite`, `torchvision`, and `itk` respectively. + +- `pip install 'monai[all]'` installs all the optional dependencies. diff --git a/testbed/Project-MONAI__MONAI/docs/source/losses.rst b/testbed/Project-MONAI__MONAI/docs/source/losses.rst new file mode 100644 index 0000000000000000000000000000000000000000..ce2e4a85f37604f78636baa4b50930d49865675b --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/losses.rst @@ -0,0 +1,46 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _losses: + +Loss functions +============== + +Segmentation Losses +------------------- + +.. automodule:: monai.losses +.. currentmodule:: monai.losses + +`DiceLoss` +~~~~~~~~~~ +.. autoclass:: DiceLoss + :members: + +.. autoclass:: Dice + :members: + +.. autoclass:: dice + :members: + +`MaskedDiceLoss` +~~~~~~~~~~~~~~~~ +.. autoclass:: MaskedDiceLoss + :members: + +`GeneralizedDiceLoss` +~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: GeneralizedDiceLoss + :members: + +.. autoclass:: generalized_dice + :members: + +`FocalLoss` +~~~~~~~~~~~ +.. autoclass:: FocalLoss + :members: + +`TverskyLoss` +~~~~~~~~~~~~~ +.. autoclass:: TverskyLoss + :members: diff --git a/testbed/Project-MONAI__MONAI/docs/source/metrics.rst b/testbed/Project-MONAI__MONAI/docs/source/metrics.rst new file mode 100644 index 0000000000000000000000000000000000000000..bd541c99f1d8bf4392038cb5df45642c76ce02cf --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/metrics.rst @@ -0,0 +1,22 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _metrics: + +Metrics +======= +.. currentmodule:: monai.metrics + +`Mean Dice` +----------- +.. autofunction:: compute_meandice + +.. autoclass:: DiceMetric + :members: + +`Area under the ROC curve` +-------------------------- +.. autofunction:: compute_roc_auc + +`Confusion Matrix` +------------------ +.. autofunction:: compute_confusion_metric diff --git a/testbed/Project-MONAI__MONAI/docs/source/networks.rst b/testbed/Project-MONAI__MONAI/docs/source/networks.rst new file mode 100644 index 0000000000000000000000000000000000000000..b9c4a5eeb5e564a545c79e3f5fb3157c2cca269c --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/networks.rst @@ -0,0 +1,256 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _networks: + +Network architectures +===================== + +Blocks +------ +.. automodule:: monai.networks.blocks +.. currentmodule:: monai.networks.blocks + +`Convolution` +~~~~~~~~~~~~~ +.. autoclass:: Convolution + :members: + +`ResidualUnit` +~~~~~~~~~~~~~~ +.. autoclass:: ResidualUnit + :members: + +`GCN Module` +~~~~~~~~~~~~ +.. autoclass:: GCN + :members: + +`Refinement Module` +~~~~~~~~~~~~~~~~~~~ +.. autoclass:: Refine + :members: + +`FCN Module` +~~~~~~~~~~~~ +.. autoclass:: FCN + :members: + +`Multi-Channel FCN Module` +~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: MCFCN + :members: + +`SegResnet Block` +~~~~~~~~~~~~~~~~~ +.. autoclass:: ResBlock + :members: + +`Squeeze-and-Excitation` +~~~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: ChannelSELayer + :members: + +`Residual Squeeze-and-Excitation` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: ResidualSELayer + :members: + +`Squeeze-and-Excitation Block` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SEBlock + :members: + +`Squeeze-and-Excitation Bottleneck` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SEBottleneck + :members: + +`Squeeze-and-Excitation Resnet Bottleneck` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SEResNetBottleneck + :members: + +`Squeeze-and-Excitation ResneXt Bottleneck` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: SEResNeXtBottleneck + :members: + +`Simple ASPP` +~~~~~~~~~~~~~ +.. autoclass:: SimpleASPP + :members: + +`MaxAvgPooling` +~~~~~~~~~~~~~~~ +.. autoclass:: MaxAvgPool + :members: + +`Upsampling` +~~~~~~~~~~~~ +.. autoclass:: UpSample + :members: +.. autoclass:: SubpixelUpsample + :members: + + +Layers +------ + +`Factories` +~~~~~~~~~~~ +.. automodule:: monai.networks.layers.factories + +.. autoclass:: monai.networks.layers.LayerFactory + :members: + +.. currentmodule:: monai.networks.layers + +`split_args` +~~~~~~~~~~~~ +.. autofunction:: monai.networks.layers.split_args + +`Dropout` +~~~~~~~~~ +.. automodule:: monai.networks.layers.Dropout + :members: + +`Act` +~~~~~ +.. automodule:: monai.networks.layers.Act + :members: + +`Norm` +~~~~~~ +.. automodule:: monai.networks.layers.Norm + :members: + +`Conv` +~~~~~~ +.. automodule:: monai.networks.layers.Conv + :members: + +`Pool` +~~~~~~ +.. automodule:: monai.networks.layers.Pool + :members: + +.. currentmodule:: monai.networks.layers + +`SkipConnection` +~~~~~~~~~~~~~~~~ +.. autoclass:: SkipConnection + :members: + +`Flatten` +~~~~~~~~~ +.. autoclass:: Flatten + :members: + +`GaussianFilter` +~~~~~~~~~~~~~~~~ +.. autoclass:: GaussianFilter + :members: + +`Affine Transform` +~~~~~~~~~~~~~~~~~~ +.. autoclass:: monai.networks.layers.AffineTransform + :members: + +`LLTM` +~~~~~~ +.. autoclass:: LLTM + :members: + +`Utilities` +~~~~~~~~~~~ +.. automodule:: monai.networks.layers.convutils + :members: + + +Nets +---- +.. currentmodule:: monai.networks.nets + +`Ahnet` +~~~~~~~ +.. autoclass:: AHNet + :members: + +`Densenet3D` +~~~~~~~~~~~~ +.. autoclass:: DenseNet + :members: +.. autofunction:: densenet121 +.. autofunction:: densenet169 +.. autofunction:: densenet201 +.. autofunction:: densenet264 + +`SegResnet` +~~~~~~~~~~~ +.. autoclass:: SegResNet + :members: + +`SegResnetVAE` +~~~~~~~~~~~~~~ +.. autoclass:: SegResNetVAE + :members: + +`Senet` +~~~~~~~ +.. autoclass:: SENet + :members: +.. autofunction:: senet154 +.. autofunction:: se_resnet50 +.. autofunction:: se_resnet101 +.. autofunction:: se_resnet152 +.. autofunction:: se_resnext50_32x4d +.. autofunction:: se_resnext101_32x4d + +`Highresnet` +~~~~~~~~~~~~ +.. autoclass:: HighResNet + :members: +.. autoclass:: HighResBlock + :members: + +`Unet` +~~~~~~ +.. autoclass:: UNet + :members: +.. autoclass:: Unet +.. autoclass:: unet + +`Vnet` +~~~~~~ +.. autoclass:: VNet + :members: + +`Generator` +~~~~~~~~~~~ +.. autoclass:: Generator + :members: + +`Regressor` +~~~~~~~~~~~ +.. autoclass:: Regressor + :members: + +`Classifier` +~~~~~~~~~~~~ +.. autoclass:: Classifier + :members: + +`Discriminator` +~~~~~~~~~~~~~~~ +.. autoclass:: Discriminator + :members: + +`Critic` +~~~~~~~~ +.. autoclass:: Critic + :members: + +Utilities +--------- +.. automodule:: monai.networks.utils + :members: diff --git a/testbed/Project-MONAI__MONAI/docs/source/transforms.rst b/testbed/Project-MONAI__MONAI/docs/source/transforms.rst new file mode 100644 index 0000000000000000000000000000000000000000..7f93aea11dd8502b55a151723d228f68fbcfda32 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/transforms.rst @@ -0,0 +1,931 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _transform_api: + +Transforms +========== + +Generic Interfaces +------------------ +.. automodule:: monai.transforms +.. currentmodule:: monai.transforms + +`Transform` +^^^^^^^^^^^ +.. autoclass:: Transform + :members: + :special-members: __call__ + +`MapTransform` +^^^^^^^^^^^^^^ +.. autoclass:: MapTransform + :members: + :special-members: __call__ + +`Randomizable` +^^^^^^^^^^^^^^ +.. autoclass:: Randomizable + :members: + +`Compose` +^^^^^^^^^ +.. autoclass:: Compose + :members: + :special-members: __call__ + +Vanilla Transforms +------------------ + +Crop and Pad +^^^^^^^^^^^^ + +`SpatialPad` +"""""""""""" +.. autoclass:: SpatialPad + :members: + :special-members: __call__ + +`BorderPad` +""""""""""" +.. autoclass:: BorderPad + :members: + :special-members: __call__ + +`DivisiblePad` +"""""""""""""" +.. autoclass:: DivisiblePad + :members: + :special-members: __call__ + +`SpatialCrop` +""""""""""""" +.. autoclass:: SpatialCrop + :members: + :special-members: __call__ + +`CenterSpatialCrop` +""""""""""""""""""" +.. autoclass:: CenterSpatialCrop + :members: + :special-members: __call__ + +`RandSpatialCrop` +""""""""""""""""" +.. autoclass:: RandSpatialCrop + :members: + :special-members: __call__ + +`RandSpatialCropSamples` +"""""""""""""""""""""""" +.. autoclass:: RandSpatialCropSamples + :members: + :special-members: __call__ + +`CropForeground` +"""""""""""""""" +.. autoclass:: CropForeground + :members: + :special-members: __call__ + +`RandCropByPosNegLabel` +""""""""""""""""""""""" +.. autoclass:: RandCropByPosNegLabel + :members: + :special-members: __call__ + +Intensity +^^^^^^^^^ + +`RandGaussianNoise` +""""""""""""""""""" +.. autoclass:: RandGaussianNoise + :members: + :special-members: __call__ + +`ShiftIntensity` +"""""""""""""""" +.. autoclass:: ShiftIntensity + :members: + :special-members: __call__ + +`RandShiftIntensity` +"""""""""""""""""""" +.. autoclass:: RandShiftIntensity + :members: + :special-members: __call__ + +`ScaleIntensity` +"""""""""""""""" +.. autoclass:: ScaleIntensity + :members: + :special-members: __call__ + +`RandScaleIntensity` +"""""""""""""""""""" +.. autoclass:: RandScaleIntensity + :members: + :special-members: __call__ + +`NormalizeIntensity` +"""""""""""""""""""" +.. autoclass:: NormalizeIntensity + :members: + :special-members: __call__ + +`ThresholdIntensity` +"""""""""""""""""""" +.. autoclass:: ThresholdIntensity + :members: + :special-members: __call__ + +`ScaleIntensityRange` +""""""""""""""""""""" +.. autoclass:: ScaleIntensityRange + :members: + :special-members: __call__ + +`ScaleIntensityRangePercentiles` +"""""""""""""""""""""""""""""""" +.. autoclass:: ScaleIntensityRangePercentiles + :members: + :special-members: __call__ + +`AdjustContrast` +"""""""""""""""" +.. autoclass:: AdjustContrast + :members: + :special-members: __call__ + +`RandAdjustContrast` +"""""""""""""""""""" +.. autoclass:: RandAdjustContrast + :members: + :special-members: __call__ + +`MaskIntensity` +""""""""""""""" +.. autoclass:: MaskIntensity + :members: + :special-members: __call__ + +`GaussianSmooth` +"""""""""""""""" +.. autoclass:: GaussianSmooth + :members: + :special-members: __call__ + +`RandGaussianSmooth` +"""""""""""""""""""" +.. autoclass:: RandGaussianSmooth + :members: + :special-members: __call__ + +`GaussianSharpen` +""""""""""""""""" +.. autoclass:: GaussianSharpen + :members: + :special-members: __call__ + +`RandGaussianSharpen` +""""""""""""""""""""" +.. autoclass:: RandGaussianSharpen + :members: + :special-members: __call__ + +IO +^^ + +`LoadImage` +""""""""""" +.. autoclass:: LoadImage + :members: + :special-members: __call__ + +`LoadNifti` +""""""""""" +.. autoclass:: LoadNifti + :members: + :special-members: __call__ + +`LoadPNG` +""""""""" +.. autoclass:: LoadPNG + :members: + :special-members: __call__ + +`LoadNumpy` +""""""""""" +.. autoclass:: LoadNumpy + :members: + :special-members: __call__ + +Post-processing +^^^^^^^^^^^^^^^ + +`SplitChannel` +"""""""""""""" +.. autoclass:: SplitChannel + :members: + :special-members: __call__ + +`Activations` +""""""""""""" +.. autoclass:: Activations + :members: + :special-members: __call__ + +`AsDiscrete` +"""""""""""" +.. autoclass:: AsDiscrete + :members: + :special-members: __call__ + +`KeepLargestConnectedComponent` +""""""""""""""""""""""""""""""" +.. autoclass:: KeepLargestConnectedComponent + :members: + :special-members: __call__ + +`LabelToContour` +"""""""""""""""" +.. autoclass:: LabelToContour + :members: + :special-members: __call__ + +`MeanEnsemble` +"""""""""""""" +.. autoclass:: MeanEnsemble + :members: + :special-members: __call__ + +`VoteEnsemble` +"""""""""""""" +.. autoclass:: VoteEnsemble + :members: + :special-members: __call__ + +Spatial +^^^^^^^ + +`Spacing` +""""""""" +.. autoclass:: Spacing + :members: + :special-members: __call__ + +`Orientation` +""""""""""""" +.. autoclass:: Orientation + :members: + :special-members: __call__ + +`RandRotate` +"""""""""""" +.. autoclass:: RandRotate + :members: + :special-members: __call__ + +`RandFlip` +"""""""""" +.. autoclass:: RandFlip + :members: + :special-members: __call__ + +`RandZoom` +"""""""""" +.. autoclass:: RandZoom + :members: + :special-members: __call__ + +`Affine` +"""""""" +.. autoclass:: Affine + :members: + :special-members: __call__ + +`Resample` +"""""""""" +.. autoclass:: Resample + :members: + :special-members: __call__ + +`RandAffine` +"""""""""""" +.. autoclass:: RandAffine + :members: + :special-members: __call__ + +`RandDeformGrid` +"""""""""""""""" +.. autoclass:: RandDeformGrid + :members: + :special-members: __call__ + +`AffineGrid` +"""""""""""""""" +.. autoclass:: AffineGrid + :members: + :special-members: __call__ + +`RandAffineGrid` +"""""""""""""""" +.. autoclass:: RandAffineGrid + :members: + :special-members: __call__ + +`Rand2DElastic` +""""""""""""""" +.. autoclass:: Rand2DElastic + :members: + :special-members: __call__ + +`Rand3DElastic` +""""""""""""""" +.. autoclass:: Rand3DElastic + :members: + :special-members: __call__ + +`Rotate90` +"""""""""" +.. autoclass:: Rotate90 + :members: + :special-members: __call__ + +`RandRotate90` +"""""""""""""" +.. autoclass:: RandRotate90 + :members: + :special-members: __call__ + +`Flip` +"""""" +.. autoclass:: Flip + :members: + :special-members: __call__ + +`Resize` +"""""""" +.. autoclass:: Resize + :members: + :special-members: __call__ + +`Rotate` +"""""""" +.. autoclass:: Rotate + :members: + :special-members: __call__ + +`Zoom` +"""""" +.. autoclass:: Zoom + :members: + :special-members: __call__ + +Utility +^^^^^^^ + +`Identity` +"""""""""" +.. autoclass:: Identity + :members: + :special-members: __call__ + +`AsChannelFirst` +"""""""""""""""" +.. autoclass:: AsChannelFirst + :members: + :special-members: __call__ + +`AsChannelLast` +""""""""""""""" +.. autoclass:: AsChannelLast + :members: + :special-members: __call__ + +`AddChannel` +"""""""""""" +.. autoclass:: AddChannel + :members: + :special-members: __call__ + +`RepeatChannel` +""""""""""""""" +.. autoclass:: RepeatChannel + :members: + :special-members: __call__ + +`CastToType` +"""""""""""" +.. autoclass:: CastToType + :members: + :special-members: __call__ + +`ToTensor` +"""""""""" +.. autoclass:: ToTensor + :members: + :special-members: __call__ + +`ToNumpy` +""""""""" +.. autoclass:: ToNumpy + :members: + :special-members: __call__ + +`Transpose` +""""""""""" +.. autoclass:: Transpose + :members: + :special-members: __call__ + +`SqueezeDim` +"""""""""""" +.. autoclass:: SqueezeDim + :members: + :special-members: __call__ + +`DataStats` +""""""""""" +.. autoclass:: DataStats + :members: + :special-members: __call__ + +`SimulateDelay` +""""""""""""""" +.. autoclass:: SimulateDelay + :members: + :special-members: __call__ + +`Lambda` +"""""""" +.. autoclass:: Lambda + :members: + :special-members: __call__ + +`LabelToMask` +""""""""""""" +.. autoclass:: LabelToMask + :members: + :special-members: __call__ + +`FgBgToIndices` +""""""""""""""" +.. autoclass:: FgBgToIndices + :members: + :special-members: __call__ + +Dictionary Transforms +--------------------- + +Crop and Pad (Dict) +^^^^^^^^^^^^^^^^^^^ + +`SpatialPadd` +""""""""""""" +.. autoclass:: SpatialPadd + :members: + :special-members: __call__ + +`BorderPadd` +"""""""""""" +.. autoclass:: BorderPadd + :members: + :special-members: __call__ + +`DivisiblePadd` +""""""""""""""" +.. autoclass:: DivisiblePadd + :members: + :special-members: __call__ + +`SpatialCropd` +"""""""""""""" +.. autoclass:: SpatialCropd + :members: + :special-members: __call__ + +`CenterSpatialCropd` +"""""""""""""""""""" +.. autoclass:: CenterSpatialCropd + :members: + :special-members: __call__ + +`RandSpatialCropd` +"""""""""""""""""" +.. autoclass:: RandSpatialCropd + :members: + :special-members: __call__ + +`RandSpatialCropSamplesd` +""""""""""""""""""""""""" +.. autoclass:: RandSpatialCropSamplesd + :members: + :special-members: __call__ + +`CropForegroundd` +""""""""""""""""" +.. autoclass:: CropForegroundd + :members: + :special-members: __call__ + +`RandCropByPosNegLabeld` +"""""""""""""""""""""""" +.. autoclass:: RandCropByPosNegLabeld + :members: + :special-members: __call__ + +Instensity (Dict) +^^^^^^^^^^^^^^^^^ + +`RandGaussianNoised` +"""""""""""""""""""" +.. autoclass:: RandGaussianNoised + :members: + :special-members: __call__ + +`ShiftIntensityd` +""""""""""""""""" +.. autoclass:: ShiftIntensityd + :members: + :special-members: __call__ + +`RandShiftIntensityd` +""""""""""""""""""""" +.. autoclass:: RandShiftIntensityd + :members: + :special-members: __call__ + +`ScaleIntensityd` +""""""""""""""""" +.. autoclass:: ScaleIntensityd + :members: + :special-members: __call__ + +`RandScaleIntensityd` +""""""""""""""""""""" +.. autoclass:: RandScaleIntensityd + :members: + :special-members: __call__ + +`NormalizeIntensityd` +""""""""""""""""""""" +.. autoclass:: NormalizeIntensityd + :members: + :special-members: __call__ + +`ThresholdIntensityd` +""""""""""""""""""""" +.. autoclass:: ThresholdIntensityd + :members: + :special-members: __call__ + +`ScaleIntensityRanged` +"""""""""""""""""""""" +.. autoclass:: ScaleIntensityRanged + :members: + :special-members: __call__ + +`ScaleIntensityRangePercentilesd` +""""""""""""""""""""""""""""""""" +.. autoclass:: ScaleIntensityRangePercentilesd + :members: + :special-members: __call__ + +`AdjustContrastd` +""""""""""""""""" +.. autoclass:: AdjustContrastd + :members: + :special-members: __call__ + +`RandAdjustContrastd` +""""""""""""""""""""" +.. autoclass:: RandAdjustContrastd + :members: + :special-members: __call__ + +`MaskIntensityd` +"""""""""""""""" +.. autoclass:: MaskIntensityd + :members: + :special-members: __call__ + +`GaussianSmoothd` +""""""""""""""""" +.. autoclass:: GaussianSmoothd + :members: + :special-members: __call__ + +`RandGaussianSmoothd` +""""""""""""""""""""" +.. autoclass:: RandGaussianSmoothd + :members: + :special-members: __call__ + +`GaussianSharpend` +"""""""""""""""""" +.. autoclass:: GaussianSharpend + :members: + :special-members: __call__ + +`RandGaussianSharpend` +"""""""""""""""""""""" +.. autoclass:: RandGaussianSharpend + :members: + :special-members: __call__ + +IO (Dict) +^^^^^^^^^ + +`LoadDatad` +""""""""""" +.. autoclass:: LoadDatad + :members: + :special-members: __call__ + +`LoadImaged` +"""""""""""" +.. autoclass:: LoadImaged + :members: + :special-members: __call__ + +`LoadNiftid` +"""""""""""" +.. autoclass:: LoadNiftid + :members: + :special-members: __call__ + +`LoadPNGd` +"""""""""" +.. autoclass:: LoadPNGd + :members: + :special-members: __call__ + +`LoadNumpyd` +"""""""""""" +.. autoclass:: LoadNumpyd + :members: + :special-members: __call__ + +Post-processing (Dict) +^^^^^^^^^^^^^^^^^^^^^^ + +`SplitChanneld` +""""""""""""""" +.. autoclass:: SplitChanneld + :members: + :special-members: __call__ + +`Activationsd` +"""""""""""""" +.. autoclass:: Activationsd + :members: + :special-members: __call__ + +`AsDiscreted` +""""""""""""" +.. autoclass:: AsDiscreted + :members: + :special-members: __call__ + +`KeepLargestConnectedComponentd` +"""""""""""""""""""""""""""""""" +.. autoclass:: KeepLargestConnectedComponentd + :members: + :special-members: __call__ + +`LabelToContourd` +""""""""""""""""" +.. autoclass:: LabelToContourd + :members: + :special-members: __call__ + +`Ensembled` +""""""""""" +.. autoclass:: Ensembled + :members: + :special-members: __call__ + +`MeanEnsembled` +""""""""""""""" +.. autoclass:: MeanEnsembled + :members: + :special-members: __call__ + +`VoteEnsembled` +""""""""""""""" +.. autoclass:: VoteEnsembled + :members: + :special-members: __call__ + +Spatial (Dict) +^^^^^^^^^^^^^^ + +`Spacingd` +"""""""""" +.. autoclass:: Spacingd + :members: + :special-members: __call__ + +`Orientationd` +"""""""""""""" +.. autoclass:: Orientationd + :members: + :special-members: __call__ + +`Flipd` +""""""" +.. autoclass:: Flipd + :members: + :special-members: __call__ + +`RandFlipd` +""""""""""" +.. autoclass:: RandFlipd + :members: + :special-members: __call__ + +`Rotated` +""""""""" +.. autoclass:: Rotated + :members: + :special-members: __call__ + +`RandRotated` +""""""""""""" +.. autoclass:: RandRotated + :members: + :special-members: __call__ + +`Zoomd` +""""""" +.. autoclass:: Zoomd + :members: + :special-members: __call__ + +`RandZoomd` +""""""""""" +.. autoclass:: RandZoomd + :members: + :special-members: __call__ + +`RandRotate90d` +""""""""""""""" +.. autoclass:: RandRotate90d + :members: + :special-members: __call__ + +`Rotate90d` +""""""""""" +.. autoclass:: Rotate90d + :members: + :special-members: __call__ + +`Resized` +""""""""" +.. autoclass:: Resized + :members: + :special-members: __call__ + +`RandAffined` +""""""""""""" +.. autoclass:: RandAffined + :members: + :special-members: __call__ + +`Rand2DElasticd` +"""""""""""""""" +.. autoclass:: Rand2DElasticd + :members: + :special-members: __call__ + +`Rand3DElasticd` +"""""""""""""""" +.. autoclass:: Rand3DElasticd + :members: + :special-members: __call__ + +Utility (Dict) +^^^^^^^^^^^^^^ + +`Identityd` +""""""""""" +.. autoclass:: Identityd + :members: + :special-members: __call__ + +`AsChannelFirstd` +""""""""""""""""" +.. autoclass:: AsChannelFirstd + :members: + :special-members: __call__ + +`AsChannelLastd` +"""""""""""""""" +.. autoclass:: AsChannelLastd + :members: + :special-members: __call__ + +`AddChanneld` +""""""""""""" +.. autoclass:: AddChanneld + :members: + :special-members: __call__ + +`RepeatChanneld` +"""""""""""""""" +.. autoclass:: RepeatChanneld + :members: + :special-members: __call__ + +`CastToTyped` +""""""""""""" +.. autoclass:: CastToTyped + :members: + :special-members: __call__ + +`ToTensord` +""""""""""" +.. autoclass:: ToTensord + :members: + :special-members: __call__ + +`ToNumpyd` +"""""""""" +.. autoclass:: ToNumpyd + :members: + :special-members: __call__ + +`DeleteItemsd` +"""""""""""""" +.. autoclass:: DeleteItemsd + :members: + :special-members: __call__ + +`SqueezeDimd` +""""""""""""" +.. autoclass:: SqueezeDimd + :members: + :special-members: __call__ + +`DataStatsd` +"""""""""""" +.. autoclass:: DataStatsd + :members: + :special-members: __call__ + +`SimulateDelayd` +"""""""""""""""" +.. autoclass:: SimulateDelayd + :members: + :special-members: __call__ + +`CopyItemsd` +"""""""""""" +.. autoclass:: CopyItemsd + :members: + :special-members: __call__ + +`ConcatItemsd` +"""""""""""""" +.. autoclass:: ConcatItemsd + :members: + :special-members: __call__ + +`Lambdad` +""""""""" +.. autoclass:: Lambdad + :members: + :special-members: __call__ + +`LabelToMaskd` +"""""""""""""" +.. autoclass:: LabelToMaskd + :members: + :special-members: __call__ + +`FgBgToIndicesd` +"""""""""""""""" +.. autoclass:: FgBgToIndicesd + :members: + :special-members: __call__ + +Transform Adaptors +------------------ +.. automodule:: monai.transforms.adaptors + +`adaptor` +^^^^^^^^^ +.. autofunction:: monai.transforms.adaptors.adaptor + +`apply_alias` +^^^^^^^^^^^^^ +.. autofunction:: monai.transforms.adaptors.apply_alias + +`to_kwargs` +^^^^^^^^^^^ +.. autofunction:: monai.transforms.adaptors.to_kwargs + +Utilities +--------- +.. automodule:: monai.transforms.utils + :members: diff --git a/testbed/Project-MONAI__MONAI/docs/source/utils.rst b/testbed/Project-MONAI__MONAI/docs/source/utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..6a03529c304c45d46dae1e326f493f6ac11d4f68 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/utils.rst @@ -0,0 +1,28 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _utils: + +Utilities +========= + +Configurations +-------------- +.. automodule:: monai.config.deviceconfig + :members: + + +Module utils +------------ +.. automodule:: monai.utils.module + :members: + + +Aliases +------- +.. automodule:: monai.utils.aliases + :members: + +Misc +---- +.. automodule:: monai.utils.misc + :members: diff --git a/testbed/Project-MONAI__MONAI/docs/source/visualize.rst b/testbed/Project-MONAI__MONAI/docs/source/visualize.rst new file mode 100644 index 0000000000000000000000000000000000000000..e6506f684911631c33f71f64550493dffd3c9689 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/docs/source/visualize.rst @@ -0,0 +1,12 @@ +:github_url: https://github.com/Project-MONAI/MONAI + +.. _visualize: + +Visualizations +============== + +Tensorboard visuals +------------------- + +.. automodule:: monai.visualize.img2tensorboard + :members: diff --git a/testbed/Project-MONAI__MONAI/monai/config/__init__.py b/testbed/Project-MONAI__MONAI/monai/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e05e70448686abccc5b00e541789521e666e8d --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/config/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2020 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 .deviceconfig import * +from .type_definitions import * diff --git a/testbed/Project-MONAI__MONAI/monai/config/deviceconfig.py b/testbed/Project-MONAI__MONAI/monai/config/deviceconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcecb18137773e8070fa1ea9623936c21cf1eda --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/config/deviceconfig.py @@ -0,0 +1,148 @@ +# Copyright 2020 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. + +import os +import sys +from collections import OrderedDict + +import numpy as np +import torch + +import monai + +try: + import ignite + + ignite_version = ignite.__version__ + del ignite +except (ImportError, AttributeError): + ignite_version = "NOT INSTALLED or UNKNOWN VERSION." + +try: + import nibabel + + nibabel_version = nibabel.__version__ + del nibabel +except (ImportError, AttributeError): + nibabel_version = "NOT INSTALLED or UNKNOWN VERSION." + +try: + import skimage + + skimage_version = skimage.__version__ + del skimage +except (ImportError, AttributeError): + skimage_version = "NOT INSTALLED or UNKNOWN VERSION." + +try: + import PIL + + PIL_version = PIL.__version__ + del PIL +except (ImportError, AttributeError): + PIL_version = "NOT INSTALLED or UNKNOWN VERSION." + +try: + import tensorboard + + tensorboard_version = tensorboard.__version__ + del tensorboard +except (ImportError, AttributeError): + tensorboard_version = "NOT INSTALLED or UNKNOWN VERSION." + +try: + import gdown + + gdown_version = gdown.__version__ + del gdown +except (ImportError, AttributeError): + gdown_version = "NOT INSTALLED or UNKNOWN VERSION." + +try: + import torchvision + + torchvision_version = torchvision.__version__ + del torchvision +except (ImportError, AttributeError): + torchvision_version = "NOT INSTALLED or UNKNOWN VERSION." + +try: + import itk # type: ignore + + itk_version = itk.Version.GetITKVersion() + del itk +except (ImportError, AttributeError): + itk_version = "NOT INSTALLED or UNKNOWN VERSION." + + +def get_config_values(): + """ + Read the package versions into a dictionary. + """ + output = OrderedDict() + + output["MONAI"] = monai.__version__ + output["Python"] = sys.version.replace("\n", " ") + output["Numpy"] = np.version.full_version + output["Pytorch"] = torch.__version__ + + return output + + +def get_optional_config_values(): + """ + Read the optional package versions into a dictionary. + """ + output = OrderedDict() + + output["Pytorch Ignite"] = ignite_version + output["Nibabel"] = nibabel_version + output["scikit-image"] = skimage_version + output["Pillow"] = PIL_version + output["Tensorboard"] = tensorboard_version + output["gdown"] = gdown_version + output["TorchVision"] = torchvision_version + output["ITK"] = itk_version + + return output + + +def print_config(file=sys.stdout): + """ + Print the package versions to `file`. + + Args: + file: `print()` text stream file. Defaults to `sys.stdout`. + """ + for k, v in get_config_values().items(): + print(f"{k} version: {v}", file=file, flush=True) + + print("\nOptional dependencies:", file=file, flush=True) + for k, v in get_optional_config_values().items(): + print(f"{k} version: {v}", file=file, flush=True) + print("\nFor details about installing the optional dependencies, please visit:", file=file, flush=True) + print( + " https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n", + file=file, + flush=True, + ) + + +def set_visible_devices(*dev_inds): + os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, dev_inds)) + + +def get_torch_version_tuple(): + """ + Returns: + tuple of ints represents the pytorch major/minor version. + """ + return tuple((int(x) for x in torch.__version__.split(".")[:2])) diff --git a/testbed/Project-MONAI__MONAI/monai/config/type_definitions.py b/testbed/Project-MONAI__MONAI/monai/config/type_definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd75a7e90baef06be72dfe412905755743a54a6 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/config/type_definitions.py @@ -0,0 +1,51 @@ +# Copyright 2020 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 typing import Collection, Hashable, Iterable, Union + +"""Commonly used concepts +This module provides naming and type specifications for commonly used concepts +within the MONAI package. The intent is to explicitly identify information +that should be used consistently throughout the entire MONAI package. + +A type would be named as type_definitions.KeysCollection +which includes a meaningful name for the concent in the name itself. The +definitions in this file map context meaningful names to the underlying +object properties that define the expected API. + +A conceptual type is represented by a new type name but is also one which +can be different depending on an environment (i.e. differences for python 3.6 vs 3.9 +may be implemented). Consistent use of the concept and recorded documentation of +the rationale and convention behind it lowers the learning curve for new +developers. For readability, short names are preferred. +""" + +KeysCollection = Union[Collection[Hashable], Hashable] +"""KeysCollection + +The KeyCollection type is used to for defining variables +that store a subset of keys to select items from a dictionary. +The container of keys must contain hashable elements. +NOTE: `Hashable` is not a collection, but is provided as a + convenience to end-users. All supplied values will be + internally converted to a tuple of `Hashable`'s before + use +""" + + +IndexSelection = Union[Iterable[int], int] +"""IndexSelection + +The IndexSelection type is used to for defining variables +that store a subset of indices to select items from a List or Array like objects. +The indices must be integers, and if a container of indices is specified, the +container must be iterable. +""" diff --git a/testbed/Project-MONAI__MONAI/monai/data/__init__.py b/testbed/Project-MONAI__MONAI/monai/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da11cdf45db86fc3d091b7950620c43b6fc43775 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2020 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 .csv_saver import CSVSaver +from .dataloader import DataLoader +from .dataset import ArrayDataset, CacheDataset, Dataset, PersistentDataset, SmartCacheDataset, ZipDataset +from .decathalon_datalist import load_decathalon_datalist +from .grid_dataset import GridPatchDataset +from .image_reader import * +from .nifti_reader import NiftiDataset +from .nifti_saver import NiftiSaver +from .nifti_writer import write_nifti +from .png_saver import PNGSaver +from .png_writer import write_png +from .synthetic import * +from .utils import * diff --git a/testbed/Project-MONAI__MONAI/monai/data/csv_saver.py b/testbed/Project-MONAI__MONAI/monai/data/csv_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..7654bfdeb3445bae42b08c6ada0f48cd63c59428 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/csv_saver.py @@ -0,0 +1,91 @@ +# Copyright 2020 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. + +import csv +import os +from collections import OrderedDict +from typing import Dict, Optional, Union + +import numpy as np +import torch + + +class CSVSaver: + """ + Save the data in a dictionary format cache, and write to a CSV file finally. + Typically, the data can be classification predictions, call `save` for single data + or call `save_batch` to save a batch of data together, and call `finalize` to write + the cached data into CSV file. If no meta data provided, use index from 0 to save data. + """ + + def __init__(self, output_dir: str = "./", filename: str = "predictions.csv", overwrite: bool = True) -> None: + """ + Args: + output_dir: output CSV file directory. + filename: name of the saved CSV file name. + overwrite: whether to overwriting existing CSV file content. If we are not overwriting, + then we check if the results have been previously saved, and load them to the prediction_dict. + + """ + self.output_dir = output_dir + self._cache_dict: OrderedDict = OrderedDict() + assert isinstance(filename, str) and filename[-4:] == ".csv", "filename must be a string with CSV format." + self._filepath = os.path.join(output_dir, filename) + self.overwrite = overwrite + self._data_index = 0 + + def finalize(self) -> None: + """ + Writes the cached dict to a csv + + """ + if not self.overwrite and os.path.exists(self._filepath): + with open(self._filepath, "r") as f: + reader = csv.reader(f) + for row in reader: + self._cache_dict[row[0]] = np.array(row[1:]).astype(np.float32) + + if not os.path.exists(self.output_dir): + os.makedirs(self.output_dir) + with open(self._filepath, "w") as f: + for k, v in self._cache_dict.items(): + f.write(k) + for result in v.flatten(): + f.write("," + str(result)) + f.write("\n") + + def save(self, data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None) -> None: + """Save data into the cache dictionary. The metadata should have the following key: + - ``'filename_or_obj'`` -- save the data corresponding to file name or object. + If meta_data is None, use the default index from 0 to save data instead. + + Args: + data: target data content that save into cache. + meta_data: the meta data information corresponding to the data. + + """ + save_key = meta_data["filename_or_obj"] if meta_data else str(self._data_index) + self._data_index += 1 + if torch.is_tensor(data): + data = data.detach().cpu().numpy() + assert isinstance(data, np.ndarray) + self._cache_dict[save_key] = data.astype(np.float32) + + def save_batch(self, batch_data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None) -> None: + """Save a batch of data into the cache dictionary. + + Args: + batch_data: target batch data content that save into cache. + meta_data: every key-value in the meta_data is corresponding to 1 batch of data. + + """ + for i, data in enumerate(batch_data): # save a batch of files + self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None) diff --git a/testbed/Project-MONAI__MONAI/monai/data/dataloader.py b/testbed/Project-MONAI__MONAI/monai/data/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9c174c5dab20cd2dd95cb79fa83b0823f949d3 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/dataloader.py @@ -0,0 +1,80 @@ +# Copyright 2020 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 typing import Callable, Optional + +from torch.utils.data import DataLoader as _TorchDataLoader +from torch.utils.data import Dataset, Sampler + +from monai.data.utils import list_data_collate, worker_init_fn + +__all__ = ["DataLoader"] + + +class DataLoader(_TorchDataLoader): + """Generates images/labels for train/validation/testing from dataset. + It inherits from PyTorch DataLoader and adds callbacks for `collate` and `worker_fn`. + + Args: + dataset: dataset from which to load the data. + batch_size: how many samples per batch to load + (default: ``1``). + shuffle: set to ``True`` to have the data reshuffled + at every epoch (default: ``False``). + sampler: defines the strategy to draw samples from + the dataset. If specified, :attr:`shuffle` must be ``False``. + batch_sampler: like :attr:`sampler`, but returns a batch of + indices at a time. Mutually exclusive with :attr:`batch_size`, + :attr:`shuffle`, :attr:`sampler`, and :attr:`drop_last`. + num_workers: how many subprocesses to use for data + loading. ``0`` means that the data will be loaded in the main process. + (default: ``0``) + pin_memory: If ``True``, the data loader will copy Tensors + into CUDA pinned memory before returning them. If your data elements + are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type, + see the example below. + drop_last: set to ``True`` to drop the last incomplete batch, + if the dataset size is not divisible by the batch size. If ``False`` and + the size of dataset is not divisible by the batch size, then the last batch + will be smaller. (default: ``False``) + timeout: if positive, the timeout value for collecting a batch + from workers. Should always be non-negative. (default: ``0``) + multiprocessing_context: specify a valid start method for multi-processing. + + """ + + def __init__( + self, + dataset: Dataset, + batch_size: int = 1, + shuffle: bool = False, + sampler: Optional[Sampler] = None, + batch_sampler: Optional[Sampler] = None, + num_workers: int = 0, + pin_memory: bool = False, + drop_last: bool = False, + timeout: float = 0.0, + multiprocessing_context: Optional[Callable] = None, + ) -> None: + super().__init__( # type: ignore[call-overload] + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + sampler=sampler, + batch_sampler=batch_sampler, + num_workers=num_workers, + collate_fn=list_data_collate, + pin_memory=pin_memory, + drop_last=drop_last, + timeout=timeout, + worker_init_fn=worker_init_fn, + multiprocessing_context=multiprocessing_context, + ) diff --git a/testbed/Project-MONAI__MONAI/monai/data/dataset.py b/testbed/Project-MONAI__MONAI/monai/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9995d881e061b2d9509c561cda82ff00de21f213 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/dataset.py @@ -0,0 +1,705 @@ +# Copyright 2020 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. + +import hashlib +import json +import math +import sys +import threading +import time +from multiprocessing.pool import ThreadPool +from pathlib import Path +from typing import Any, Callable, List, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +from torch.utils.data import Dataset as _TorchDataset + +from monai.transforms import Compose, Randomizable, Transform, apply_transform +from monai.utils import get_seed, progress_bar + + +class Dataset(_TorchDataset): + """ + A generic dataset with a length property and an optional callable data transform + when fetching a data sample. + For example, typical input data can be a list of dictionaries:: + + [{ { { + 'img': 'image1.nii.gz', 'img': 'image2.nii.gz', 'img': 'image3.nii.gz', + 'seg': 'label1.nii.gz', 'seg': 'label2.nii.gz', 'seg': 'label3.nii.gz', + 'extra': 123 'extra': 456 'extra': 789 + }, }, }] + """ + + def __init__(self, data: Sequence, transform: Optional[Callable] = None) -> None: + """ + Args: + data: input data to load and transform to generate dataset for model. + transform: a callable data transform on input data. + """ + self.data = data + self.transform = transform + + def __len__(self) -> int: + return len(self.data) + + def __getitem__(self, index: int): + data = self.data[index] + if self.transform is not None: + data = apply_transform(self.transform, data) + + return data + + +class PersistentDataset(Dataset): + """ + Persistent storage of pre-computed values to efficiently manage larger than memory dictionary format data, + it can operate transforms for specific fields. Results from the non-random transform components are computed + when first used, and stored in the `cache_dir` for rapid retrieval on subsequent uses. + + For example, typical input data can be a list of dictionaries:: + + [{ { { + 'img': 'image1.nii.gz', 'img': 'image2.nii.gz', 'img': 'image3.nii.gz', + 'seg': 'label1.nii.gz', 'seg': 'label2.nii.gz', 'seg': 'label3.nii.gz', + 'extra': 123 'extra': 456 'extra': 789 + }, }, }] + + For a composite transform like + + .. code-block:: python + + [ LoadNiftid(keys=['image', 'label']), + Orientationd(keys=['image', 'label'], axcodes='RAS'), + ScaleIntensityRanged(keys=['image'], a_min=-57, a_max=164, b_min=0.0, b_max=1.0, clip=True), + RandCropByPosNegLabeld(keys=['image', 'label'], label_key='label', spatial_size=(96, 96, 96), + pos=1, neg=1, num_samples=4, image_key='image', image_threshold=0), + ToTensord(keys=['image', 'label'])] + + Upon first use a filename based dataset will be processed by the transform for the + [LoadNiftid, Orientationd, ScaleIntensityRanged] and the resulting tensor written to + the `cache_dir` before applying the remaining random dependant transforms + [RandCropByPosNegLabeld, ToTensord] elements for use in the analysis. + + Subsequent uses of a dataset directly read pre-processed results from `cache_dir` + followed by applying the random dependant parts of transform processing. + + Note: + The input data must be a list of file paths and will hash them as cache keys. + + """ + + def __init__( + self, + data: Sequence[str], + transform: Union[Sequence[Callable], Callable], + cache_dir: Optional[Union[Path, str]] = None, + ) -> None: + """ + Args: + data: input data file paths to load and transform to generate dataset for model. + `PersistentDataset` expects input data to be a list of file paths and hashes them as cache keys. + transform: transforms to execute operations on input data. + cache_dir: If specified, this is the location for persistent storage + of pre-computed transformed data tensors. The cache_dir is computed once, and + persists on disk until explicitly removed. Different runs, programs, experiments + may share a common cache dir provided that the transforms pre-processing is consistent. + If the cache_dir doesn't exist, will automatically create it. + """ + if not isinstance(transform, Compose): + transform = Compose(transform) + super().__init__(data=data, transform=transform) + self.cache_dir = Path(cache_dir) if cache_dir is not None else None + if self.cache_dir is not None: + if not self.cache_dir.exists(): + self.cache_dir.mkdir(parents=True) + if not self.cache_dir.is_dir(): + raise ValueError("cache_dir must be a directory.") + + def _pre_first_random_transform(self, item_transformed): + """ + Process the data from original state up to the first random element. + + Args: + item_transformed: The data to be transformed + + Returns: + the transformed element up to the first identified + random transform object + """ + for _transform in self.transform.transforms: # pytype: disable=attribute-error + # execute all the deterministic transforms + if isinstance(_transform, Randomizable) or not isinstance(_transform, Transform): + break + item_transformed = apply_transform(_transform, item_transformed) + return item_transformed + + def _first_random_and_beyond_transform(self, item_transformed): + """ + Process the data from before the first random transform to the final state ready for evaluation. + + Args: + item_transformed: The data to be transformed (already processed up to the first random transform) + + Returns: + the transformed element through the random transforms + """ + start_post_randomize_run = False + for _transform in self.transform.transforms: # pytype: disable=attribute-error + if ( + start_post_randomize_run + or isinstance(_transform, Randomizable) + or not isinstance(_transform, Transform) + ): + start_post_randomize_run = True + item_transformed = apply_transform(_transform, item_transformed) + return item_transformed + + def _pre_first_random_cachecheck(self, item_transformed): + """ + A function to cache the expensive input data transform operations + so that huge data sets (larger than computer memory) can be processed + on the fly as needed, and intermediate results written to disk for + future use. + + Args: + item_transformed: The current data element to be mutated into transformed representation + + Returns: + The transformed data_element, either from cache, or explicitly computing it. + + Warning: + The current implementation does not encode transform information as part of the + hashing mechanism used for generating cache names. If the transforms applied are + changed in any way, the objects in the cache dir will be invalid. The hash for the + cache is ONLY dependant on the input filename paths. + """ + if item_transformed.get("cached", False) is False: + hashfile = None + if self.cache_dir is not None: + # TODO: Find way to hash transforms content as part of the cache + data_item_md5 = hashlib.md5(json.dumps(item_transformed, sort_keys=True).encode("utf-8")).hexdigest() + hashfile = self.cache_dir / f"{data_item_md5}.pt" + + if hashfile is not None and hashfile.is_file(): + item_transformed = torch.load(hashfile) + else: + item_transformed = self._pre_first_random_transform(item_transformed) + if hashfile is not None: + # add sentinel flag to indicate that the transforms have already been computed. + item_transformed["cached"] = True + # NOTE: Writing to ".temp_write_cache" and then using a nearly atomic rename operation + # to make the cache more robust to manual killing of parent process + # which may leave partially written cache files in an incomplete state + temp_hash_file = hashfile.with_suffix(".temp_write_cache") + torch.save(item_transformed, temp_hash_file) + temp_hash_file.rename(hashfile) + + return item_transformed + + def __getitem__(self, index: int): + pre_random_item = self._pre_first_random_cachecheck(self.data[index]) + post_random_item = self._first_random_and_beyond_transform(pre_random_item) + return post_random_item + + +class CacheDataset(Dataset): + """ + Dataset with cache mechanism that can load data and cache deterministic transforms' result during training. + + By caching the results of non-random preprocessing transforms, it accelerates the training data pipeline. + If the requested data is not in the cache, all transforms will run normally + (see also :py:class:`monai.data.dataset.Dataset`). + + Users can set the cache rate or number of items to cache. + It is recommended to experiment with different `cache_num` or `cache_rate` to identify the best training speed. + + To improve the caching efficiency, please always put as many as possible non-random transforms + before the randomized ones when composing the chain of transforms. + + For example, if the transform is a `Compose` of:: + + transforms = Compose([ + LoadNiftid(), + AddChanneld(), + Spacingd(), + Orientationd(), + ScaleIntensityRanged(), + RandCropByPosNegLabeld(), + ToTensord() + ]) + + when `transforms` is used in a multi-epoch training pipeline, before the first training epoch, + this dataset will cache the results up to ``ScaleIntensityRanged``, as + all non-random transforms `LoadNiftid`, `AddChanneld`, `Spacingd`, `Orientationd`, `ScaleIntensityRanged` + can be cached. During training, the dataset will load the cached results and run + ``RandCropByPosNegLabeld`` and ``ToTensord``, as ``RandCropByPosNegLabeld`` is a randomized transform + and the outcome not cached. + """ + + def __init__( + self, + data: Sequence, + transform: Union[Sequence[Callable], Callable], + cache_num: int = sys.maxsize, + cache_rate: float = 1.0, + num_workers: int = 0, + ) -> None: + """ + Args: + data: input data to load and transform to generate dataset for model. + transform: transforms to execute operations on input data. + cache_num: number of items to be cached. Default is `sys.maxsize`. + will take the minimum of (cache_num, data_length x cache_rate, data_length). + cache_rate: percentage of cached data in total, default is 1.0 (cache all). + will take the minimum of (cache_num, data_length x cache_rate, data_length). + num_workers: the number of worker threads to use. + If 0 a single thread will be used. Default is 0. + """ + if not isinstance(transform, Compose): + transform = Compose(transform) + super().__init__(data, transform) + self.cache_num = min(cache_num, int(len(data) * cache_rate), len(data)) + if self.cache_num > 0: + self._cache = [None] * self.cache_num + if num_workers > 0: + self._item_processed = 0 + self._thread_lock = threading.Lock() + with ThreadPool(num_workers) as p: + p.map( + self._load_cache_item_thread, + [(i, data[i], transform.transforms) for i in range(self.cache_num)], + ) + else: + for i in range(self.cache_num): + self._cache[i] = self._load_cache_item(data[i], transform.transforms) + progress_bar(i + 1, self.cache_num, "Load and cache transformed data: ") + + def _load_cache_item(self, item: Any, transforms: Sequence[Callable]): + """ + Args: + item: input item to load and transform to generate dataset for model. + transforms: transforms to execute operations on input item. + """ + for _transform in transforms: + # execute all the deterministic transforms + if isinstance(_transform, Randomizable) or not isinstance(_transform, Transform): + break + item = apply_transform(_transform, item) + return item + + def _load_cache_item_thread(self, args: Tuple[int, Any, Sequence[Callable]]) -> None: + """ + Args: + args: tuple with contents (i, item, transforms). + i: the index to load the cached item to. + item: input item to load and transform to generate dataset for model. + transforms: transforms to execute operations on input item. + """ + i, item, transforms = args + self._cache[i] = self._load_cache_item(item, transforms) + with self._thread_lock: + self._item_processed += 1 + progress_bar(self._item_processed, self.cache_num, "Load and cache transformed data: ") + + def __getitem__(self, index): + if index < self.cache_num: + # load data from cache and execute from the first random transform + start_run = False + data = self._cache[index] + for _transform in self.transform.transforms: # pytype: disable=attribute-error + if not start_run and not isinstance(_transform, Randomizable) and isinstance(_transform, Transform): + continue + else: + start_run = True + data = apply_transform(_transform, data) + else: + # no cache for this data, execute all the transforms directly + data = super(CacheDataset, self).__getitem__(index) + return data + + +class SmartCacheDataset(CacheDataset): + """ + Re-implementation of the SmartCache mechanism in NVIDIA Clara-train SDK. + At any time, the cache pool only keeps a subset of the whole dataset. In each epoch, only the items + in the cache are used for training. This ensures that data needed for training is readily available, + keeping GPU resources busy. Note that cached items may still have to go through a non-deterministic + transform sequence before being fed to GPU. At the same time, another thread is preparing replacement + items by applying the transform sequence to items not in cache. Once one epoch is completed, Smart + Cache replaces the same number of items with replacement items. + Smart Cache uses a simple `running window` algorithm to determine the cache content and replacement items. + Let N be the configured number of objects in cache; and R be the number of replacement objects (R = ceil(N * r), + where r is the configured replace rate). + For more details, please refer to: + https://docs.nvidia.com/clara/tlt-mi/clara-train-sdk-v3.0/nvmidl/additional_features/smart_cache.html#smart-cache + + For example, if we have 5 images: `[image1, image2, image3, image4, image5]`, and `cache_num=4`, `replace_rate=0.25`. + so the actual training images cached and replaced for every epoch are as below: + epoch 1: [image1, image2, image3, image4] + epoch 2: [image2, image3, image4, image5] + epoch 3: [image3, image4, image5, image1] + epoch 3: [image4, image5, image1, image2] + epoch N: [image[N % 5] ...] + + The usage of `SmartCacheDataset` contains 4 steps: + 1. Initialize `SmartCacheDataset` object and cache for the first epoch. + 2. Call `start()` to run replacement thread in background. + 3. Call `update_cache()` before every epoch to replace training items. + 4. Call `shutdown()` when training ends. + + """ + + def __init__( + self, + data: Sequence, + transform: Union[Sequence[Callable], Callable], + replace_rate: float, + cache_num: int = sys.maxsize, + cache_rate: float = 1.0, + num_init_workers: int = 0, + num_replace_workers: int = 0, + ) -> None: + """ + Args: + data: input data to load and transform to generate dataset for model. + transform: transforms to execute operations on input data. + replace_rate: percentage of the cached items to be replaced in every epoch. + cache_num: number of items to be cached. Default is `sys.maxsize`. + will take the minimum of (cache_num, data_length x cache_rate, data_length). + cache_rate: percentage of cached data in total, default is 1.0 (cache all). + will take the minimum of (cache_num, data_length x cache_rate, data_length). + num_init_workers: the number of worker threads to initialize the cache for first epoch. + if 0, run in main thread, no separate thread will open. + num_replace_workers: the number of worker threads to prepare the replacement cache for every epoch. + if 0, run in main thread, no separate thread will open. + """ + super().__init__(data, transform, cache_num, cache_rate, num_init_workers) + if self.cache_num >= len(data): + raise ValueError("cache_num must be smaller than dataset length to support replacement.") + if replace_rate <= 0: + raise ValueError("replace_rate must be greater than 0, otherwise, please use CacheDataset.") + self.num_replace_workers: int = num_replace_workers + + self._total_num: int = len(data) + self._replace_num: int = min(math.ceil(self.cache_num * replace_rate), len(data) - self.cache_num) + self._replacements: List[Any] = [None for _ in range(self._replace_num)] + self._replace_data_idx: List[int] = list(range(self._replace_num)) + + self._start_pos: int = 0 + self._update_lock: threading.Lock = threading.Lock() + self._round: int = 1 + self._replace_done: bool = False + self._replace_mgr: Optional[threading.Thread] = None + + self._compute_data_idx() + + def _compute_data_idx(self): + """ + Update the replacement data position in the total data. + + """ + for i in range(self._replace_num): + pos: int = self._start_pos + self.cache_num + i + if pos >= self._total_num: + pos -= self._total_num + self._replace_data_idx[i] = pos + + def is_started(self): + """ + Check whether the replacement thread is already started. + + """ + if self._replace_mgr is None: + return False + return self._replace_mgr.isAlive() + + def start(self): + """ + Start the background thread to replace training items for every epoch. + + """ + if self._replace_mgr is None or not self.is_started(): + self._restart() + + def _restart(self): + """ + Restart background thread if killed for some reason. + + """ + self._round = 1 + self._replace_mgr = threading.Thread(target=self.manage_replacement, daemon=True) + self._replace_mgr.start() + + def _try_update_cache(self): + """ + Update the cache items with new replacement for current epoch. + + """ + with self._update_lock: + if self._replace_done: + remain_num: int = self.cache_num - self._replace_num + for i in range(remain_num): + self._cache[i] = self._cache[i + self._replace_num] + for i in range(self._replace_num): + self._cache[remain_num + i] = self._replacements[i] + + self._start_pos += self._replace_num + if self._start_pos >= self._total_num: + self._start_pos -= self._total_num + + self._compute_data_idx() + + # ready for next round + self._round += 1 + self._replace_done = False + return True + else: + return False + + def update_cache(self): + """ + Update cache items for current epoch, need to call this function before every epoch. + If the cache has been shutdown before, need to restart the `_replace_mgr` thread. + + """ + if not self._replace_mgr.isAlive(): + self._restart() + + # make sure update is done + while not self._try_update_cache(): + time.sleep(0.01) + + def _try_shutdown(self): + """ + Wait for thread lock to shut down the background thread. + + """ + with self._update_lock: + if self._replace_done: + self._round = 0 + self._replace_done = False + return True + else: + return False + + def shutdown(self): + """ + Shut down the background thread for replacement. + + """ + if not self.is_started(): + return + + # wait until replace mgr is done the current round + while not self._try_shutdown(): + time.sleep(0.01) + self._replace_mgr.join() + + def _replace_cache_thread(self, index: int): + """ + Execute deterministic transforms on the new data for replacement. + + """ + pos: int = self._replace_data_idx[index] + self._replacements[index] = self._load_cache_item(self.data[pos], self.transform.transforms) # type: ignore + + def _compute_replacements(self): + """ + Compute expected items for the replacement of next epoch, execute deterministic transforms. + It can support multi-threads to accelerate the computation progress. + + """ + if self.num_replace_workers > 0: + with ThreadPool(self.num_replace_workers) as p: + p.map(self._replace_cache_thread, list(range(self._replace_num))) + else: + for i in range(self._replace_num): + self._replace_cache_thread(i) + self._replace_done = True + + def _try_manage_replacement(self, check_round): + """ + Wait thread lock and replace training items in the background thread. + + """ + with self._update_lock: + if self._round <= 0: + # shutdown replacement + self._replace_done = True + return True, -1 + + if self._round != check_round: + self._compute_replacements() + return False, self._round + + def manage_replacement(self): + """ + Background thread for replacement. + + """ + check_round: int = -1 + done = False + while not done: + done, check_round = self._try_manage_replacement(check_round) + time.sleep(0.01) + + def __len__(self): + """ + The dataset length is given by cache_num instead of len(data). + + """ + return self.cache_num + + +class ZipDataset(Dataset): + """ + Zip several PyTorch datasets and output data(with the same index) together in a tuple. + If the output of single dataset is already a tuple, flatten it and extend to the result. + For example: if datasetA returns (img, imgmeta), datasetB returns (seg, segmeta), + finally return (img, imgmeta, seg, segmeta). + And if the datasets don't have same length, use the minimum length of them as the length + of ZipDataset. + + Examples:: + + >>> zip_data = ZipDataset([[1, 2, 3], [4, 5]]) + >>> print(len(zip_data)) + 2 + >>> for item in zip_data: + >>> print(item) + [1, 4] + [2, 5] + + """ + + def __init__(self, datasets: Sequence, transform: Optional[Callable] = None) -> None: + """ + Args: + datasets: list of datasets to zip together. + transform: a callable data transform operates on the zipped item from `datasets`. + """ + super().__init__(list(datasets), transform=transform) + + def __len__(self) -> int: + return min((len(dataset) for dataset in self.data)) + + def __getitem__(self, index: int): + def to_list(x): + return list(x) if isinstance(x, (tuple, list)) else [x] + + data = list() + for dataset in self.data: + data.extend(to_list(dataset[index])) + if self.transform is not None: + data = apply_transform(self.transform, data, map_items=False) # transform the list data + # use tuple instead of list as the default collate_fn callback of MONAI DataLoader flattens nested lists + return tuple(data) + + +class ArrayDataset(Randomizable, _TorchDataset): + """ + Dataset for segmentation and classification tasks based on array format input data and transforms. + It ensures the same random seeds in the randomized transforms defined for image, segmentation and label. + The `transform` can be :py:class:`monai.transforms.Compose` or any other callable object. + For example: + If train based on Nifti format images without metadata, all transforms can be composed:: + + img_transform = Compose( + [ + LoadNifti(image_only=True), + AddChannel(), + RandAdjustContrast() + ] + ) + ArrayDataset(img_file_list, img_transform=img_transform) + + If training based on images and the metadata, the array transforms can not be composed + because several transforms receives multiple parameters or return multiple values. Then Users need + to define their own callable method to parse metadata from `LoadNifti` or set `affine` matrix + to `Spacing` transform:: + + class TestCompose(Compose): + def __call__(self, input_): + img, metadata = self.transforms[0](input_) + img = self.transforms[1](img) + img, _, _ = self.transforms[2](img, metadata["affine"]) + return self.transforms[3](img), metadata + img_transform = TestCompose( + [ + LoadNifti(image_only=False), + AddChannel(), + Spacing(pixdim=(1.5, 1.5, 3.0)), + RandAdjustContrast() + ] + ) + ArrayDataset(img_file_list, img_transform=img_transform) + + Examples:: + + >>> ds = ArrayDataset([1, 2, 3, 4], lambda x: x + 0.1) + >>> print(ds[0]) + 1.1 + + >>> ds = ArrayDataset(img=[1, 2, 3, 4], seg=[5, 6, 7, 8]) + >>> print(ds[0]) + [1, 5] + + """ + + def __init__( + self, + img: Sequence, + img_transform: Optional[Callable] = None, + seg: Optional[Sequence] = None, + seg_transform: Optional[Callable] = None, + labels: Optional[Sequence] = None, + label_transform: Optional[Callable] = None, + ) -> None: + """ + Initializes the dataset with the filename lists. The transform `img_transform` is applied + to the images and `seg_transform` to the segmentations. + + Args: + img: sequence of images. + img_transform: transform to apply to each element in `img`. + seg: sequence of segmentations. + seg_transform: transform to apply to each element in `seg`. + labels: sequence of labels. + label_transform: transform to apply to each element in `labels`. + + """ + items = [(img, img_transform), (seg, seg_transform), (labels, label_transform)] + self.set_random_state(seed=get_seed()) + datasets = [Dataset(x[0], x[1]) for x in items if x[0] is not None] + self.dataset = datasets[0] if len(datasets) == 1 else ZipDataset(datasets) + + self._seed = 0 # transform synchronization seed + + def __len__(self) -> int: + return len(self.dataset) + + def randomize(self, data: Optional[Any] = None) -> None: + self._seed = self.R.randint(np.iinfo(np.int32).max) + + def __getitem__(self, index: int): + self.randomize() + if isinstance(self.dataset, ZipDataset): + # set transforms of each zip component + for dataset in self.dataset.data: + transform = getattr(dataset, "transform", None) + if isinstance(transform, Randomizable): + transform.set_random_state(seed=self._seed) + transform = getattr(self.dataset, "transform", None) + if isinstance(transform, Randomizable): + transform.set_random_state(seed=self._seed) + return self.dataset[index] diff --git a/testbed/Project-MONAI__MONAI/monai/data/decathalon_datalist.py b/testbed/Project-MONAI__MONAI/monai/data/decathalon_datalist.py new file mode 100644 index 0000000000000000000000000000000000000000..be6bf60c497f0a98fea282586371f53321c0f07a --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/decathalon_datalist.py @@ -0,0 +1,115 @@ +# Copyright 2020 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. + +import json +import os +from typing import Dict, List, Optional, overload + + +@overload +def _compute_path(base_dir: str, element: str) -> str: + ... + + +@overload +def _compute_path(base_dir: str, element: List[str]) -> List[str]: + ... + + +def _compute_path(base_dir, element): + """ + Args: + base_dir: the base directory of the dataset. + element: file path(s) to append to directory. + + Raises: + TypeError: When ``element`` contains a non ``str``. + TypeError: When ``element`` type is not in ``Union[list, str]``. + + """ + if isinstance(element, str): + return os.path.normpath(os.path.join(base_dir, element)) + elif isinstance(element, list): + for e in element: + if not isinstance(e, str): + raise TypeError(f"Every file path in element must be a str but got {type(element).__name__}.") + return [os.path.normpath(os.path.join(base_dir, e)) for e in element] + else: + raise TypeError(f"element must be one of (str, list) but is {type(element).__name__}.") + + +def _append_paths(base_dir: str, is_segmentation: bool, items: List[Dict]) -> List[Dict]: + """ + Args: + base_dir: the base directory of the dataset. + is_segmentation: whether the datalist is for segmentation task. + items: list of data items, each of which is a dict keyed by element names. + + Raises: + TypeError: When ``items`` contains a non ``dict``. + + """ + for item in items: + if not isinstance(item, dict): + raise TypeError(f"Every item in items must be a dict but got {type(item).__name__}.") + for k, v in item.items(): + if k == "image": + item[k] = _compute_path(base_dir, v) + elif is_segmentation and k == "label": + item[k] = _compute_path(base_dir, v) + return items + + +def load_decathalon_datalist( + data_list_file_path: str, + is_segmentation: bool = True, + data_list_key: str = "training", + base_dir: Optional[str] = None, +) -> List[Dict]: + """Load image/label paths of decathalon challenge from JSON file + + Json file is similar to what you get from http://medicaldecathlon.com/ + Those dataset.json files + + Args: + data_list_file_path: the path to the json file of datalist. + is_segmentation: whether the datalist is for segmentation task, default is True. + data_list_key: the key to get a list of dictionary to be used, default is "training". + base_dir: the base directory of the dataset, if None, use the datalist directory. + + Raises: + ValueError: When ``data_list_file_path`` does not point to a file. + ValueError: When ``data_list_key`` is not specified in the data list file. + + Returns a list of data items, each of which is a dict keyed by element names, for example: + + .. code-block:: + + [ + {'image': '/workspace/data/chest_19.nii.gz', 'label': 0}, + {'image': '/workspace/data/chest_31.nii.gz', 'label': 1} + ] + + """ + if not os.path.isfile(data_list_file_path): + raise ValueError(f"Data list file {data_list_file_path} does not exist.") + with open(data_list_file_path) as json_file: + json_data = json.load(json_file) + if data_list_key not in json_data: + raise ValueError(f'Data list {data_list_key} not specified in "{data_list_file_path}".') + expected_data = json_data[data_list_key] + if data_list_key == "test": + expected_data = [{"image": i} for i in expected_data] + + if base_dir is None: + base_dir = os.path.dirname(data_list_file_path) + + return _append_paths(base_dir, is_segmentation, expected_data) diff --git a/testbed/Project-MONAI__MONAI/monai/data/grid_dataset.py b/testbed/Project-MONAI__MONAI/monai/data/grid_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..100dcf0c64960fb9913ab0f6983c19b7c00a2b37 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/grid_dataset.py @@ -0,0 +1,76 @@ +# Copyright 2020 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. + +import math +from typing import Dict, Sequence, Union + +import torch +from torch.utils.data import Dataset, IterableDataset + +from monai.data.utils import iter_patch +from monai.utils import NumpyPadMode, ensure_tuple + + +class GridPatchDataset(IterableDataset): + """ + Yields patches from arrays read from an input dataset. The patches are chosen in a contiguous grid sampling scheme. + """ + + def __init__( + self, + dataset: Dataset, + patch_size: Sequence[int], + start_pos: Sequence[int] = (), + mode: Union[NumpyPadMode, str] = NumpyPadMode.WRAP, + **pad_opts: Dict, + ) -> None: + """ + Initializes this dataset in terms of the input dataset and patch size. The `patch_size` is the size of the + patch to sample from the input arrays. It is assumed the arrays first dimension is the channel dimension which + will be yielded in its entirety so this should not be specified in `patch_size`. For example, for an input 3D + array with 1 channel of size (1, 20, 20, 20) a regular grid sampling of eight patches (1, 10, 10, 10) would be + specified by a `patch_size` of (10, 10, 10). + + Args: + dataset: the dataset to read array data from + patch_size: size of patches to generate slices for, 0/None selects whole dimension + start_pos: starting position in the array, default is 0 for each dimension + mode: {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, + ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + One of the listed string values or a user supplied function. Defaults to ``"wrap"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + pad_opts: padding options, see numpy.pad + """ + + self.dataset = dataset + self.patch_size = (None,) + tuple(patch_size) + self.start_pos = ensure_tuple(start_pos) + self.mode: NumpyPadMode = NumpyPadMode(mode) + self.pad_opts = pad_opts + + def __iter__(self): + worker_info = torch.utils.data.get_worker_info() + iter_start = 0 + iter_end = len(self.dataset) + + if worker_info is not None: + # split workload + per_worker = int(math.ceil((iter_end - iter_start) / float(worker_info.num_workers))) + worker_id = worker_info.id + iter_start = iter_start + worker_id * per_worker + iter_end = min(iter_start + per_worker, iter_end) + + for index in range(iter_start, iter_end): + arrays = self.dataset[index] + + iters = [iter_patch(a, self.patch_size, self.start_pos, False, self.mode, **self.pad_opts) for a in arrays] + + yield from zip(*iters) diff --git a/testbed/Project-MONAI__MONAI/monai/data/image_reader.py b/testbed/Project-MONAI__MONAI/monai/data/image_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..d2bdede4bd7c2aeaae585ff10febc0edd43307a1 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/image_reader.py @@ -0,0 +1,350 @@ +# Copyright 2020 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 abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union + +import numpy as np + +from monai.data.utils import correct_nifti_header_if_necessary +from monai.utils import ensure_tuple, optional_import + +from .utils import is_supported_format + +if TYPE_CHECKING: + import itk # type: ignore + import nibabel as nib + from itk import Image # type: ignore + from nibabel.nifti1 import Nifti1Image +else: + itk, _ = optional_import("itk", allow_namespace_pkg=True) + Image, _ = optional_import("itk", allow_namespace_pkg=True, name="Image") + nib, _ = optional_import("nibabel") + Nifti1Image, _ = optional_import("nibabel.nifti1", name="Nifti1Image") + + +class ImageReader(ABC): + """Abstract class to define interface APIs to load image files. + users need to call `read` to load image and then use `get_data` + to get the image data and properties from meta data. + + """ + + @abstractmethod + def verify_suffix(self, filename: Union[Sequence[str], str]) -> bool: + """ + Verify whether the specified file or files format is supported by current reader. + + Args: + filename: file name or a list of file names to read. + if a list of files, verify all the subffixes. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + @abstractmethod + def read(self, data: Union[Sequence[str], str, Any], **kwargs) -> Union[Sequence[Any], Any]: + """ + Read image data from specified file or files, or set a loaded image. + Note that it returns the raw data, so different readers return different image data type. + + Args: + data: file name or a list of file names to read, or a loaded image object. + kwargs: additional args for 3rd party reader API. + + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + @abstractmethod + def get_data(self) -> Tuple[np.ndarray, Dict]: + """ + Extract data array and meta data from loaded image and return them. + This function must return 2 objects, first is numpy array of image data, second is dict of meta data. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + +class ITKReader(ImageReader): + """ + Load medical images based on ITK library. + All the supported image formats can be found: + https://github.com/InsightSoftwareConsortium/ITK/tree/master/Modules/IO + + Args: + c_order_axis_indexing: if `True`, the numpy array will have C-order indexing. + this is the reverse of how indices are specified in ITK, i.e. k,j,i versus i,j,k. + however C-order indexing is expected by most algorithms in numpy / scipy. + + """ + + def __init__(self, c_order_axis_indexing: bool = False): + super().__init__() + self._img: Optional[Sequence[Image]] = None + self.c_order_axis_indexing = c_order_axis_indexing + + def verify_suffix(self, filename: Union[Sequence[str], str]) -> bool: + """ + Verify whether the specified file or files format is supported by ITK reader. + + Args: + filename: file name or a list of file names to read. + if a list of files, verify all the subffixes. + + """ + return True + + def read(self, data: Union[Sequence[str], str, Image], **kwargs): + """ + Read image data from specified file or files, or set a `itk.Image` object. + Note that the returned object is ITK image object or list of ITK image objects. + `self._img` is always a list, even only has 1 image. + + Args: + data: file name or a list of file names to read, or a `itk.Image` object for the usage that + the image data is already in memory and no need to read from file again. + kwargs: additional args for `itk.imread` API. more details about available args: + https://github.com/InsightSoftwareConsortium/ITK/blob/master/Wrapping/Generators/Python/itkExtras.py + + """ + self._img = list() + if isinstance(data, Image): + self._img.append(data) + return data + + filenames: Sequence[str] = ensure_tuple(data) + for name in filenames: + self._img.append(itk.imread(name, **kwargs)) + return self._img if len(filenames) > 1 else self._img[0] + + def get_data(self): + """ + Extract data array and meta data from loaded image and return them. + This function returns 2 objects, first is numpy array of image data, second is dict of meta data. + It constructs `affine`, `original_affine`, and `spatial_shape` and stores in meta dict. + If loading a list of files, stack them together and add a new dimension as first dimension, + and use the meta data of the first image to represent the stacked result. + + """ + img_array: List[np.ndarray] = list() + compatible_meta: Dict = None + if self._img is None: + raise RuntimeError("please call read() first then use get_data().") + + for img in self._img: + header = self._get_meta_dict(img) + header["original_affine"] = self._get_affine(img) + header["affine"] = header["original_affine"].copy() + header["spatial_shape"] = self._get_spatial_shape(img) + img_array.append(self._get_array_data(img)) + + if compatible_meta is None: + compatible_meta = header + else: + if not np.allclose(header["affine"], compatible_meta["affine"]): + raise RuntimeError("affine matrix of all images should be same.") + if not np.allclose(header["spatial_shape"], compatible_meta["spatial_shape"]): + raise RuntimeError("spatial_shape of all images should be same.") + + img_array_ = np.stack(img_array, axis=0) if len(img_array) > 1 else img_array[0] + return img_array_, compatible_meta + + def _get_meta_dict(self, img: Image) -> Dict: + """ + Get all the meta data of the image and convert to dict type. + + Args: + img: a ITK image object loaded from a image file. + + """ + img_meta_dict = img.GetMetaDataDictionary() + meta_dict = dict() + for key in img_meta_dict.GetKeys(): + # ignore deprecated, legacy members that cause issues + if key.startswith("ITK_original_"): + continue + meta_dict[key] = img_meta_dict[key] + meta_dict["origin"] = np.asarray(img.GetOrigin()) + meta_dict["spacing"] = np.asarray(img.GetSpacing()) + meta_dict["direction"] = itk.array_from_matrix(img.GetDirection()) + return meta_dict + + def _get_affine(self, img: Image) -> np.ndarray: + """ + Get or construct the affine matrix of the image, it can be used to correct + spacing, orientation or execute spatial transforms. + Construct Affine matrix based on direction, spacing, origin information. + Refer to: https://github.com/RSIP-Vision/medio + + Args: + img: a ITK image object loaded from a image file. + + """ + direction = itk.array_from_matrix(img.GetDirection()) + spacing = np.asarray(img.GetSpacing()) + origin = np.asarray(img.GetOrigin()) + + direction = np.asarray(direction) + affine = np.eye(direction.shape[0] + 1) + affine[(slice(-1), slice(-1))] = direction @ np.diag(spacing) + affine[(slice(-1), -1)] = origin + return affine + + def _get_spatial_shape(self, img: Image) -> Sequence: + """ + Get the spatial shape of image data, it doesn't contain the channel dim. + + Args: + img: a ITK image object loaded from a image file. + + """ + return list(itk.size(img)) + + def _get_array_data(self, img: Image) -> np.ndarray: + """ + Get the raw array data of the image, converted to Numpy array. + + Args: + img: a ITK image object loaded from a image file. + + """ + return itk.array_view_from_image(img, keep_axes=not self.c_order_axis_indexing) + + +class NibabelReader(ImageReader): + """ + Load NIfTI format images based on Nibabel library. + + Args: + as_closest_canonical: if True, load the image as closest to canonical axis format. + + """ + + def __init__(self, as_closest_canonical: bool = False): + super().__init__() + self._img: Optional[Sequence[Nifti1Image]] = None + self.as_closest_canonical = as_closest_canonical + + def verify_suffix(self, filename: Union[Sequence[str], str]) -> bool: + """ + Verify whether the specified file or files format is supported by Nibabel reader. + + Args: + filename: file name or a list of file names to read. + if a list of files, verify all the subffixes. + + """ + suffixes: Sequence[str] = ["nii", "nii.gz"] + return is_supported_format(filename, suffixes) + + def read(self, data: Union[Sequence[str], str, Nifti1Image], **kwargs): + """ + Read image data from specified file or files, or set a Nibabel Image object. + Note that the returned object is Nibabel image object or list of Nibabel image objects. + `self._img` is always a list, even only has 1 image. + + Args: + data: file name or a list of file names to read. + kwargs: additional args for `nibabel.load` API. more details about available args: + https://github.com/nipy/nibabel/blob/master/nibabel/loadsave.py + + """ + self._img = list() + if isinstance(data, Nifti1Image): + self._img.append(data) + return data + + filenames: Sequence[str] = ensure_tuple(data) + for name in filenames: + img = nib.load(name, **kwargs) + img = correct_nifti_header_if_necessary(img) + self._img.append(img) + return self._img if len(filenames) > 1 else self._img[0] + + def get_data(self): + """ + Extract data array and meta data from loaded image and return them. + This function returns 2 objects, first is numpy array of image data, second is dict of meta data. + It constructs `affine`, `original_affine`, and `spatial_shape` and stores in meta dict. + If loading a list of files, stack them together and add a new dimension as first dimension, + and use the meta data of the first image to represent the stacked result. + + """ + img_array: List[np.ndarray] = list() + compatible_meta: Dict = None + if self._img is None: + raise RuntimeError("please call read() first then use get_data().") + + for img in self._img: + header = self._get_meta_dict(img) + header["original_affine"] = self._get_affine(img) + header["affine"] = header["original_affine"].copy() + if self.as_closest_canonical: + img = nib.as_closest_canonical(img) + header["affine"] = self._get_affine(img) + header["as_closest_canonical"] = self.as_closest_canonical + header["spatial_shape"] = self._get_spatial_shape(img) + img_array.append(self._get_array_data(img)) + + if compatible_meta is None: + compatible_meta = header + else: + if not np.allclose(header["affine"], compatible_meta["affine"]): + raise RuntimeError("affine matrix of all images should be same.") + if not np.allclose(header["spatial_shape"], compatible_meta["spatial_shape"]): + raise RuntimeError("spatial_shape of all images should be same.") + + img_array_ = np.stack(img_array, axis=0) if len(img_array) > 1 else img_array[0] + return img_array_, compatible_meta + + def _get_meta_dict(self, img: Nifti1Image) -> Dict: + """ + Get the all the meta data of the image and convert to dict type. + + Args: + img: a Nibabel image object loaded from a image file. + + """ + return dict(img.header) + + def _get_affine(self, img: Nifti1Image) -> np.ndarray: + """ + Get the affine matrix of the image, it can be used to correct + spacing, orientation or execute spatial transforms. + + Args: + img: a Nibabel image object loaded from a image file. + + """ + return img.affine + + def _get_spatial_shape(self, img: Nifti1Image) -> Sequence: + """ + Get the spatial shape of image data, it doesn't contain the channel dim. + + Args: + img: a Nibabel image object loaded from a image file. + + """ + ndim = img.header["dim"][0] + spatial_rank = min(ndim, 3) + return list(img.header["dim"][1 : spatial_rank + 1]) + + def _get_array_data(self, img: Nifti1Image) -> np.ndarray: + """ + Get the raw array data of the image, converted to Numpy array. + + Args: + img: a Nibabel image object loaded from a image file. + + """ + return np.asarray(img.dataobj) diff --git a/testbed/Project-MONAI__MONAI/monai/data/nifti_reader.py b/testbed/Project-MONAI__MONAI/monai/data/nifti_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..76bf305c1a0be8911ae7719ea9f2a9ba45e652ee --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/nifti_reader.py @@ -0,0 +1,120 @@ +# Copyright 2020 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 typing import Any, Callable, Optional, Sequence + +import numpy as np +from torch.utils.data import Dataset + +from monai.transforms import LoadNifti, Randomizable, apply_transform +from monai.utils import get_seed + + +class NiftiDataset(Dataset, Randomizable): + """ + Loads image/segmentation pairs of Nifti files from the given filename lists. Transformations can be specified + for the image and segmentation arrays separately. + """ + + def __init__( + self, + image_files: Sequence[str], + seg_files: Optional[Sequence[str]] = None, + labels: Optional[Sequence[float]] = None, + as_closest_canonical: bool = False, + transform: Optional[Callable] = None, + seg_transform: Optional[Callable] = None, + image_only: bool = True, + dtype: Optional[np.dtype] = np.float32, + ) -> None: + """ + Initializes the dataset with the image and segmentation filename lists. The transform `transform` is applied + to the images and `seg_transform` to the segmentations. + + Args: + image_files: list of image filenames + seg_files: if in segmentation task, list of segmentation filenames + labels: if in classification task, list of classification labels + as_closest_canonical: if True, load the image as closest to canonical orientation + transform: transform to apply to image arrays + seg_transform: transform to apply to segmentation arrays + image_only: if True return only the image volume, other return image volume and header dict + dtype: if not None convert the loaded image to this data type + + Raises: + ValueError: When ``seg_files`` length differs from ``image_files``. + + """ + + if seg_files is not None and len(image_files) != len(seg_files): + raise ValueError( + "Must have same the number of segmentation as image files: " + f"images={len(image_files)}, segmentations={len(seg_files)}." + ) + + self.image_files = image_files + self.seg_files = seg_files + self.labels = labels + self.as_closest_canonical = as_closest_canonical + self.transform = transform + self.seg_transform = seg_transform + self.image_only = image_only + self.dtype = dtype + self.set_random_state(seed=get_seed()) + + self._seed = 0 # transform synchronization seed + + def __len__(self) -> int: + return len(self.image_files) + + def randomize(self, data: Optional[Any] = None) -> None: + self._seed = self.R.randint(np.iinfo(np.int32).max) + + def __getitem__(self, index: int): + self.randomize() + meta_data = None + img_loader = LoadNifti( + as_closest_canonical=self.as_closest_canonical, image_only=self.image_only, dtype=self.dtype + ) + if self.image_only: + img = img_loader(self.image_files[index]) + else: + img, meta_data = img_loader(self.image_files[index]) + seg = None + if self.seg_files is not None: + seg_loader = LoadNifti(image_only=True) + seg = seg_loader(self.seg_files[index]) + label = None + if self.labels is not None: + label = self.labels[index] + + if self.transform is not None: + if isinstance(self.transform, Randomizable): + self.transform.set_random_state(seed=self._seed) + img = apply_transform(self.transform, img) + + data = [img] + + if self.seg_transform is not None: + if isinstance(self.seg_transform, Randomizable): + self.seg_transform.set_random_state(seed=self._seed) + seg = apply_transform(self.seg_transform, seg) + + if seg is not None: + data.append(seg) + if label is not None: + data.append(label) + if not self.image_only and meta_data is not None: + data.append(meta_data) + if len(data) == 1: + return data[0] + # use tuple instead of list as the default collate_fn callback of MONAI DataLoader flattens nested lists + return tuple(data) diff --git a/testbed/Project-MONAI__MONAI/monai/data/nifti_saver.py b/testbed/Project-MONAI__MONAI/monai/data/nifti_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..1f9887970c3a166d6eadd9451323104dd2ed16d9 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/nifti_saver.py @@ -0,0 +1,141 @@ +# Copyright 2020 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 typing import Dict, Optional, Union + +import numpy as np +import torch + +from monai.data.nifti_writer import write_nifti +from monai.data.utils import create_file_basename +from monai.utils import GridSampleMode, GridSamplePadMode + + +class NiftiSaver: + """ + Save the data as NIfTI file, it can support single data content or a batch of data. + Typically, the data can be segmentation predictions, call `save` for single data + or call `save_batch` to save a batch of data together. If no meta data provided, + use index from 0 as the filename prefix. + """ + + def __init__( + self, + output_dir: str = "./", + output_postfix: str = "seg", + output_ext: str = ".nii.gz", + resample: bool = True, + mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, + padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, + align_corners: bool = False, + dtype: Optional[np.dtype] = np.float64, + ) -> None: + """ + Args: + output_dir: output image directory. + output_postfix: a string appended to all output file names. + output_ext: output file extension name. + resample: whether to resample before saving the data array. + mode: {``"bilinear"``, ``"nearest"``} + This option is used when ``resample = True``. + Interpolation mode to calculate output values. Defaults to ``"bilinear"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} + This option is used when ``resample = True``. + Padding mode for outside grid values. Defaults to ``"border"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + align_corners: Geometrically, we consider the pixels of the input as squares rather than points. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + dtype: data type for resampling computation. Defaults to ``np.float64`` for best precision. + If None, use the data type of input data. To be compatible with other modules, + the output data type is always ``np.float32``. + """ + self.output_dir = output_dir + self.output_postfix = output_postfix + self.output_ext = output_ext + self.resample = resample + self.mode: GridSampleMode = GridSampleMode(mode) + self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) + self.align_corners = align_corners + self.dtype = dtype + self._data_index = 0 + + def save(self, data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None) -> None: + """ + Save data into a Nifti file. + The meta_data could optionally have the following keys: + + - ``'filename_or_obj'`` -- for output file name creation, corresponding to filename or object. + - ``'original_affine'`` -- for data orientation handling, defaulting to an identity matrix. + - ``'affine'`` -- for data output affine, defaulting to an identity matrix. + - ``'spatial_shape'`` -- for data output shape. + + When meta_data is specified, the saver will try to resample batch data from the space + defined by "affine" to the space defined by "original_affine". + + If meta_data is None, use the default index (starting from 0) as the filename. + + Args: + data: target data content that to be saved as a NIfTI format file. + Assuming the data shape starts with a channel dimension and followed by spatial dimensions. + meta_data: the meta data information corresponding to the data. + + See Also + :py:meth:`monai.data.nifti_writer.write_nifti` + """ + filename = meta_data["filename_or_obj"] if meta_data else str(self._data_index) + self._data_index += 1 + original_affine = meta_data.get("original_affine", None) if meta_data else None + affine = meta_data.get("affine", None) if meta_data else None + spatial_shape = meta_data.get("spatial_shape", None) if meta_data else None + + if torch.is_tensor(data): + data = data.detach().cpu().numpy() + filename = create_file_basename(self.output_postfix, filename, self.output_dir) + filename = f"{filename}{self.output_ext}" + # change data shape to be (channel, h, w, d) + while len(data.shape) < 4: + data = np.expand_dims(data, -1) + # change data to "channel last" format and write to nifti format file + data = np.moveaxis(data, 0, -1) + write_nifti( + data, + file_name=filename, + affine=affine, + target_affine=original_affine, + resample=self.resample, + output_spatial_shape=spatial_shape, + mode=self.mode, + padding_mode=self.padding_mode, + align_corners=self.align_corners, + dtype=self.dtype, + ) + + def save_batch(self, batch_data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None) -> None: + """ + Save a batch of data into Nifti format files. + + Spatially it supports up to three dimensions, that is, H, HW, HWD for + 1D, 2D, 3D respectively (with resampling supports for 2D and 3D only). + + When saving multiple time steps or multiple channels `batch_data`, + time and/or modality axes should be appended after the batch dimensions. + For example, the shape of a batch of 2D eight-class + segmentation probabilities to be saved could be `(batch, 8, 64, 64)`; + in this case each item in the batch will be saved as (64, 64, 1, 8) + NIfTI file (the third dimension is reserved as a spatial dimension). + + Args: + batch_data: target batch data content that save into NIfTI format. + meta_data: every key-value in the meta_data is corresponding to a batch of data. + """ + for i, data in enumerate(batch_data): # save a batch of files + self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None) diff --git a/testbed/Project-MONAI__MONAI/monai/data/nifti_writer.py b/testbed/Project-MONAI__MONAI/monai/data/nifti_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad06ee22787768cf585cb721bf68292bd61df5f --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/nifti_writer.py @@ -0,0 +1,153 @@ +# Copyright 2020 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 typing import Optional, Sequence, Union + +import numpy as np +import torch + +from monai.data.utils import compute_shape_offset, to_affine_nd +from monai.networks.layers import AffineTransform +from monai.utils import GridSampleMode, GridSamplePadMode, optional_import + +nib, _ = optional_import("nibabel") + + +def write_nifti( + data: np.ndarray, + file_name: str, + affine: Optional[np.ndarray] = None, + target_affine: Optional[np.ndarray] = None, + resample: bool = True, + output_spatial_shape: Optional[Sequence[int]] = None, + mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, + padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, + align_corners: bool = False, + dtype: Optional[np.dtype] = np.float64, +) -> None: + """ + Write numpy data into NIfTI files to disk. This function converts data + into the coordinate system defined by `target_affine` when `target_affine` + is specified. + + If the coordinate transform between `affine` and `target_affine` could be + achieved by simply transposing and flipping `data`, no resampling will + happen. otherwise this function will resample `data` using the coordinate + transform computed from `affine` and `target_affine`. Note that the shape + of the resampled `data` may subject to some rounding errors. For example, + resampling a 20x20 pixel image from pixel size (1.5, 1.5)-mm to (3.0, + 3.0)-mm space will return a 10x10-pixel image. However, resampling a + 20x20-pixel image from pixel size (2.0, 2.0)-mm to (3.0, 3.0)-mma space + will output a 14x14-pixel image, where the image shape is rounded from + 13.333x13.333 pixels. In this case `output_spatial_shape` could be specified so + that this function writes image data to a designated shape. + + When `affine` and `target_affine` are None, the data will be saved with an + identity matrix as the image affine. + + This function assumes the NIfTI dimension notations. + Spatially it supports up to three dimensions, that is, H, HW, HWD for + 1D, 2D, 3D respectively. + When saving multiple time steps or multiple channels `data`, time and/or + modality axes should be appended after the first three dimensions. For + example, shape of 2D eight-class segmentation probabilities to be saved + could be `(64, 64, 1, 8)`. Also, data in shape (64, 64, 8), (64, 64, 8, 1) + will be considered as a single-channel 3D image. + + Args: + data: input data to write to file. + file_name: expected file name that saved on disk. + affine: the current affine of `data`. Defaults to `np.eye(4)` + target_affine: before saving + the (`data`, `affine`) as a Nifti1Image, + transform the data into the coordinates defined by `target_affine`. + resample: whether to run resampling when the target affine + could not be achieved by swapping/flipping data axes. + output_spatial_shape: spatial shape of the output image. + This option is used when resample = True. + mode: {``"bilinear"``, ``"nearest"``} + This option is used when ``resample = True``. + Interpolation mode to calculate output values. Defaults to ``"bilinear"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} + This option is used when ``resample = True``. + Padding mode for outside grid values. Defaults to ``"border"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + align_corners: Geometrically, we consider the pixels of the input as squares rather than points. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + dtype: data type for resampling computation. Defaults to ``np.float64`` for best precision. + If None, use the data type of input data. To be compatible with other modules, + the output data type is always ``np.float32``. + """ + assert isinstance(data, np.ndarray), "input data must be numpy array." + dtype = dtype or data.dtype + sr = min(data.ndim, 3) + if affine is None: + affine = np.eye(4, dtype=np.float64) + affine = to_affine_nd(sr, affine) + + if target_affine is None: + target_affine = affine + target_affine = to_affine_nd(sr, target_affine) + + if np.allclose(affine, target_affine, atol=1e-3): + # no affine changes, save (data, affine) + results_img = nib.Nifti1Image(data.astype(np.float32), to_affine_nd(3, target_affine)) + nib.save(results_img, file_name) + return + + # resolve orientation + start_ornt = nib.orientations.io_orientation(affine) + target_ornt = nib.orientations.io_orientation(target_affine) + ornt_transform = nib.orientations.ornt_transform(start_ornt, target_ornt) + data_shape = data.shape + data = nib.orientations.apply_orientation(data, ornt_transform) + _affine = affine @ nib.orientations.inv_ornt_aff(ornt_transform, data_shape) + if np.allclose(_affine, target_affine, atol=1e-3) or not resample: + results_img = nib.Nifti1Image(data.astype(np.float32), to_affine_nd(3, target_affine)) + nib.save(results_img, file_name) + return + + # need resampling + affine_xform = AffineTransform( + normalized=False, mode=mode, padding_mode=padding_mode, align_corners=align_corners, reverse_indexing=True + ) + transform = np.linalg.inv(_affine) @ target_affine + if output_spatial_shape is None: + output_spatial_shape, _ = compute_shape_offset(data.shape, _affine, target_affine) + output_spatial_shape_ = list(output_spatial_shape) + if data.ndim > 3: # multi channel, resampling each channel + while len(output_spatial_shape_) < 3: + output_spatial_shape_ = output_spatial_shape_ + [1] + spatial_shape, channel_shape = data.shape[:3], data.shape[3:] + data_np = data.reshape(list(spatial_shape) + [-1]) + data_np = np.moveaxis(data_np, -1, 0) # channel first for pytorch + data_torch = affine_xform( + torch.as_tensor(np.ascontiguousarray(data_np).astype(dtype)).unsqueeze(0), + torch.as_tensor(np.ascontiguousarray(transform).astype(dtype)), + spatial_size=output_spatial_shape_[:3], + ) + data_np = data_torch.squeeze(0).detach().cpu().numpy() + data_np = np.moveaxis(data_np, 0, -1) # channel last for nifti + data_np = data_np.reshape(list(data_np.shape[:3]) + list(channel_shape)) + else: # single channel image, need to expand to have batch and channel + while len(output_spatial_shape_) < len(data.shape): + output_spatial_shape_ = output_spatial_shape_ + [1] + data_torch = affine_xform( + torch.as_tensor(np.ascontiguousarray(data).astype(dtype)[None, None]), + torch.as_tensor(np.ascontiguousarray(transform).astype(dtype)), + spatial_size=output_spatial_shape_[: len(data.shape)], + ) + data_np = data_torch.squeeze(0).squeeze(0).detach().cpu().numpy() + + results_img = nib.Nifti1Image(data_np.astype(np.float32), to_affine_nd(3, target_affine)) + nib.save(results_img, file_name) + return diff --git a/testbed/Project-MONAI__MONAI/monai/data/png_saver.py b/testbed/Project-MONAI__MONAI/monai/data/png_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..dea7387bd48dee65f78172d33bcd928811a361e5 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/png_saver.py @@ -0,0 +1,118 @@ +# Copyright 2020 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 typing import Dict, Optional, Union + +import numpy as np +import torch + +from monai.data.png_writer import write_png +from monai.data.utils import create_file_basename +from monai.utils import InterpolateMode + + +class PNGSaver: + """ + Save the data as png file, it can support single data content or a batch of data. + Typically, the data can be segmentation predictions, call `save` for single data + or call `save_batch` to save a batch of data together. If no meta data provided, + use index from 0 as the filename prefix. + """ + + def __init__( + self, + output_dir: str = "./", + output_postfix: str = "seg", + output_ext: str = ".png", + resample: bool = True, + mode: Union[InterpolateMode, str] = InterpolateMode.NEAREST, + scale: Optional[int] = None, + ) -> None: + """ + Args: + output_dir: output image directory. + output_postfix: a string appended to all output file names. + output_ext: output file extension name. + resample: whether to resample and resize if providing spatial_shape in the metadata. + mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} + The interpolation mode. Defaults to ``"nearest"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate + scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling + [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling. + + """ + self.output_dir = output_dir + self.output_postfix = output_postfix + self.output_ext = output_ext + self.resample = resample + self.mode: InterpolateMode = InterpolateMode(mode) + self.scale = scale + + self._data_index = 0 + + def save(self, data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None) -> None: + """ + Save data into a png file. + The meta_data could optionally have the following keys: + + - ``'filename_or_obj'`` -- for output file name creation, corresponding to filename or object. + - ``'spatial_shape'`` -- for data output shape. + + If meta_data is None, use the default index (starting from 0) as the filename. + + Args: + data: target data content that to be saved as a png format file. + Assuming the data shape are spatial dimensions. + Shape of the spatial dimensions (C,H,W). + C should be 1, 3 or 4 + meta_data: the meta data information corresponding to the data. + + Raises: + ValueError: When ``data`` channels is not one of [1, 3, 4]. + + See Also + :py:meth:`monai.data.png_writer.write_png` + + """ + filename = meta_data["filename_or_obj"] if meta_data else str(self._data_index) + self._data_index += 1 + spatial_shape = meta_data.get("spatial_shape", None) if meta_data and self.resample else None + + if torch.is_tensor(data): + data = data.detach().cpu().numpy() + + filename = create_file_basename(self.output_postfix, filename, self.output_dir) + filename = f"{filename}{self.output_ext}" + + if data.shape[0] == 1: + data = data.squeeze(0) + elif 2 < data.shape[0] < 5: + data = np.moveaxis(data, 0, -1) + else: + raise ValueError(f"Unsupported number of channels: {data.shape[0]}, available options are [1, 3, 4]") + + write_png( + data, + file_name=filename, + output_spatial_shape=spatial_shape, + mode=self.mode, + scale=self.scale, + ) + + def save_batch(self, batch_data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None) -> None: + """Save a batch of data into png format files. + + Args: + batch_data: target batch data content that save into png format. + meta_data: every key-value in the meta_data is corresponding to a batch of data. + """ + for i, data in enumerate(batch_data): # save a batch of files + self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None) diff --git a/testbed/Project-MONAI__MONAI/monai/data/png_writer.py b/testbed/Project-MONAI__MONAI/monai/data/png_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..d35a530a86d3d024f4a34b963a3b48a2e467632f --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/png_writer.py @@ -0,0 +1,80 @@ +# Copyright 2020 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 typing import Optional, Sequence, Union + +import numpy as np + +from monai.transforms import Resize +from monai.utils import InterpolateMode, ensure_tuple_rep, optional_import + +Image, _ = optional_import("PIL", name="Image") + + +def write_png( + data: np.ndarray, + file_name: str, + output_spatial_shape: Optional[Sequence[int]] = None, + mode: Union[InterpolateMode, str] = InterpolateMode.BICUBIC, + scale: Optional[int] = None, +) -> None: + """ + Write numpy data into png files to disk. + Spatially it supports HW for 2D.(H,W) or (H,W,3) or (H,W,4). + If `scale` is None, expect the input data in `np.uint8` or `np.uint16` type. + It's based on the Image module in PIL library: + https://pillow.readthedocs.io/en/stable/reference/Image.html + + Args: + data: input data to write to file. + file_name: expected file name that saved on disk. + output_spatial_shape: spatial shape of the output image. + mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} + The interpolation mode. Defaults to ``"bicubic"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate + scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling to + [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling. + + Raises: + ValueError: When ``scale`` is not one of [255, 65535]. + + """ + assert isinstance(data, np.ndarray), "input data must be numpy array." + if len(data.shape) == 3 and data.shape[2] == 1: # PIL Image can't save image with 1 channel + data = data.squeeze(2) + if output_spatial_shape is not None: + output_spatial_shape_ = ensure_tuple_rep(output_spatial_shape, 2) + mode = InterpolateMode(mode) + align_corners = None if mode in (InterpolateMode.NEAREST, InterpolateMode.AREA) else False + xform = Resize(spatial_size=output_spatial_shape_, mode=mode, align_corners=align_corners) + _min, _max = np.min(data), np.max(data) + if len(data.shape) == 3: + data = np.moveaxis(data, -1, 0) # to channel first + data = xform(data) + data = np.moveaxis(data, 0, -1) + else: # (H, W) + data = np.expand_dims(data, 0) # make a channel + data = xform(data)[0] # first channel + if mode != InterpolateMode.NEAREST: + data = np.clip(data, _min, _max) + + if scale is not None: + data = np.clip(data, 0.0, 1.0) # png writer only can scale data in range [0, 1] + if scale == np.iinfo(np.uint8).max: + data = (scale * data).astype(np.uint8) + elif scale == np.iinfo(np.uint16).max: + data = (scale * data).astype(np.uint16) + else: + raise ValueError(f"Unsupported scale: {scale}, available options are [255, 65535]") + + img = Image.fromarray(data) + img.save(file_name, "PNG") + return diff --git a/testbed/Project-MONAI__MONAI/monai/data/synthetic.py b/testbed/Project-MONAI__MONAI/monai/data/synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..cdbb660566a1081309bb7a13f384eb9c70dde2dd --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/synthetic.py @@ -0,0 +1,139 @@ +# Copyright 2020 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 typing import Optional, Tuple + +import numpy as np + +from monai.transforms.utils import rescale_array + +__all__ = ["create_test_image_2d", "create_test_image_3d"] + + +def create_test_image_2d( + width: int, + height: int, + num_objs: int = 12, + rad_max: int = 30, + noise_max: float = 0.0, + num_seg_classes: int = 5, + channel_dim: Optional[int] = None, + random_state: Optional[np.random.RandomState] = None, +) -> Tuple[np.ndarray, np.ndarray]: + """ + Return a noisy 2D image with `num_objs` circles and a 2D mask image. The maximum radius of the circles is given as + `rad_max`. The mask will have `num_seg_classes` number of classes for segmentations labeled sequentially from 1, plus a + background class represented as 0. If `noise_max` is greater than 0 then noise will be added to the image taken from + the uniform distribution on range `[0,noise_max)`. If `channel_dim` is None, will create an image without channel + dimension, otherwise create an image with channel dimension as first dim or last dim. + + Args: + width: width of the image. + height: height of the image. + num_objs: number of circles to generate. Defaults to `12`. + rad_max: maximum circle radius. Defaults to `30`. + noise_max: if greater than 0 then noise will be added to the image taken from + the uniform distribution on range `[0,noise_max)`. Defaults to `0`. + num_seg_classes: number of classes for segmentations. Defaults to `5`. + channel_dim: if None, create an image without channel dimension, otherwise create + an image with channel dimension as first dim or last dim. Defaults to `None`. + random_state: the random generator to use. Defaults to `np.random`. + """ + image = np.zeros((width, height)) + rs = np.random if random_state is None else random_state + + for _ in range(num_objs): + x = rs.randint(rad_max, width - rad_max) + y = rs.randint(rad_max, height - rad_max) + rad = rs.randint(5, rad_max) + spy, spx = np.ogrid[-x : width - x, -y : height - y] + circle = (spx * spx + spy * spy) <= rad * rad + + if num_seg_classes > 1: + image[circle] = np.ceil(rs.random() * num_seg_classes) + else: + image[circle] = rs.random() * 0.5 + 0.5 + + labels = np.ceil(image).astype(np.int32) + + norm = rs.uniform(0, num_seg_classes * noise_max, size=image.shape) + noisyimage = rescale_array(np.maximum(image, norm)) + + if channel_dim is not None: + assert isinstance(channel_dim, int) and channel_dim in (-1, 0, 2), "invalid channel dim." + if channel_dim == 0: + noisyimage = noisyimage[None] + labels = labels[None] + else: + noisyimage = noisyimage[..., None] + labels = labels[..., None] + + return noisyimage, labels + + +def create_test_image_3d( + height: int, + width: int, + depth: int, + num_objs: int = 12, + rad_max: int = 30, + noise_max: float = 0.0, + num_seg_classes: int = 5, + channel_dim: Optional[int] = None, + random_state: Optional[np.random.RandomState] = None, +) -> Tuple[np.ndarray, np.ndarray]: + """ + Return a noisy 3D image and segmentation. + + Args: + height: height of the image. + width: width of the image. + depth: depth of the image. + num_objs: number of circles to generate. Defaults to `12`. + rad_max: maximum circle radius. Defaults to `30`. + noise_max: if greater than 0 then noise will be added to the image taken from + the uniform distribution on range `[0,noise_max)`. Defaults to `0`. + num_seg_classes: number of classes for segmentations. Defaults to `5`. + channel_dim: if None, create an image without channel dimension, otherwise create + an image with channel dimension as first dim or last dim. Defaults to `None`. + random_state: the random generator to use. Defaults to `np.random`. + + See also: + :py:meth:`~create_test_image_2d` + """ + image = np.zeros((width, height, depth)) + rs = np.random if random_state is None else random_state + + for _ in range(num_objs): + x = rs.randint(rad_max, width - rad_max) + y = rs.randint(rad_max, height - rad_max) + z = rs.randint(rad_max, depth - rad_max) + rad = rs.randint(5, rad_max) + spy, spx, spz = np.ogrid[-x : width - x, -y : height - y, -z : depth - z] + circle = (spx * spx + spy * spy + spz * spz) <= rad * rad + + if num_seg_classes > 1: + image[circle] = np.ceil(rs.random() * num_seg_classes) + else: + image[circle] = rs.random() * 0.5 + 0.5 + + labels = np.ceil(image).astype(np.int32) + + norm = rs.uniform(0, num_seg_classes * noise_max, size=image.shape) + noisyimage = rescale_array(np.maximum(image, norm)) + + if channel_dim is not None: + assert isinstance(channel_dim, int) and channel_dim in (-1, 0, 3), "invalid channel dim." + noisyimage, labels = ( + (noisyimage[None], labels[None]) if channel_dim == 0 else (noisyimage[..., None], labels[..., None]) + ) + + return noisyimage, labels diff --git a/testbed/Project-MONAI__MONAI/monai/data/utils.py b/testbed/Project-MONAI__MONAI/monai/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5e03734ce3fbd005faaa94a6bffd2aa6c7853f8d --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/data/utils.py @@ -0,0 +1,538 @@ +# Copyright 2020 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. + +import math +import os +import warnings +from itertools import product, starmap +from typing import Dict, Generator, List, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +from torch.utils.data._utils.collate import default_collate + +from monai.networks.layers.simplelayers import GaussianFilter +from monai.utils import BlendMode, NumpyPadMode, ensure_tuple, ensure_tuple_size, first, optional_import + +nib, _ = optional_import("nibabel") + + +def get_random_patch( + dims: Sequence[int], patch_size: Sequence[int], rand_state: Optional[np.random.RandomState] = None +) -> Tuple[slice, ...]: + """ + Returns a tuple of slices to define a random patch in an array of shape `dims` with size `patch_size` or the as + close to it as possible within the given dimension. It is expected that `patch_size` is a valid patch for a source + of shape `dims` as returned by `get_valid_patch_size`. + + Args: + dims: shape of source array + patch_size: shape of patch size to generate + rand_state: a random state object to generate random numbers from + + Returns: + (tuple of slice): a tuple of slice objects defining the patch + """ + + # choose the minimal corner of the patch + rand_int = np.random.randint if rand_state is None else rand_state.randint + min_corner = tuple(rand_int(0, ms - ps) if ms > ps else 0 for ms, ps in zip(dims, patch_size)) + + # create the slices for each dimension which define the patch in the source array + return tuple(slice(mc, mc + ps) for mc, ps in zip(min_corner, patch_size)) + + +def iter_patch_slices( + dims: Sequence[int], patch_size: Union[Sequence[int], int], start_pos: Sequence[int] = () +) -> Generator[Tuple[slice, ...], None, None]: + """ + Yield successive tuples of slices defining patches of size `patch_size` from an array of dimensions `dims`. The + iteration starts from position `start_pos` in the array, or starting at the origin if this isn't provided. Each + patch is chosen in a contiguous grid using a first dimension as least significant ordering. + + Args: + dims: dimensions of array to iterate over + patch_size: size of patches to generate slices for, 0 or None selects whole dimension + start_pos: starting position in the array, default is 0 for each dimension + + Yields: + Tuples of slice objects defining each patch + """ + + # ensure patchSize and startPos are the right length + ndim = len(dims) + patch_size_ = get_valid_patch_size(dims, patch_size) + start_pos = ensure_tuple_size(start_pos, ndim) + + # collect the ranges to step over each dimension + ranges = tuple(starmap(range, zip(start_pos, dims, patch_size_))) + + # choose patches by applying product to the ranges + for position in product(*ranges[::-1]): # reverse ranges order to iterate in index order + yield tuple(slice(s, s + p) for s, p in zip(position[::-1], patch_size_)) + + +def dense_patch_slices( + image_size: Sequence[int], + patch_size: Sequence[int], + scan_interval: Sequence[int], +) -> List[Tuple[slice, ...]]: + """ + Enumerate all slices defining 2D/3D patches of size `patch_size` from an `image_size` input image. + + Args: + image_size: dimensions of image to iterate over + patch_size: size of patches to generate slices + scan_interval: dense patch sampling interval + + Raises: + ValueError: When ``image_size`` length is not one of [2, 3]. + + Returns: + a list of slice objects defining each patch + + """ + num_spatial_dims = len(image_size) + if num_spatial_dims not in (2, 3): + raise ValueError(f"Unsupported image_size length: {len(image_size)}, available options are [2, 3]") + patch_size = get_valid_patch_size(image_size, patch_size) + scan_interval = ensure_tuple_size(scan_interval, num_spatial_dims) + + scan_num = list() + for i in range(num_spatial_dims): + if scan_interval[i] == 0: + scan_num.append(1) + else: + num = int(math.ceil(float(image_size[i]) / scan_interval[i])) + scan_dim = first(d for d in range(num) if d * scan_interval[i] + patch_size[i] >= image_size[i]) + scan_num.append(scan_dim + 1) + + slices: List[Tuple[slice, ...]] = [] + if num_spatial_dims == 3: + for i in range(scan_num[0]): + start_i = i * scan_interval[0] + start_i -= max(start_i + patch_size[0] - image_size[0], 0) + slice_i = slice(start_i, start_i + patch_size[0]) + + for j in range(scan_num[1]): + start_j = j * scan_interval[1] + start_j -= max(start_j + patch_size[1] - image_size[1], 0) + slice_j = slice(start_j, start_j + patch_size[1]) + + for k in range(0, scan_num[2]): + start_k = k * scan_interval[2] + start_k -= max(start_k + patch_size[2] - image_size[2], 0) + slice_k = slice(start_k, start_k + patch_size[2]) + slices.append((slice_i, slice_j, slice_k)) + else: + for i in range(scan_num[0]): + start_i = i * scan_interval[0] + start_i -= max(start_i + patch_size[0] - image_size[0], 0) + slice_i = slice(start_i, start_i + patch_size[0]) + + for j in range(scan_num[1]): + start_j = j * scan_interval[1] + start_j -= max(start_j + patch_size[1] - image_size[1], 0) + slice_j = slice(start_j, start_j + patch_size[1]) + slices.append((slice_i, slice_j)) + return slices + + +def iter_patch( + arr: np.ndarray, + patch_size: Union[Sequence[int], int] = 0, + start_pos: Sequence[int] = (), + copy_back: bool = True, + mode: Union[NumpyPadMode, str] = NumpyPadMode.WRAP, + **pad_opts: Dict, +) -> Generator[np.ndarray, None, None]: + """ + Yield successive patches from `arr` of size `patch_size`. The iteration can start from position `start_pos` in `arr` + but drawing from a padded array extended by the `patch_size` in each dimension (so these coordinates can be negative + to start in the padded region). If `copy_back` is True the values from each patch are written back to `arr`. + + Args: + arr: array to iterate over + patch_size: size of patches to generate slices for, 0 or None selects whole dimension + start_pos: starting position in the array, default is 0 for each dimension + copy_back: if True data from the yielded patches is copied back to `arr` once the generator completes + mode: {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, + ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + One of the listed string values or a user supplied function. Defaults to ``"wrap"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + pad_opts: padding options, see `numpy.pad` + + Yields: + Patches of array data from `arr` which are views into a padded array which can be modified, if `copy_back` is + True these changes will be reflected in `arr` once the iteration completes. + """ + # ensure patchSize and startPos are the right length + patch_size_ = get_valid_patch_size(arr.shape, patch_size) + start_pos = ensure_tuple_size(start_pos, arr.ndim) + + # pad image by maximum values needed to ensure patches are taken from inside an image + arrpad = np.pad(arr, tuple((p, p) for p in patch_size_), NumpyPadMode(mode).value, **pad_opts) + + # choose a start position in the padded image + start_pos_padded = tuple(s + p for s, p in zip(start_pos, patch_size_)) + + # choose a size to iterate over which is smaller than the actual padded image to prevent producing + # patches which are only in the padded regions + iter_size = tuple(s + p for s, p in zip(arr.shape, patch_size_)) + + for slices in iter_patch_slices(iter_size, patch_size_, start_pos_padded): + yield arrpad[slices] + + # copy back data from the padded image if required + if copy_back: + slices = tuple(slice(p, p + s) for p, s in zip(patch_size_, arr.shape)) + arr[...] = arrpad[slices] + + +def get_valid_patch_size(image_size: Sequence[int], patch_size: Union[Sequence[int], int]) -> Tuple[int, ...]: + """ + Given an image of dimensions `image_size`, return a patch size tuple taking the dimension from `patch_size` if this is + not 0/None. Otherwise, or if `patch_size` is shorter than `image_size`, the dimension from `image_size` is taken. This ensures + the returned patch size is within the bounds of `image_size`. If `patch_size` is a single number this is interpreted as a + patch of the same dimensionality of `image_size` with that size in each dimension. + """ + ndim = len(image_size) + patch_size_ = ensure_tuple_size(patch_size, ndim) + + # ensure patch size dimensions are not larger than image dimension, if a dimension is None or 0 use whole dimension + return tuple(min(ms, ps or ms) for ms, ps in zip(image_size, patch_size_)) + + +def list_data_collate(batch: Sequence): + """ + Enhancement for PyTorch DataLoader default collate. + If dataset already returns a list of batch data that generated in transforms, need to merge all data to 1 list. + Then it's same as the default collate behavior. + + Note: + Need to use this collate if apply some transforms that can generate batch data. + + """ + elem = batch[0] + data = [i for k in batch for i in k] if isinstance(elem, list) else batch + return default_collate(data) + + +def worker_init_fn(worker_id: int) -> None: + """ + Callback function for PyTorch DataLoader `worker_init_fn`. + It can set different random seed for the transforms in different workers. + + """ + worker_info = torch.utils.data.get_worker_info() + if hasattr(worker_info.dataset, "transform") and hasattr(worker_info.dataset.transform, "set_random_state"): + worker_info.dataset.transform.set_random_state(worker_info.seed % (2 ** 32)) + + +def correct_nifti_header_if_necessary(img_nii): + """ + Check nifti object header's format, update the header if needed. + In the updated image pixdim matches the affine. + + Args: + img_nii: nifti image object + """ + dim = img_nii.header["dim"][0] + if dim >= 5: + return img_nii # do nothing for high-dimensional array + # check that affine matches zooms + pixdim = np.asarray(img_nii.header.get_zooms())[:dim] + norm_affine = np.sqrt(np.sum(np.square(img_nii.affine[:dim, :dim]), 0)) + if np.allclose(pixdim, norm_affine): + return img_nii + if hasattr(img_nii, "get_sform"): + return rectify_header_sform_qform(img_nii) + return img_nii + + +def rectify_header_sform_qform(img_nii): + """ + Look at the sform and qform of the nifti object and correct it if any + incompatibilities with pixel dimensions + + Adapted from https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/io/misc_io.py + + Args: + img_nii: nifti image object + """ + d = img_nii.header["dim"][0] + pixdim = np.asarray(img_nii.header.get_zooms())[:d] + sform, qform = img_nii.get_sform(), img_nii.get_qform() + norm_sform = np.sqrt(np.sum(np.square(sform[:d, :d]), 0)) + norm_qform = np.sqrt(np.sum(np.square(qform[:d, :d]), 0)) + sform_mismatch = not np.allclose(norm_sform, pixdim) + qform_mismatch = not np.allclose(norm_qform, pixdim) + + if img_nii.header["sform_code"] != 0: + if not sform_mismatch: + return img_nii + if not qform_mismatch: + img_nii.set_sform(img_nii.get_qform()) + return img_nii + if img_nii.header["qform_code"] != 0: + if not qform_mismatch: + return img_nii + if not sform_mismatch: + img_nii.set_qform(img_nii.get_sform()) + return img_nii + + norm = np.sqrt(np.sum(np.square(img_nii.affine[:d, :d]), 0)) + warnings.warn(f"Modifying image pixdim from {pixdim} to {norm}") + + img_nii.header.set_zooms(norm) + return img_nii + + +def zoom_affine(affine: np.ndarray, scale: Sequence[float], diagonal: bool = True) -> np.ndarray: + """ + To make column norm of `affine` the same as `scale`. If diagonal is False, + returns an affine that combines orthogonal rotation and the new scale. + This is done by first decomposing `affine`, then setting the zoom factors to + `scale`, and composing a new affine; the shearing factors are removed. If + diagonal is True, returns a diagonal matrix, the scaling factors are set + to the diagonal elements. This function always return an affine with zero + translations. + + Args: + affine (nxn matrix): a square matrix. + scale: new scaling factor along each dimension. + diagonal: whether to return a diagonal scaling matrix. + Defaults to True. + + Raises: + ValueError: When ``affine`` is not a square matrix. + ValueError: When ``scale`` contains a nonpositive scalar. + + Returns: + the updated `n x n` affine. + + """ + + affine = np.array(affine, dtype=float, copy=True) + if len(affine) != len(affine[0]): + raise ValueError(f"affine must be n x n, got {len(affine)} x {len(affine[0])}.") + scale_np = np.array(scale, dtype=float, copy=True) + if np.any(scale_np <= 0): + raise ValueError("scale must contain only positive numbers.") + d = len(affine) - 1 + if len(scale_np) < d: # defaults based on affine + norm = np.sqrt(np.sum(np.square(affine), 0))[:-1] + scale_np = np.append(scale_np, norm[len(scale_np) :]) + scale_np = scale_np[:d] + scale_np[scale_np == 0] = 1.0 + if diagonal: + return np.diag(np.append(scale_np, [1.0])) + rzs = affine[:-1, :-1] # rotation zoom scale + zs = np.linalg.cholesky(rzs.T @ rzs).T + rotation = rzs @ np.linalg.inv(zs) + s = np.sign(np.diag(zs)) * np.abs(scale_np) + # construct new affine with rotation and zoom + new_affine = np.eye(len(affine)) + new_affine[:-1, :-1] = rotation @ np.diag(s) + return new_affine + + +def compute_shape_offset( + spatial_shape: np.ndarray, in_affine: np.ndarray, out_affine: np.ndarray +) -> Tuple[np.ndarray, np.ndarray]: + """ + Given input and output affine, compute appropriate shapes + in the output space based on the input array's shape. + This function also returns the offset to put the shape + in a good position with respect to the world coordinate system. + + Args: + spatial_shape: input array's shape + in_affine (matrix): 2D affine matrix + out_affine (matrix): 2D affine matrix + """ + shape = np.array(spatial_shape, copy=True, dtype=float) + sr = len(shape) + in_affine = to_affine_nd(sr, in_affine) + out_affine = to_affine_nd(sr, out_affine) + in_coords = [(0.0, dim - 1.0) for dim in shape] + corners = np.asarray(np.meshgrid(*in_coords, indexing="ij")).reshape((len(shape), -1)) + corners = np.concatenate((corners, np.ones_like(corners[:1]))) + corners = in_affine @ corners + corners_out = np.linalg.inv(out_affine) @ corners + corners_out = corners_out[:-1] / corners_out[-1] + out_shape = np.round(corners_out.ptp(axis=1) + 1.0) + if np.allclose(nib.io_orientation(in_affine), nib.io_orientation(out_affine)): + # same orientation, get translate from the origin + offset = in_affine @ ([0] * sr + [1]) + offset = offset[:-1] / offset[-1] + else: + # different orientation, the min is the origin + corners = corners[:-1] / corners[-1] + offset = np.min(corners, 1) + return out_shape.astype(int), offset + + +def to_affine_nd(r: Union[np.ndarray, int], affine: np.ndarray) -> np.ndarray: + """ + Using elements from affine, to create a new affine matrix by + assigning the rotation/zoom/scaling matrix and the translation vector. + + when ``r`` is an integer, output is an (r+1)x(r+1) matrix, + where the top left kxk elements are copied from ``affine``, + the last column of the output affine is copied from ``affine``'s last column. + `k` is determined by `min(r, len(affine) - 1)`. + + when ``r`` is an affine matrix, the output has the same as ``r``, + the top left kxk elements are copied from ``affine``, + the last column of the output affine is copied from ``affine``'s last column. + `k` is determined by `min(len(r) - 1, len(affine) - 1)`. + + Args: + r (int or matrix): number of spatial dimensions or an output affine to be filled. + affine (matrix): 2D affine matrix + + Raises: + ValueError: When ``affine`` dimensions is not 2. + ValueError: When ``r`` is nonpositive. + + Returns: + an (r+1) x (r+1) matrix + + """ + affine_np = np.array(affine, dtype=np.float64) + if affine_np.ndim != 2: + raise ValueError(f"affine must have 2 dimensions, got {affine_np.ndim}.") + new_affine = np.array(r, dtype=np.float64, copy=True) + if new_affine.ndim == 0: + sr = new_affine.astype(int) + if not np.isfinite(sr) or sr < 0: + raise ValueError(f"r must be positive, got {sr}.") + new_affine = np.eye(sr + 1, dtype=np.float64) + d = max(min(len(new_affine) - 1, len(affine_np) - 1), 1) + new_affine[:d, :d] = affine_np[:d, :d] + if d > 1: + new_affine[:d, -1] = affine_np[:d, -1] + return new_affine + + +def create_file_basename(postfix: str, input_file_name: str, folder_path: str, data_root_dir: str = "") -> str: + """ + Utility function to create the path to the output file based on the input + filename (extension is added by lib level writer before writing the file) + + Args: + postfix: output name's postfix + input_file_name: path to the input image file + folder_path: path for the output file + data_root_dir: if not empty, it specifies the beginning parts of the input file's + absolute path. This is used to compute `input_file_rel_path`, the relative path to the file from + `data_root_dir` to preserve folder structure when saving in case there are files in different + folders with the same file names. + """ + + # get the filename and directory + filedir, filename = os.path.split(input_file_name) + + # jettison the extension to have just filename + filename, ext = os.path.splitext(filename) + while ext != "": + filename, ext = os.path.splitext(filename) + + # use data_root_dir to find relative path to file + filedir_rel_path = "" + if data_root_dir: + filedir_rel_path = os.path.relpath(filedir, data_root_dir) + + # sub-folder path will be original name without the extension + subfolder_path = os.path.join(folder_path, filedir_rel_path, filename) + if not os.path.exists(subfolder_path): + os.makedirs(subfolder_path) + + # add the sub-folder plus the postfix name to become the file basename in the output path + return os.path.join(subfolder_path, filename + "_" + postfix) + + +def compute_importance_map( + patch_size: Tuple[int, ...], + mode: Union[BlendMode, str] = BlendMode.CONSTANT, + sigma_scale: float = 0.125, + device: Optional[torch.device] = None, +) -> torch.Tensor: + """Get importance map for different weight modes. + + Args: + patch_size: Size of the required importance map. This should be either H, W [,D]. + mode: {``"constant"``, ``"gaussian"``} + How to blend output of overlapping windows. Defaults to ``"constant"``. + + - ``"constant``": gives equal weight to all predictions. + - ``"gaussian``": gives less weight to predictions on edges of windows. + + sigma_scale: Sigma_scale to calculate sigma for each dimension + (sigma = sigma_scale * dim_size). Used for gaussian mode only. + device: Device to put importance map on. + + Raises: + ValueError: When ``mode`` is not one of ["constant", "gaussian"]. + + Returns: + Tensor of size patch_size. + + """ + mode = BlendMode(mode) + if mode == BlendMode.CONSTANT: + importance_map = torch.ones(patch_size, device=device).float() + elif mode == BlendMode.GAUSSIAN: + center_coords = [i // 2 for i in patch_size] + sigmas = [i * sigma_scale for i in patch_size] + + importance_map = torch.zeros(patch_size, device=device) + importance_map[tuple(center_coords)] = 1 + pt_gaussian = GaussianFilter(len(patch_size), sigmas).to(device=device, dtype=torch.float) + importance_map = pt_gaussian(importance_map.unsqueeze(0).unsqueeze(0)) + importance_map = importance_map.squeeze(0).squeeze(0) + importance_map = importance_map / torch.max(importance_map) + importance_map = importance_map.float() + + # importance_map cannot be 0, otherwise we may end up with nans! + importance_map[importance_map == 0] = torch.min(importance_map[importance_map != 0]) + else: + raise ValueError(f'Unsupported mode: {mode}, available options are ["constant", "gaussian"].') + + return importance_map + + +def is_supported_format(filename: Union[Sequence[str], str], suffixes: Sequence[str]) -> bool: + """ + Verify whether the specified file or files format match supported suffixes. + If supported suffixes is None, skip the verification and return True. + + Args: + filename: file name or a list of file names to read. + if a list of files, verify all the subffixes. + suffixes: all the supported image subffixes of current reader. + + """ + supported_format: bool = True + filenames: Sequence[str] = ensure_tuple(filename) + for name in filenames: + tokens: Sequence[str] = name.split(".") + passed: bool = False + for i in range(len(tokens) - 1): + if ".".join(tokens[-(i + 2) : -1]) in suffixes: + passed = True + break + if not passed: + supported_format = False + break + + return supported_format diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/__init__.py b/testbed/Project-MONAI__MONAI/monai/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee63ae1acbf1b7a80ccdb671ccff8419767b7262 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2020 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 .checkpoint_loader import CheckpointLoader +from .checkpoint_saver import CheckpointSaver +from .classification_saver import ClassificationSaver +from .lr_schedule_handler import LrScheduleHandler +from .mean_dice import MeanDice +from .metric_logger import MetricLogger +from .roc_auc import ROCAUC +from .segmentation_saver import SegmentationSaver +from .smartcache_handler import SmartCacheHandler +from .stats_handler import StatsHandler +from .tensorboard_handlers import TensorBoardImageHandler, TensorBoardStatsHandler +from .utils import * +from .validation_handler import ValidationHandler diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/checkpoint_loader.py b/testbed/Project-MONAI__MONAI/monai/handlers/checkpoint_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..a77f8cac8f36ab91a70651185659583b88456178 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/checkpoint_loader.py @@ -0,0 +1,89 @@ +# Copyright 2020 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. + +import logging +from typing import TYPE_CHECKING, Dict, Optional + +import torch + +from monai.utils import exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +Checkpoint, _ = optional_import("ignite.handlers", "0.3.0", exact_version, "Checkpoint") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class CheckpointLoader: + """ + CheckpointLoader acts as an Ignite handler to load checkpoint data from file. + It can load variables for network, optimizer, lr_scheduler, etc. + If saving checkpoint after `torch.nn.DataParallel`, need to save `model.module` instead + as PyTorch recommended and then use this loader to load the model. + + Args: + load_path: the file path of checkpoint, it should be a PyTorch `pth` file. + load_dict: target objects that load checkpoint to. examples:: + + {'network': net, 'optimizer': optimizer, 'lr_scheduler': lr_scheduler} + + name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``. + map_location: when loading the module for distributed training/evaluation, + need to provide an appropriate map_location argument to prevent a process + to step into others’ devices. If map_location is missing, torch.load will + first load the module to CPU and then copy each parameter to where it was + saved, which would result in all processes on the same machine using the + same set of devices. + + """ + + def __init__( + self, + load_path: str, + load_dict: Dict, + name: Optional[str] = None, + map_location: Optional[Dict] = None, + ) -> None: + assert load_path is not None, "must provide clear path to load checkpoint." + self.load_path = load_path + assert load_dict is not None and len(load_dict) > 0, "must provide target objects to load." + self.logger = logging.getLogger(name) + for k, v in load_dict.items(): + if hasattr(v, "module"): + load_dict[k] = v.module + self.load_dict = load_dict + self._name = name + self.map_location = map_location + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + engine.add_event_handler(Events.STARTED, self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + checkpoint = torch.load(self.load_path, map_location=self.map_location) + if len(self.load_dict) == 1: + key = list(self.load_dict.keys())[0] + if not (key in checkpoint): + checkpoint = {key: checkpoint} + + Checkpoint.load_objects(to_load=self.load_dict, checkpoint=checkpoint) + self.logger.info(f"Restored all variables from {self.load_path}") diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/checkpoint_saver.py b/testbed/Project-MONAI__MONAI/monai/handlers/checkpoint_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..aea8ad7e4c7c8cc341bbfda9481fecfaff54934e --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/checkpoint_saver.py @@ -0,0 +1,211 @@ +# Copyright 2020 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. + +import logging +from typing import TYPE_CHECKING, Dict, Optional + +from monai.utils import exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +ModelCheckpoint, _ = optional_import("ignite.handlers", "0.3.0", exact_version, "ModelCheckpoint") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class CheckpointSaver: + """ + CheckpointSaver acts as an Ignite handler to save checkpoint data into files. + It supports to save according to metrics result, epoch number, iteration number + and last model or exception. + + Args: + save_dir: the target directory to save the checkpoints. + save_dict: source objects that save to the checkpoint. examples:: + + {'network': net, 'optimizer': optimizer, 'lr_scheduler': lr_scheduler} + + name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``. + file_prefix: prefix for the filenames to which objects will be saved. + save_final: whether to save checkpoint or session at final iteration or exception. + If checkpoints are to be saved when an exception is raised, put this handler before + `StatsHandler` in the handler list, because the logic with Ignite can only trigger + the first attached handler for `EXCEPTION_RAISED` event. + save_key_metric: whether to save checkpoint or session when the value of key_metric is + higher than all the previous values during training.keep 4 decimal places of metric, + checkpoint name is: {file_prefix}_key_metric=0.XXXX.pth. + key_metric_name: the name of key_metric in ignite metrics dictionary. + If None, use `engine.state.key_metric` instead. + key_metric_n_saved: save top N checkpoints or sessions, sorted by the value of key + metric in descending order. + epoch_level: save checkpoint during training for every N epochs or every N iterations. + `True` is epoch level, `False` is iteration level. + save_interval: save checkpoint every N epochs, default is 0 to save no checkpoint. + n_saved: save latest N checkpoints of epoch level or iteration level, 'None' is to save all. + + Note: + CheckpointHandler can be used during training, validation or evaluation. + example of saved files: + + - checkpoint_iteration=400.pth + - checkpoint_iteration=800.pth + - checkpoint_epoch=1.pth + - checkpoint_final_iteration=1000.pth + - checkpoint_key_metric=0.9387.pth + + """ + + def __init__( + self, + save_dir: str, + save_dict: Dict, + name: Optional[str] = None, + file_prefix: str = "", + save_final: bool = False, + save_key_metric: bool = False, + key_metric_name: Optional[str] = None, + key_metric_n_saved: int = 1, + epoch_level: bool = True, + save_interval: int = 0, + n_saved: Optional[int] = None, + ) -> None: + assert save_dir is not None, "must provide directory to save the checkpoints." + self.save_dir = save_dir + assert save_dict is not None and len(save_dict) > 0, "must provide source objects to save." + for k, v in save_dict.items(): + if hasattr(v, "module"): + save_dict[k] = v.module + self.save_dict = save_dict + self.logger = logging.getLogger(name) + self.epoch_level = epoch_level + self.save_interval = save_interval + self._final_checkpoint = self._key_metric_checkpoint = self._interval_checkpoint = None + self._name = name + + if save_final: + + def _final_func(engine: Engine): + return engine.state.iteration + + self._final_checkpoint = ModelCheckpoint( + self.save_dir, + file_prefix, + score_function=_final_func, + score_name="final_iteration", + require_empty=False, + ) + if save_key_metric: + + def _score_func(engine: Engine): + if isinstance(key_metric_name, str): + metric_name = key_metric_name + elif hasattr(engine.state, "key_metric_name") and isinstance(engine.state.key_metric_name, str): + metric_name = engine.state.key_metric_name + else: + raise ValueError( + f"Incompatible values: save_key_metric=True and key_metric_name={key_metric_name}." + ) + return round(engine.state.metrics[metric_name], 4) + + self._key_metric_checkpoint = ModelCheckpoint( + self.save_dir, + file_prefix, + score_function=_score_func, + score_name="key_metric", + n_saved=key_metric_n_saved, + require_empty=False, + ) + if save_interval > 0: + + def _interval_func(engine: Engine): + return engine.state.epoch if self.epoch_level else engine.state.iteration + + self._interval_checkpoint = ModelCheckpoint( + self.save_dir, + file_prefix, + score_function=_interval_func, + score_name="epoch" if self.epoch_level else "iteration", + n_saved=n_saved, + require_empty=False, + ) + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + if self._final_checkpoint is not None: + engine.add_event_handler(Events.COMPLETED, self.completed) + engine.add_event_handler(Events.EXCEPTION_RAISED, self.exception_raised) + if self._key_metric_checkpoint is not None: + engine.add_event_handler(Events.EPOCH_COMPLETED, self.metrics_completed) + if self._interval_checkpoint is not None: + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.save_interval), self.interval_completed) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.save_interval), self.interval_completed) + + def completed(self, engine: Engine) -> None: + """Callback for train or validation/evaluation completed Event. + Save final checkpoint if configure save_final is True. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + assert callable(self._final_checkpoint), "Error: _final_checkpoint function not specified." + self._final_checkpoint(engine, self.save_dict) + assert self.logger is not None + assert hasattr(self.logger, "info"), "Error, provided logger has not info attribute." + self.logger.info(f"Train completed, saved final checkpoint: {self._final_checkpoint.last_checkpoint}") + + def exception_raised(self, engine: Engine, e: Exception) -> None: + """Callback for train or validation/evaluation exception raised Event. + Save current data as final checkpoint if configure save_final is True. This callback may be skipped + because the logic with Ignite can only trigger the first attached handler for `EXCEPTION_RAISED` event. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + e: the exception caught in Ignite during engine.run(). + """ + assert callable(self._final_checkpoint), "Error: _final_checkpoint function not specified." + self._final_checkpoint(engine, self.save_dict) + assert self.logger is not None + assert hasattr(self.logger, "info"), "Error, provided logger has not info attribute." + self.logger.info(f"Exception_raised, saved exception checkpoint: {self._final_checkpoint.last_checkpoint}") + raise e + + def metrics_completed(self, engine: Engine) -> None: + """Callback to compare metrics and save models in train or validation when epoch completed. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + assert callable(self._key_metric_checkpoint), "Error: _key_metric_checkpoint function not specified." + self._key_metric_checkpoint(engine, self.save_dict) + + def interval_completed(self, engine: Engine) -> None: + """Callback for train epoch/iteration completed Event. + Save checkpoint if configure save_interval = N + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + assert callable(self._interval_checkpoint), "Error: _interval_checkpoint function not specified." + self._interval_checkpoint(engine, self.save_dict) + assert self.logger is not None + assert hasattr(self.logger, "info"), "Error, provided logger has not info attribute." + if self.epoch_level: + self.logger.info(f"Saved checkpoint at epoch: {engine.state.epoch}") + else: + self.logger.info(f"Saved checkpoint at iteration: {engine.state.iteration}") diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/classification_saver.py b/testbed/Project-MONAI__MONAI/monai/handlers/classification_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..9eeb6134a64f0a44b107b6a3f0b189c2b8e401e9 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/classification_saver.py @@ -0,0 +1,82 @@ +# Copyright 2020 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. + +import logging +from typing import TYPE_CHECKING, Callable, Optional + +from monai.data import CSVSaver +from monai.utils import exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class ClassificationSaver: + """ + Event handler triggered on completing every iteration to save the classification predictions as CSV file. + """ + + def __init__( + self, + output_dir: str = "./", + filename: str = "predictions.csv", + overwrite: bool = True, + batch_transform: Callable = lambda x: x, + output_transform: Callable = lambda x: x, + name: Optional[str] = None, + ) -> None: + """ + Args: + output_dir: output CSV file directory. + filename: name of the saved CSV file name. + overwrite: whether to overwriting existing CSV file content. If we are not overwriting, + then we check if the results have been previously saved, and load them to the prediction_dict. + batch_transform: a callable that is used to transform the + ignite.engine.batch into expected format to extract the meta_data dictionary. + output_transform: a callable that is used to transform the + ignite.engine.output into the form expected model prediction data. + The first dimension of this transform's output will be treated as the + batch dimension. Each item in the batch will be saved individually. + name: identifier of logging.logger to use, defaulting to `engine.logger`. + + """ + self.saver = CSVSaver(output_dir, filename, overwrite) + self.batch_transform = batch_transform + self.output_transform = output_transform + + self.logger = logging.getLogger(name) + self._name = name + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + if not engine.has_event_handler(self, Events.ITERATION_COMPLETED): + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + if not engine.has_event_handler(self.saver.finalize, Events.COMPLETED): + engine.add_event_handler(Events.COMPLETED, lambda engine: self.saver.finalize()) + + def __call__(self, engine: Engine) -> None: + """ + This method assumes self.batch_transform will extract metadata from the input batch. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + meta_data = self.batch_transform(engine.state.batch) + engine_output = self.output_transform(engine.state.output) + self.saver.save_batch(engine_output, meta_data) diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/lr_schedule_handler.py b/testbed/Project-MONAI__MONAI/monai/handlers/lr_schedule_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c59b898547e15562e89e3dd7ab3b55c7d547fb --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/lr_schedule_handler.py @@ -0,0 +1,84 @@ +# Copyright 2020 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. + +import logging +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +from torch.optim.lr_scheduler import ReduceLROnPlateau, _LRScheduler + +from monai.utils import ensure_tuple, exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class LrScheduleHandler: + """ + Ignite handler to update the Learning Rate based on PyTorch LR scheduler. + """ + + def __init__( + self, + lr_scheduler: Union[_LRScheduler, ReduceLROnPlateau], + print_lr: bool = True, + name: Optional[str] = None, + epoch_level: bool = True, + step_transform: Callable[[Engine], Any] = lambda engine: (), + ) -> None: + """ + Args: + lr_scheduler: typically, lr_scheduler should be PyTorch + lr_scheduler object. If customized version, must have `step` and `get_last_lr` methods. + print_lr: whether to print out the latest learning rate with logging. + name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``. + epoch_level: execute lr_scheduler.step() after every epoch or every iteration. + `True` is epoch level, `False` is iteration level. + step_transform: a callable that is used to transform the information from `engine` + to expected input data of lr_scheduler.step() function if necessary. + + Raises: + TypeError: When ``step_transform`` is not ``callable``. + + """ + self.lr_scheduler = lr_scheduler + self.print_lr = print_lr + self.logger = logging.getLogger(name) + self.epoch_level = epoch_level + if not callable(step_transform): + raise TypeError(f"step_transform must be callable but is {type(step_transform).__name__}.") + self.step_transform = step_transform + + self._name = name + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED, self) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + args = ensure_tuple(self.step_transform(engine)) + self.lr_scheduler.step(*args) + if self.print_lr: + self.logger.info(f"Current learning rate: {self.lr_scheduler._last_lr[0]}") # type: ignore[union-attr] diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/mean_dice.py b/testbed/Project-MONAI__MONAI/monai/handlers/mean_dice.py new file mode 100644 index 0000000000000000000000000000000000000000..3e901dcd1d2fb027e062ce288804d655486422db --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/mean_dice.py @@ -0,0 +1,108 @@ +# Copyright 2020 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 typing import Callable, Optional, Sequence + +import torch + +from monai.metrics import DiceMetric +from monai.utils import MetricReduction, exact_version, optional_import + +NotComputableError, _ = optional_import("ignite.exceptions", "0.3.0", exact_version, "NotComputableError") +Metric, _ = optional_import("ignite.metrics", "0.3.0", exact_version, "Metric") +reinit__is_reduced, _ = optional_import("ignite.metrics.metric", "0.3.0", exact_version, "reinit__is_reduced") +sync_all_reduce, _ = optional_import("ignite.metrics.metric", "0.3.0", exact_version, "sync_all_reduce") + + +class MeanDice(Metric): # type: ignore[valid-type, misc] # due to optional_import + """ + Computes Dice score metric from full size Tensor and collects average over batch, class-channels, iterations. + """ + + def __init__( + self, + include_background: bool = True, + to_onehot_y: bool = False, + mutually_exclusive: bool = False, + sigmoid: bool = False, + other_act: Optional[Callable] = None, + logit_thresh: float = 0.5, + output_transform: Callable = lambda x: x, + device: Optional[torch.device] = None, + ) -> None: + """ + + Args: + include_background: whether to include dice computation on the first channel of the predicted output. + Defaults to True. + to_onehot_y: whether to convert the output prediction into the one-hot format. Defaults to False. + mutually_exclusive: if True, the output prediction will be converted into a binary matrix using + a combination of argmax and to_onehot. Defaults to False. + sigmoid: whether to add sigmoid function to the output prediction before computing Dice. + Defaults to False. + other_act: callable function to replace `sigmoid` as activation layer if needed, Defaults to ``None``. + for example: `other_act = torch.tanh`. + logit_thresh: the threshold value to round value to 0.0 and 1.0. Defaults to None (no thresholding). + output_transform: transform the ignite.engine.state.output into [y_pred, y] pair. + device: device specification in case of distributed computation usage. + + See also: + :py:meth:`monai.metrics.meandice.compute_meandice` + """ + super().__init__(output_transform, device=device) + self.dice = DiceMetric( + include_background=include_background, + to_onehot_y=to_onehot_y, + mutually_exclusive=mutually_exclusive, + sigmoid=sigmoid, + other_act=other_act, + logit_thresh=logit_thresh, + reduction=MetricReduction.MEAN, + ) + self._sum = 0.0 + self._num_examples = 0 + + @reinit__is_reduced + def reset(self) -> None: + self._sum = 0.0 + self._num_examples = 0 + + @reinit__is_reduced + def update(self, output: Sequence[torch.Tensor]) -> None: + """ + Args: + output: sequence with contents [y_pred, y]. + + Raises: + ValueError: When ``output`` length is not 2. MeanDice metric can only support y_pred and y. + + """ + if len(output) != 2: + raise ValueError(f"output must have length 2, got {len(output)}.") + y_pred, y = output + score = self.dice(y_pred, y) + assert self.dice.not_nans is not None + not_nans = int(self.dice.not_nans.item()) + + # add all items in current batch + self._sum += score.item() * not_nans + self._num_examples += not_nans + + @sync_all_reduce("_sum", "_num_examples") + def compute(self) -> float: + """ + Raises: + NotComputableError: When ``compute`` is called before an ``update`` occurs. + + """ + if self._num_examples == 0: + raise NotComputableError("MeanDice must have at least one example before it can be computed.") + return self._sum / self._num_examples diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/metric_logger.py b/testbed/Project-MONAI__MONAI/monai/handlers/metric_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..f19da1facfb1544d87ec4c581ef68bb4a7b34217 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/metric_logger.py @@ -0,0 +1,55 @@ +# Copyright 2020 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 collections import defaultdict +from typing import TYPE_CHECKING, Callable, DefaultDict, List + +from monai.utils import exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class MetricLogger: + def __init__(self, loss_transform: Callable = lambda x: x, metric_transform: Callable = lambda x: x) -> None: + self.loss_transform = loss_transform + self.metric_transform = metric_transform + self.loss: List = [] + self.metrics: DefaultDict = defaultdict(list) + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + self.loss.append(self.loss_transform(engine.state.output)) + + for m, v in engine.state.metrics.items(): + v = self.metric_transform(v) + # # metrics may not be added on the first timestep, pad the list if this is the case + # # so that each metric list is the same length as self.loss + # if len(self.metrics[m])==0: + # self.metrics[m].append([v[0]]*len(self.loss)) + + self.metrics[m].append(v) + + +metriclogger = MetricLogger diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/roc_auc.py b/testbed/Project-MONAI__MONAI/monai/handlers/roc_auc.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc48b31e250f016e91a90aa65f0fa103a17f15c --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/roc_auc.py @@ -0,0 +1,119 @@ +# Copyright 2020 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 typing import Callable, List, Optional, Sequence, Union + +import torch +import torch.distributed as dist + +from monai.metrics import compute_roc_auc +from monai.utils import Average, exact_version, optional_import + +Metric, _ = optional_import("ignite.metrics", "0.3.0", exact_version, "Metric") +reinit__is_reduced, _ = optional_import("ignite.metrics.metric", "0.3.0", exact_version, "reinit__is_reduced") + + +class ROCAUC(Metric): # type: ignore[valid-type, misc] # due to optional_import + """ + Computes Area Under the Receiver Operating Characteristic Curve (ROC AUC). + accumulating predictions and the ground-truth during an epoch and applying `compute_roc_auc`. + + Args: + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + softmax: whether to add softmax function to `y_pred` before computation. Defaults to False. + other_act: callable function to replace `softmax` as activation layer if needed, Defaults to ``None``. + for example: `other_act = lambda x: torch.log_softmax(x)`. + average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} + Type of averaging performed if not binary classification. Defaults to ``"macro"``. + + - ``"macro"``: calculate metrics for each label, and find their unweighted mean. + This does not take label imbalance into account. + - ``"weighted"``: calculate metrics for each label, and find their average, + weighted by support (the number of true instances for each label). + - ``"micro"``: calculate metrics globally by considering each element of the label + indicator matrix as a label. + - ``"none"``: the scores for each class are returned. + + output_transform: a callable that is used to transform the + :class:`~ignite.engine.Engine` `process_function` output into the + form expected by the metric. This can be useful if, for example, you have a multi-output model and + you want to compute the metric with respect to one of the outputs. + + Note: + ROCAUC expects y to be comprised of 0's and 1's. + y_pred must either be probability estimates or confidence values. + + """ + + def __init__( + self, + to_onehot_y: bool = False, + softmax: bool = False, + other_act: Optional[Callable] = None, + average: Union[Average, str] = Average.MACRO, + output_transform: Callable = lambda x: x, + ) -> None: + super().__init__(output_transform) + self.to_onehot_y = to_onehot_y + self.softmax = softmax + self.other_act = other_act + self.average: Average = Average(average) + + @reinit__is_reduced + def reset(self) -> None: + self._predictions: List[torch.Tensor] = [] + self._targets: List[torch.Tensor] = [] + + @reinit__is_reduced + def update(self, output: Sequence[torch.Tensor]) -> None: + """ + Args: + output: sequence with contents [y_pred, y]. + + Raises: + ValueError: When ``output`` length is not 2. ROCAUC metric can only support y_pred and y. + ValueError: When ``y_pred`` dimension is not one of [1, 2]. + ValueError: When ``y`` dimension is not one of [1, 2]. + + """ + if len(output) != 2: + raise ValueError(f"output must have length 2, got {len(output)}.") + y_pred, y = output + if y_pred.ndimension() not in (1, 2): + raise ValueError("Predictions should be of shape (batch_size, n_classes) or (batch_size, ).") + if y.ndimension() not in (1, 2): + raise ValueError("Targets should be of shape (batch_size, n_classes) or (batch_size, ).") + + self._predictions.append(y_pred.clone()) + self._targets.append(y.clone()) + + def compute(self): + _prediction_tensor = torch.cat(self._predictions, dim=0) + _target_tensor = torch.cat(self._targets, dim=0) + + if dist.is_available() and dist.is_initialized() and not self._is_reduced: + # create placeholder to collect the data from all processes: + output = [torch.zeros_like(_prediction_tensor) for _ in range(dist.get_world_size())] + dist.all_gather(output, _prediction_tensor) + _prediction_tensor = torch.cat(output, dim=0) + output = [torch.zeros_like(_target_tensor) for _ in range(dist.get_world_size())] + dist.all_gather(output, _target_tensor) + _target_tensor = torch.cat(output, dim=0) + self._is_reduced = True + + return compute_roc_auc( + y_pred=_prediction_tensor, + y=_target_tensor, + to_onehot_y=self.to_onehot_y, + softmax=self.softmax, + other_act=self.other_act, + average=self.average, + ) diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/segmentation_saver.py b/testbed/Project-MONAI__MONAI/monai/handlers/segmentation_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..5c822c016b63a093b97729451966f81ce2a3569c --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/segmentation_saver.py @@ -0,0 +1,130 @@ +# Copyright 2020 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. + +import logging +from typing import TYPE_CHECKING, Callable, Optional, Union + +import numpy as np + +from monai.data import NiftiSaver, PNGSaver +from monai.utils import GridSampleMode, GridSamplePadMode, InterpolateMode, exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class SegmentationSaver: + """ + Event handler triggered on completing every iteration to save the segmentation predictions into files. + """ + + def __init__( + self, + output_dir: str = "./", + output_postfix: str = "seg", + output_ext: str = ".nii.gz", + resample: bool = True, + mode: Union[GridSampleMode, InterpolateMode, str] = "nearest", + padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, + scale: Optional[int] = None, + dtype: Optional[np.dtype] = None, + batch_transform: Callable = lambda x: x, + output_transform: Callable = lambda x: x, + name: Optional[str] = None, + ) -> None: + """ + Args: + output_dir: output image directory. + output_postfix: a string appended to all output file names. + output_ext: output file extension name. + resample: whether to resample before saving the data array. + mode: This option is used when ``resample = True``. Defaults to ``"nearest"``. + + - NIfTI files {``"bilinear"``, ``"nearest"``} + Interpolation mode to calculate output values. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + - PNG files {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} + The interpolation mode. + See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate + + padding_mode: This option is used when ``resample = True``. Defaults to ``"border"``. + + - NIfTI files {``"zeros"``, ``"border"``, ``"reflection"``} + Padding mode for outside grid values. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + - PNG files + This option is ignored. + + scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling + [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling. + It's used for PNG format only. + dtype: convert the image data to save to this data type. + If None, keep the original type of data. It's used for Nifti format only. + batch_transform: a callable that is used to transform the + ignite.engine.batch into expected format to extract the meta_data dictionary. + output_transform: a callable that is used to transform the + ignite.engine.output into the form expected image data. + The first dimension of this transform's output will be treated as the + batch dimension. Each item in the batch will be saved individually. + name: identifier of logging.logger to use, defaulting to `engine.logger`. + + """ + self.saver: Union[NiftiSaver, PNGSaver] + if output_ext in (".nii.gz", ".nii"): + self.saver = NiftiSaver( + output_dir=output_dir, + output_postfix=output_postfix, + output_ext=output_ext, + resample=resample, + mode=GridSampleMode(mode), + padding_mode=padding_mode, + dtype=dtype, + ) + elif output_ext == ".png": + self.saver = PNGSaver( + output_dir=output_dir, + output_postfix=output_postfix, + output_ext=output_ext, + resample=resample, + mode=InterpolateMode(mode), + scale=scale, + ) + self.batch_transform = batch_transform + self.output_transform = output_transform + + self.logger = logging.getLogger(name) + self._name = name + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + if not engine.has_event_handler(self, Events.ITERATION_COMPLETED): + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + + def __call__(self, engine: Engine) -> None: + """ + This method assumes self.batch_transform will extract metadata from the input batch. + Output file datatype is determined from ``engine.state.output.dtype``. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + meta_data = self.batch_transform(engine.state.batch) + engine_output = self.output_transform(engine.state.output) + self.saver.save_batch(engine_output, meta_data) + self.logger.info("saved all the model outputs into files.") diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/smartcache_handler.py b/testbed/Project-MONAI__MONAI/monai/handlers/smartcache_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..309481c4f9fef565ae412405f6c9eda5876ddc4d --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/smartcache_handler.py @@ -0,0 +1,78 @@ +# Copyright 2020 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 typing import TYPE_CHECKING + +from monai.data import SmartCacheDataset +from monai.utils import exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class SmartCacheHandler: + """ + Attach SmartCache logic to the engine in Ignite. + Mainly include the `start`, `update_cache`, and `shutdown` functions of SmartCacheDataset. + + """ + + def __init__(self, smartcacher: SmartCacheDataset) -> None: + """ + Args: + smartcacher: predefined SmartCacheDataset, will attach it to the engine. + + Raises: + TypeError: When ``smartcacher`` is not a ``monai.data.SmartCacheDataset``. + + """ + if not isinstance(smartcacher, SmartCacheDataset): + raise TypeError("smartcacher must be a monai.data.SmartCacheDataset.") + self.smartcacher = smartcacher + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + engine.add_event_handler(Events.STARTED, self.started) + engine.add_event_handler(Events.EPOCH_COMPLETED, self.epoch_completed) + engine.add_event_handler(Events.COMPLETED, self.completed) + + def started(self, engine: Engine) -> None: + """Callback for train or validation/evaluation started Event. + Start the replacement thread of SmartCacheDataset. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + self.smartcacher.start() + + def epoch_completed(self, engine: Engine) -> None: + """Callback for train or validation/evaluation epoch completed Event. + Update cache content with replacement data. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + self.smartcacher.update_cache() + + def completed(self, engine: Engine) -> None: + """Callback for train or validation/evaluation completed Event. + Stop the replacement thread of SmartCacheDataset. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + self.smartcacher.shutdown() diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/stats_handler.py b/testbed/Project-MONAI__MONAI/monai/handlers/stats_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..2546e402047a6ade26917425eb051a94bc9a8b7f --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/stats_handler.py @@ -0,0 +1,221 @@ +# Copyright 2020 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. + +import logging +import warnings +from typing import TYPE_CHECKING, Any, Callable, Optional + +import torch + +from monai.utils import exact_version, is_scalar, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + +DEFAULT_KEY_VAL_FORMAT = "{}: {:.4f} " +DEFAULT_TAG = "Loss" + + +class StatsHandler(object): + """ + StatsHandler defines a set of Ignite Event-handlers for all the log printing logics. + It's can be used for any Ignite Engine(trainer, validator and evaluator). + And it can support logging for epoch level and iteration level with pre-defined loggers. + + Default behaviors: + - When EPOCH_COMPLETED, logs ``engine.state.metrics`` using ``self.logger``. + - When ITERATION_COMPLETED, logs + ``self.output_transform(engine.state.output)`` using ``self.logger``. + + """ + + def __init__( + self, + epoch_print_logger: Optional[Callable[[Engine], Any]] = None, + iteration_print_logger: Optional[Callable[[Engine], Any]] = None, + output_transform: Callable = lambda x: x, + global_epoch_transform: Callable = lambda x: x, + name: Optional[str] = None, + tag_name: str = DEFAULT_TAG, + key_var_format: str = DEFAULT_KEY_VAL_FORMAT, + logger_handler: Optional[logging.Handler] = None, + ) -> None: + """ + + Args: + epoch_print_logger: customized callable printer for epoch level logging. + Must accept parameter "engine", use default printer if None. + iteration_print_logger: customized callable printer for iteration level logging. + Must accept parameter "engine", use default printer if None. + output_transform: a callable that is used to transform the + ``ignite.engine.output`` into a scalar to print, or a dictionary of {key: scalar}. + In the latter case, the output string will be formatted as key: value. + By default this value logging happens when every iteration completed. + global_epoch_transform: a callable that is used to customize global epoch number. + For example, in evaluation, the evaluator engine might want to print synced epoch number + with the trainer engine. + name: identifier of logging.logger to use, defaulting to ``engine.logger``. + tag_name: when iteration output is a scalar, tag_name is used to print + tag_name: scalar_value to logger. Defaults to ``'Loss'``. + key_var_format: a formatting string to control the output string format of key: value. + logger_handler: add additional handler to handle the stats data: save to file, etc. + Add existing python logging handlers: https://docs.python.org/3/library/logging.handlers.html + """ + + self.epoch_print_logger = epoch_print_logger + self.iteration_print_logger = iteration_print_logger + self.output_transform = output_transform + self.global_epoch_transform = global_epoch_transform + self.logger = logging.getLogger(name) + self._name = name + + self.tag_name = tag_name + self.key_var_format = key_var_format + if logger_handler is not None: + self.logger.addHandler(logger_handler) + + def attach(self, engine: Engine) -> None: + """ + Register a set of Ignite Event-Handlers to a specified Ignite engine. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self._name is None: + self.logger = engine.logger + if not engine.has_event_handler(self.iteration_completed, Events.ITERATION_COMPLETED): + engine.add_event_handler(Events.ITERATION_COMPLETED, self.iteration_completed) + if not engine.has_event_handler(self.epoch_completed, Events.EPOCH_COMPLETED): + engine.add_event_handler(Events.EPOCH_COMPLETED, self.epoch_completed) + if not engine.has_event_handler(self.exception_raised, Events.EXCEPTION_RAISED): + engine.add_event_handler(Events.EXCEPTION_RAISED, self.exception_raised) + + def epoch_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation epoch completed Event. + Print epoch level log, default values are from Ignite state.metrics dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.epoch_print_logger is not None: + self.epoch_print_logger(engine) + else: + self._default_epoch_print(engine) + + def iteration_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation iteration completed Event. + Print iteration level log, default values are from Ignite state.logs dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.iteration_print_logger is not None: + self.iteration_print_logger(engine) + else: + self._default_iteration_print(engine) + + def exception_raised(self, engine: Engine, e: Exception) -> None: + """ + Handler for train or validation/evaluation exception raised Event. + Print the exception information and traceback. This callback may be skipped because the logic + with Ignite can only trigger the first attached handler for `EXCEPTION_RAISED` event. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + e: the exception caught in Ignite during engine.run(). + + """ + self.logger.exception(f"Exception: {e}") + raise e + + def _default_epoch_print(self, engine: Engine) -> None: + """ + Execute epoch level log operation based on Ignite engine.state data. + print the values from Ignite state.metrics dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + prints_dict = engine.state.metrics + if not prints_dict: + return + current_epoch = self.global_epoch_transform(engine.state.epoch) + + out_str = f"Epoch[{current_epoch}] Metrics -- " + for name in sorted(prints_dict): + value = prints_dict[name] + out_str += self.key_var_format.format(name, value) + self.logger.info(out_str) + + if hasattr(engine.state, "key_metric_name"): + if hasattr(engine.state, "best_metric") and hasattr(engine.state, "best_metric_epoch"): + out_str = f"Key metric: {engine.state.key_metric_name} " + out_str += f"best value: {engine.state.best_metric} at epoch: {engine.state.best_metric_epoch}" + self.logger.info(out_str) + + def _default_iteration_print(self, engine: Engine) -> None: + """ + Execute iteration log operation based on Ignite engine.state data. + Print the values from Ignite state.logs dict. + Default behavior is to print loss from output[1], skip if output[1] is not loss. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + loss = self.output_transform(engine.state.output) + if loss is None: + return # no printing if the output is empty + + out_str = "" + if isinstance(loss, dict): # print dictionary items + for name in sorted(loss): + value = loss[name] + if not is_scalar(value): + warnings.warn( + "ignoring non-scalar output in StatsHandler," + " make sure `output_transform(engine.state.output)` returns" + " a scalar or dictionary of key and scalar pairs to avoid this warning." + " {}:{}".format(name, type(value)) + ) + continue # not printing multi dimensional output + out_str += self.key_var_format.format(name, value.item() if torch.is_tensor(value) else value) + else: + if is_scalar(loss): # not printing multi dimensional output + out_str += self.key_var_format.format(self.tag_name, loss.item() if torch.is_tensor(loss) else loss) + else: + warnings.warn( + "ignoring non-scalar output in StatsHandler," + " make sure `output_transform(engine.state.output)` returns" + " a scalar or a dictionary of key and scalar pairs to avoid this warning." + " {}".format(type(loss)) + ) + + if not out_str: + return # no value to print + + num_iterations = engine.state.epoch_length + current_iteration = (engine.state.iteration - 1) % num_iterations + 1 + current_epoch = engine.state.epoch + num_epochs = engine.state.max_epochs + + base_str = f"Epoch: {current_epoch}/{num_epochs}, Iter: {current_iteration}/{num_iterations} --" + + self.logger.info(" ".join([base_str, out_str])) diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/tensorboard_handlers.py b/testbed/Project-MONAI__MONAI/monai/handlers/tensorboard_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab323a6e0da773194acce336b450934619489b2 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/tensorboard_handlers.py @@ -0,0 +1,302 @@ +# Copyright 2020 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. + +import warnings +from typing import TYPE_CHECKING, Any, Callable, Optional + +import numpy as np +import torch + +from monai.utils import exact_version, is_scalar, optional_import +from monai.visualize import plot_2d_or_3d_image + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine + from torch.utils.tensorboard import SummaryWriter +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter") + +DEFAULT_TAG = "Loss" + + +class TensorBoardStatsHandler(object): + """ + TensorBoardStatsHandler defines a set of Ignite Event-handlers for all the TensorBoard logics. + It's can be used for any Ignite Engine(trainer, validator and evaluator). + And it can support both epoch level and iteration level with pre-defined TensorBoard event writer. + The expected data source is Ignite ``engine.state.output`` and ``engine.state.metrics``. + + Default behaviors: + - When EPOCH_COMPLETED, write each dictionary item in + ``engine.state.metrics`` to TensorBoard. + - When ITERATION_COMPLETED, write each dictionary item in + ``self.output_transform(engine.state.output)`` to TensorBoard. + """ + + def __init__( + self, + summary_writer: Optional[SummaryWriter] = None, + log_dir: str = "./runs", + epoch_event_writer: Optional[Callable[[Engine, SummaryWriter], Any]] = None, + iteration_event_writer: Optional[Callable[[Engine, SummaryWriter], Any]] = None, + output_transform: Callable = lambda x: x, + global_epoch_transform: Callable = lambda x: x, + tag_name: str = DEFAULT_TAG, + ) -> None: + """ + Args: + summary_writer: user can specify TensorBoard SummaryWriter, + default to create a new writer. + log_dir: if using default SummaryWriter, write logs to this directory, default is `./runs`. + epoch_event_writer: customized callable TensorBoard writer for epoch level. + Must accept parameter "engine" and "summary_writer", use default event writer if None. + iteration_event_writer: customized callable TensorBoard writer for iteration level. + Must accept parameter "engine" and "summary_writer", use default event writer if None. + output_transform: a callable that is used to transform the + ``ignite.engine.output`` into a scalar to plot, or a dictionary of {key: scalar}. + In the latter case, the output string will be formatted as key: value. + By default this value plotting happens when every iteration completed. + global_epoch_transform: a callable that is used to customize global epoch number. + For example, in evaluation, the evaluator engine might want to use trainer engines epoch number + when plotting epoch vs metric curves. + tag_name: when iteration output is a scalar, tag_name is used to plot, defaults to ``'Loss'``. + """ + self._writer = SummaryWriter(log_dir=log_dir) if summary_writer is None else summary_writer + self.epoch_event_writer = epoch_event_writer + self.iteration_event_writer = iteration_event_writer + self.output_transform = output_transform + self.global_epoch_transform = global_epoch_transform + self.tag_name = tag_name + + def attach(self, engine: Engine) -> None: + """ + Register a set of Ignite Event-Handlers to a specified Ignite engine. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if not engine.has_event_handler(self.iteration_completed, Events.ITERATION_COMPLETED): + engine.add_event_handler(Events.ITERATION_COMPLETED, self.iteration_completed) + if not engine.has_event_handler(self.epoch_completed, Events.EPOCH_COMPLETED): + engine.add_event_handler(Events.EPOCH_COMPLETED, self.epoch_completed) + + def epoch_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation epoch completed Event. + Write epoch level events, default values are from Ignite state.metrics dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.epoch_event_writer is not None: + self.epoch_event_writer(engine, self._writer) + else: + self._default_epoch_writer(engine, self._writer) + + def iteration_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation iteration completed Event. + Write iteration level events, default values are from Ignite state.logs dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.iteration_event_writer is not None: + self.iteration_event_writer(engine, self._writer) + else: + self._default_iteration_writer(engine, self._writer) + + def _default_epoch_writer(self, engine: Engine, writer: SummaryWriter) -> None: + """ + Execute epoch level event write operation based on Ignite engine.state data. + Default is to write the values from Ignite state.metrics dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + writer: TensorBoard writer, created in TensorBoardHandler. + + """ + current_epoch = self.global_epoch_transform(engine.state.epoch) + summary_dict = engine.state.metrics + for name, value in summary_dict.items(): + writer.add_scalar(name, value, current_epoch) + writer.flush() + + def _default_iteration_writer(self, engine: Engine, writer: SummaryWriter) -> None: + """ + Execute iteration level event write operation based on Ignite engine.state data. + Default is to write the loss value of current iteration. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + writer: TensorBoard writer, created in TensorBoardHandler. + + """ + loss = self.output_transform(engine.state.output) + if loss is None: + return # do nothing if output is empty + if isinstance(loss, dict): + for name in sorted(loss): + value = loss[name] + if not is_scalar(value): + warnings.warn( + "ignoring non-scalar output in TensorBoardStatsHandler," + " make sure `output_transform(engine.state.output)` returns" + " a scalar or dictionary of key and scalar pairs to avoid this warning." + " {}:{}".format(name, type(value)) + ) + continue # not plot multi dimensional output + writer.add_scalar(name, value.item() if torch.is_tensor(value) else value, engine.state.iteration) + elif is_scalar(loss): # not printing multi dimensional output + writer.add_scalar(self.tag_name, loss.item() if torch.is_tensor(loss) else loss, engine.state.iteration) + else: + warnings.warn( + "ignoring non-scalar output in TensorBoardStatsHandler," + " make sure `output_transform(engine.state.output)` returns" + " a scalar or a dictionary of key and scalar pairs to avoid this warning." + " {}".format(type(loss)) + ) + writer.flush() + + +class TensorBoardImageHandler(object): + """ + TensorBoardImageHandler is an Ignite Event handler that can visualise images, labels and outputs as 2D/3D images. + 2D output (shape in Batch, channel, H, W) will be shown as simple image using the first element in the batch, + for 3D to ND output (shape in Batch, channel, H, W, D) input, each of ``self.max_channels`` number of images' + last three dimensions will be shown as animated GIF along the last axis (typically Depth). + + It can be used for any Ignite Engine (trainer, validator and evaluator). + User can easily add it to engine for any expected Event, for example: ``EPOCH_COMPLETED``, + ``ITERATION_COMPLETED``. The expected data source is ignite's ``engine.state.batch`` and ``engine.state.output``. + + Default behavior: + - Show y_pred as images (GIF for 3D) on TensorBoard when Event triggered, + - Need to use ``batch_transform`` and ``output_transform`` to specify + how many images to show and show which channel. + - Expects ``batch_transform(engine.state.batch)`` to return data + format: (image[N, channel, ...], label[N, channel, ...]). + - Expects ``output_transform(engine.state.output)`` to return a torch + tensor in format (y_pred[N, channel, ...], loss). + + """ + + def __init__( + self, + summary_writer: Optional[SummaryWriter] = None, + log_dir: str = "./runs", + interval: int = 1, + epoch_level: bool = True, + batch_transform: Callable = lambda x: x, + output_transform: Callable = lambda x: x, + global_iter_transform: Callable = lambda x: x, + index: int = 0, + max_channels: int = 1, + max_frames: int = 64, + ) -> None: + """ + Args: + summary_writer: user can specify TensorBoard SummaryWriter, + default to create a new writer. + log_dir: if using default SummaryWriter, write logs to this directory, default is `./runs`. + interval: plot content from engine.state every N epochs or every N iterations, default is 1. + epoch_level: plot content from engine.state every N epochs or N iterations. `True` is epoch level, + `False` is iteration level. + batch_transform: a callable that is used to transform the + ``ignite.engine.batch`` into expected format to extract several label data. + output_transform: a callable that is used to transform the + ``ignite.engine.output`` into expected format to extract several output data. + global_iter_transform: a callable that is used to customize global step number for TensorBoard. + For example, in evaluation, the evaluator engine needs to know current epoch from trainer. + index: plot which element in a data batch, default is the first element. + max_channels: number of channels to plot. + max_frames: number of frames for 2D-t plot. + """ + self._writer = SummaryWriter(log_dir=log_dir) if summary_writer is None else summary_writer + self.interval = interval + self.epoch_level = epoch_level + self.batch_transform = batch_transform + self.output_transform = output_transform + self.global_iter_transform = global_iter_transform + self.index = index + self.max_frames = max_frames + self.max_channels = max_channels + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.interval), self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + Raises: + TypeError: When ``output_transform(engine.state.output)[0]`` type is not in + ``Optional[Union[numpy.ndarray, torch.Tensor]]``. + TypeError: When ``batch_transform(engine.state.batch)[1]`` type is not in + ``Optional[Union[numpy.ndarray, torch.Tensor]]``. + TypeError: When ``output_transform(engine.state.output)`` type is not in + ``Optional[Union[numpy.ndarray, torch.Tensor]]``. + + """ + step = self.global_iter_transform(engine.state.epoch if self.epoch_level else engine.state.iteration) + show_images = self.batch_transform(engine.state.batch)[0] + if torch.is_tensor(show_images): + show_images = show_images.detach().cpu().numpy() + if show_images is not None: + if not isinstance(show_images, np.ndarray): + raise TypeError( + "output_transform(engine.state.output)[0] must be None or one of " + f"(numpy.ndarray, torch.Tensor) but is {type(show_images).__name__}." + ) + plot_2d_or_3d_image( + show_images, step, self._writer, self.index, self.max_channels, self.max_frames, "input_0" + ) + + show_labels = self.batch_transform(engine.state.batch)[1] + if torch.is_tensor(show_labels): + show_labels = show_labels.detach().cpu().numpy() + if show_labels is not None: + if not isinstance(show_labels, np.ndarray): + raise TypeError( + "batch_transform(engine.state.batch)[1] must be None or one of " + f"(numpy.ndarray, torch.Tensor) but is {type(show_labels).__name__}." + ) + plot_2d_or_3d_image( + show_labels, step, self._writer, self.index, self.max_channels, self.max_frames, "input_1" + ) + + show_outputs = self.output_transform(engine.state.output) + if torch.is_tensor(show_outputs): + show_outputs = show_outputs.detach().cpu().numpy() + if show_outputs is not None: + if not isinstance(show_outputs, np.ndarray): + raise TypeError( + "output_transform(engine.state.output) must be None or one of " + f"(numpy.ndarray, torch.Tensor) but is {type(show_outputs).__name__}." + ) + plot_2d_or_3d_image( + show_outputs, step, self._writer, self.index, self.max_channels, self.max_frames, "output" + ) + + self._writer.flush() diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/utils.py b/testbed/Project-MONAI__MONAI/monai/handlers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..051ec74be70f24ea9ad7a142de199da1a8dede04 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/utils.py @@ -0,0 +1,41 @@ +# Copyright 2020 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 typing import TYPE_CHECKING, Any, Callable + +from monai.utils import exact_version, optional_import + +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +def stopping_fn_from_metric(metric_name: str) -> Callable[[Engine], Any]: + """ + Returns a stopping function for ignite.handlers.EarlyStopping using the given metric name. + """ + + def stopping_fn(engine: Engine): + return engine.state.metrics[metric_name] + + return stopping_fn + + +def stopping_fn_from_loss() -> Callable[[Engine], Any]: + """ + Returns a stopping function for ignite.handlers.EarlyStopping using the loss value. + """ + + def stopping_fn(engine: Engine): + return -engine.state.output + + return stopping_fn diff --git a/testbed/Project-MONAI__MONAI/monai/handlers/validation_handler.py b/testbed/Project-MONAI__MONAI/monai/handlers/validation_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..e03d4909eaee66302d676c39c983786470e93433 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/handlers/validation_handler.py @@ -0,0 +1,64 @@ +# Copyright 2020 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 typing import TYPE_CHECKING + +from monai.engines.evaluator import Evaluator +from monai.utils import exact_version, optional_import + +Events, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", "0.3.0", exact_version, "Engine") + + +class ValidationHandler: + """ + Attach validator to the trainer engine in Ignite. + It can support to execute validation every N epochs or every N iterations. + + """ + + def __init__(self, validator: Evaluator, interval: int, epoch_level: bool = True) -> None: + """ + Args: + validator: run the validator when trigger validation, suppose to be Evaluator. + interval: do validation every N epochs or every N iterations during training. + epoch_level: execute validation every N epochs or N iterations. + `True` is epoch level, `False` is iteration level. + + Raises: + TypeError: When ``validator`` is not a ``monai.engines.evaluator.Evaluator``. + + """ + if not isinstance(validator, Evaluator): + raise TypeError(f"validator must be a monai.engines.evaluator.Evaluator but is {type(validator).__name__}.") + self.validator = validator + self.interval = interval + self.epoch_level = epoch_level + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.interval), self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + self.validator.run(engine.state.epoch) diff --git a/testbed/Project-MONAI__MONAI/monai/losses/__init__.py b/testbed/Project-MONAI__MONAI/monai/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a11ccf3e2be0b4e4de883bacbe90e4c3702f69ad --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/losses/__init__.py @@ -0,0 +1,22 @@ +# Copyright 2020 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 .dice import ( + Dice, + DiceLoss, + GeneralizedDiceLoss, + GeneralizedWassersteinDiceLoss, + MaskedDiceLoss, + dice, + generalized_dice, +) +from .focal_loss import FocalLoss +from .tversky import TverskyLoss diff --git a/testbed/Project-MONAI__MONAI/monai/losses/dice.py b/testbed/Project-MONAI__MONAI/monai/losses/dice.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8bf967640d29f5605ea432c84df53b0a425dcb --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/losses/dice.py @@ -0,0 +1,512 @@ +# Copyright 2020 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. + +import warnings +from typing import Callable, Optional, Union + +import numpy as np +import torch +import torch.nn.functional as F +from torch.nn.modules.loss import _Loss + +from monai.networks import one_hot +from monai.utils import LossReduction, Weight + + +class DiceLoss(_Loss): + """ + Compute average Dice loss between two tensors. It can support both multi-classes and multi-labels tasks. + Input logits `input` (BNHW[D] where N is number of classes) is compared with ground truth `target` (BNHW[D]). + Axis N of `input` is expected to have logit predictions for each class rather than being image channels, + while the same axis of `target` can be 1 or N (one-hot format). The `smooth` parameter is a value added to the + intersection and union components of the inter-over-union calculation to smooth results and prevent divide by 0, + this value should be small. The `include_background` class attribute can be set to False for an instance of + DiceLoss to exclude the first category (channel index 0) which is by convention assumed to be background. + If the non-background segmentations are small compared to the total image size they can get overwhelmed by + the signal from the background so excluding it in such cases helps convergence. + + Milletari, F. et. al. (2016) V-Net: Fully Convolutional Neural Networks forVolumetric Medical Image Segmentation, 3DV, 2016. + + """ + + def __init__( + self, + include_background: bool = True, + to_onehot_y: bool = False, + sigmoid: bool = False, + softmax: bool = False, + other_act: Optional[Callable] = None, + squared_pred: bool = False, + jaccard: bool = False, + reduction: Union[LossReduction, str] = LossReduction.MEAN, + ) -> None: + """ + Args: + include_background: if False channel index 0 (background category) is excluded from the calculation. + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + sigmoid: if True, apply a sigmoid function to the prediction. + softmax: if True, apply a softmax function to the prediction. + other_act: if don't want to use `sigmoid` or `softmax`, use other callable function to execute + other activation layers, Defaults to ``None``. for example: + `other_act = torch.tanh`. + squared_pred: use squared versions of targets and predictions in the denominator or not. + jaccard: compute Jaccard Index (soft IoU) instead of dice or not. + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + + Raises: + TypeError: When ``other_act`` is not an ``Optional[Callable]``. + ValueError: When more than 1 of [``sigmoid=True``, ``softmax=True``, ``other_act is not None``]. + Incompatible values. + + """ + super().__init__(reduction=LossReduction(reduction).value) + if other_act is not None and not callable(other_act): + raise TypeError(f"other_act must be None or callable but is {type(other_act).__name__}.") + if int(sigmoid) + int(softmax) + int(other_act is not None) > 1: + raise ValueError("Incompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None].") + self.include_background = include_background + self.to_onehot_y = to_onehot_y + self.sigmoid = sigmoid + self.softmax = softmax + self.other_act = other_act + self.squared_pred = squared_pred + self.jaccard = jaccard + + def forward(self, input: torch.Tensor, target: torch.Tensor, smooth: float = 1e-5) -> torch.Tensor: + """ + Args: + input: the shape should be BNH[WD]. + target: the shape should be BNH[WD]. + smooth: a small constant to avoid nan. + + Raises: + ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. + + """ + if self.sigmoid: + input = torch.sigmoid(input) + + n_pred_ch = input.shape[1] + if self.softmax: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `softmax=True` ignored.") + else: + input = torch.softmax(input, 1) + + if self.other_act is not None: + input = self.other_act(input) + + if self.to_onehot_y: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `to_onehot_y=True` ignored.") + else: + target = one_hot(target, num_classes=n_pred_ch) + + if not self.include_background: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `include_background=False` ignored.") + else: + # if skipping background, removing first channel + target = target[:, 1:] + input = input[:, 1:] + + assert ( + target.shape == input.shape + ), f"ground truth has differing shape ({target.shape}) from input ({input.shape})" + + # reducing only spatial dimensions (not batch nor channels) + reduce_axis = list(range(2, len(input.shape))) + intersection = torch.sum(target * input, dim=reduce_axis) + + if self.squared_pred: + target = torch.pow(target, 2) + input = torch.pow(input, 2) + + ground_o = torch.sum(target, dim=reduce_axis) + pred_o = torch.sum(input, dim=reduce_axis) + + denominator = ground_o + pred_o + + if self.jaccard: + denominator = 2.0 * (denominator - intersection) + + f: torch.Tensor = 1.0 - (2.0 * intersection + smooth) / (denominator + smooth) + + if self.reduction == LossReduction.MEAN.value: + f = torch.mean(f) # the batch and channel average + elif self.reduction == LossReduction.SUM.value: + f = torch.sum(f) # sum over the batch and channel dims + elif self.reduction == LossReduction.NONE.value: + pass # returns [N, n_classes] losses + else: + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') + + return f + + +class MaskedDiceLoss(DiceLoss): + """ + Add an additional `masking` process before `DiceLoss`, accept a binary mask ([0, 1]) indicating a region, + `input` and `target` will be masked by the region: region with mask `1` will keep the original value, + region with `0` mask will be converted to `0`. Then feed `input` and `target` to normal `DiceLoss` computation. + This has the effect of ensuring only the masked region contributes to the loss computation and + hence gradient calculation. + + """ + + def forward( + self, input: torch.Tensor, target: torch.Tensor, smooth: float = 1e-5, mask: Optional[torch.Tensor] = None + ) -> torch.Tensor: + """ + Args: + input: the shape should be BNH[WD]. + target: the shape should be BNH[WD]. + smooth: a small constant to avoid nan. + mask: the shape should B1H[WD] or 11H[WD]. + """ + if mask is not None: + # checking if mask is of proper shape + assert input.dim() == mask.dim(), f"dim of input ({input.shape}) is different from mask ({mask.shape})" + assert ( + input.shape[0] == mask.shape[0] or mask.shape[0] == 1 + ), f" batch size of mask ({mask.shape}) must be 1 or equal to input ({input.shape})" + + if target.dim() > 1: + assert mask.shape[1] == 1, f"mask ({mask.shape}) must have only 1 channel" + assert ( + input.shape[2:] == mask.shape[2:] + ), f"spatial size of input ({input.shape}) is different from mask ({mask.shape})" + + input = input * mask + target = target * mask + else: + warnings.warn("no mask value specified for the MaskedDiceLoss.") + + return super().forward(input=input, target=target, smooth=smooth) + + +class GeneralizedDiceLoss(_Loss): + """ + Compute the generalised Dice loss defined in: + + Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning + loss function for highly unbalanced segmentations. DLMIA 2017. + + Adapted from: + https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/layer/loss_segmentation.py#L279 + """ + + def __init__( + self, + include_background: bool = True, + to_onehot_y: bool = False, + sigmoid: bool = False, + softmax: bool = False, + other_act: Optional[Callable] = None, + w_type: Union[Weight, str] = Weight.SQUARE, + reduction: Union[LossReduction, str] = LossReduction.MEAN, + ) -> None: + """ + Args: + include_background: If False channel index 0 (background category) is excluded from the calculation. + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + sigmoid: If True, apply a sigmoid function to the prediction. + softmax: If True, apply a softmax function to the prediction. + other_act: if don't want to use `sigmoid` or `softmax`, use other callable function to execute + other activation layers, Defaults to ``None``. for example: + `other_act = torch.tanh`. + squared_pred: use squared versions of targets and predictions in the denominator or not. + w_type: {``"square"``, ``"simple"``, ``"uniform"``} + Type of function to transform ground truth volume to a weight factor. Defaults to ``"square"``. + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + + Raises: + TypeError: When ``other_act`` is not an ``Optional[Callable]``. + ValueError: When more than 1 of [``sigmoid=True``, ``softmax=True``, ``other_act is not None``]. + Incompatible values. + + """ + super().__init__(reduction=LossReduction(reduction).value) + if other_act is not None and not callable(other_act): + raise TypeError(f"other_act must be None or callable but is {type(other_act).__name__}.") + if int(sigmoid) + int(softmax) + int(other_act is not None) > 1: + raise ValueError("Incompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None].") + self.include_background = include_background + self.to_onehot_y = to_onehot_y + self.sigmoid = sigmoid + self.softmax = softmax + self.other_act = other_act + + w_type = Weight(w_type) + self.w_func: Callable = torch.ones_like + if w_type == Weight.SIMPLE: + self.w_func = torch.reciprocal + elif w_type == Weight.SQUARE: + self.w_func = lambda x: torch.reciprocal(x * x) + + def forward(self, input: torch.Tensor, target: torch.Tensor, smooth: float = 1e-5) -> torch.Tensor: + """ + Args: + input: the shape should be BNH[WD]. + target: the shape should be BNH[WD]. + smooth: a small constant to avoid nan. + + Raises: + ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. + + """ + if self.sigmoid: + input = torch.sigmoid(input) + n_pred_ch = input.shape[1] + if self.softmax: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `softmax=True` ignored.") + else: + input = torch.softmax(input, 1) + + if self.other_act is not None: + input = self.other_act(input) + + if self.to_onehot_y: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `to_onehot_y=True` ignored.") + else: + target = one_hot(target, num_classes=n_pred_ch) + + if not self.include_background: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `include_background=False` ignored.") + else: + # if skipping background, removing first channel + target = target[:, 1:] + input = input[:, 1:] + + assert ( + target.shape == input.shape + ), f"ground truth has differing shape ({target.shape}) from input ({input.shape})" + + # reducing only spatial dimensions (not batch nor channels) + reduce_axis = list(range(2, len(input.shape))) + intersection = torch.sum(target * input, reduce_axis) + + ground_o = torch.sum(target, reduce_axis) + pred_o = torch.sum(input, reduce_axis) + + denominator = ground_o + pred_o + + w = self.w_func(ground_o.float()) + for b in w: + infs = torch.isinf(b) + b[infs] = 0.0 + b[infs] = torch.max(b) + + f: torch.Tensor = 1.0 - (2.0 * (intersection * w).sum(1) + smooth) / ((denominator * w).sum(1) + smooth) + + if self.reduction == LossReduction.MEAN.value: + f = torch.mean(f) # the batch and channel average + elif self.reduction == LossReduction.SUM.value: + f = torch.sum(f) # sum over the batch and channel dims + elif self.reduction == LossReduction.NONE.value: + pass # returns [N, n_classes] losses + else: + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') + + return f + + +class GeneralizedWassersteinDiceLoss(_Loss): + """ + Generalized Wasserstein Dice Loss [1] in PyTorch. + Compared to [1] we used a weighting method similar to the one + used in the generalized Dice Loss [2]. + + References: + =========== + [1] "Generalised Wasserstein Dice Score for Imbalanced Multi-class + Segmentation using Holistic Convolutional Networks", + Fidon L. et al. MICCAI BrainLes 2017. + [2] "Generalised dice overlap as a deep learning loss function + for highly unbalanced segmentations", + Sudre C., et al. MICCAI DLMIA 2017. + + wasserstein_distance_map: + Compute the voxel-wise Wasserstein distance (eq. 6 in [1]) between the + flattened prediction and the flattened labels (ground_truth) with respect + to the distance matrix on the label space M. + References: + [1] "Generalised Wasserstein Dice Score for Imbalanced Multi-class + Segmentation using Holistic Convolutional Networks", + Fidon L. et al. MICCAI BrainLes 2017 + + compute_weights_generalized_true_positives: + Compute the weights \alpha_l of eq. 9 in [1] but using the weighting + method proposed in the generalized Dice Loss [2]. + References: + [1] "Generalised Wasserstein Dice Score for Imbalanced Multi-class + Segmentation using Holistic Convolutional Networks", + Fidon L. et al. MICCAI BrainLes 2017 + [2] "Generalised dice overlap as a deep learning loss function + for highly unbalanced segmentations." Sudre C., et al. + MICCAI DLMIA 2017. + """ + + def __init__( + self, dist_matrix: Union[np.ndarray, torch.Tensor], reduction: Union[LossReduction, str] = LossReduction.MEAN + ) -> None: + """ + Args: + dist_matrix: 2d tensor or 2d numpy array; matrix of distances + between the classes. It must have dimension C x C where C is the + number of classes. + reduction: str; reduction mode. + + Raises: + ValueError: When ``dist_matrix`` is not a square matrix. + + """ + super(GeneralizedWassersteinDiceLoss, self).__init__(reduction=LossReduction(reduction).value) + + if dist_matrix.shape[0] != dist_matrix.shape[1]: + raise ValueError(f"dist_matrix must be C x C, got {dist_matrix.shape[0]} x {dist_matrix.shape[1]}.") + + self.m = dist_matrix + if isinstance(self.m, np.ndarray): + self.m = torch.from_numpy(self.m) + if torch.max(self.m) != 1: + self.m = self.m / torch.max(self.m) + self.num_classes = self.m.size(0) + + def forward(self, input: torch.Tensor, target: torch.Tensor, smooth: float = 1e-5) -> torch.Tensor: + """ + Args: + input: the shape should be BNH[WD]. + target: the shape should be BNH[WD]. + smooth: a small constant to avoid nan. + + """ + # Aggregate spatial dimensions + flat_input = input.view(input.size(0), input.size(1), -1) + flat_target = target.view(target.size(0), -1).long() + + # Apply the softmax to the input scores map + probs = F.softmax(flat_input, dim=1) + + # Compute the Wasserstein distance map + wass_dist_map = self.wasserstein_distance_map(probs, flat_target) + + # Compute the generalised number of true positives + alpha = self.compute_weights_generalized_true_positives(flat_target) + true_pos = self.compute_generalized_true_positive(alpha, flat_target, wass_dist_map) + denom = self.compute_denominator(alpha, flat_target, wass_dist_map) + + # Compute and return the final loss + wass_dice: torch.Tensor = (2.0 * true_pos + smooth) / (denom + smooth) + wass_dice_loss: torch.Tensor = 1.0 - wass_dice + return wass_dice_loss.mean() + + def wasserstein_distance_map(self, flat_proba: torch.Tensor, flat_target: torch.Tensor) -> torch.Tensor: + """ + Args: + flat_proba: the probabilities of input(predicted) tensor. + flat_target: the target tensor. + """ + # Turn the distance matrix to a map of identical matrix + m = torch.clone(self.m).to(flat_proba.device) + m_extended = torch.unsqueeze(m, dim=0) + m_extended = torch.unsqueeze(m_extended, dim=3) + m_extended = m_extended.expand((flat_proba.size(0), m_extended.size(1), m_extended.size(2), flat_proba.size(2))) + + # Expand the feature dimensions of the target + flat_target_extended = torch.unsqueeze(flat_target, dim=1) + flat_target_extended = flat_target_extended.expand( + (flat_target.size(0), m_extended.size(1), flat_target.size(1)) + ) + flat_target_extended = torch.unsqueeze(flat_target_extended, dim=1) + + # Extract the vector of class distances for the ground-truth label at each voxel + m_extended = torch.gather(m_extended, dim=1, index=flat_target_extended) + m_extended = torch.squeeze(m_extended, dim=1) + + # Compute the wasserstein distance map + wasserstein_map = m_extended * flat_proba + + # Sum over the classes + wasserstein_map = torch.sum(wasserstein_map, dim=1) + return wasserstein_map + + def compute_generalized_true_positive( + self, alpha: torch.Tensor, flat_target: torch.Tensor, wasserstein_distance_map: torch.Tensor + ) -> torch.Tensor: + """ + Args: + alpha: generalised number of true positives of target class. + flat_target: the target tensor. + wasserstein_distance_map: the map obtained from the above function. + """ + # Extend alpha to a map and select value at each voxel according to flat_target + alpha_extended = torch.unsqueeze(alpha, dim=2) + alpha_extended = alpha_extended.expand((flat_target.size(0), self.num_classes, flat_target.size(1))) + flat_target_extended = torch.unsqueeze(flat_target, dim=1) + alpha_extended = torch.gather(alpha_extended, index=flat_target_extended, dim=1) + + # Compute the generalized true positive as in eq. 9 + generalized_true_pos = torch.sum( + alpha_extended * (1.0 - wasserstein_distance_map), + dim=[1, 2], + ) + return generalized_true_pos + + def compute_denominator( + self, alpha: torch.Tensor, flat_target: torch.Tensor, wasserstein_distance_map: torch.Tensor + ) -> torch.Tensor: + """ + Args: + alpha: generalised number of true positives of target class. + flat_target: the target tensor. + wasserstein_distance_map: the map obtained from the above function. + """ + # Extend alpha to a map and select value at each voxel according to flat_target + alpha_extended = torch.unsqueeze(alpha, dim=2) + alpha_extended = alpha_extended.expand((flat_target.size(0), self.num_classes, flat_target.size(1))) + flat_target_extended = torch.unsqueeze(flat_target, dim=1) + alpha_extended = torch.gather(alpha_extended, index=flat_target_extended, dim=1) + + # Compute the generalized true positive as in eq. 9 + generalized_true_pos = torch.sum( + alpha_extended * (2.0 - wasserstein_distance_map), + dim=[1, 2], + ) + return generalized_true_pos + + def compute_weights_generalized_true_positives(self, flat_target: torch.Tensor) -> torch.Tensor: + """ + Args: + flat_target: the target tensor. + """ + one_hot = F.one_hot(flat_target, num_classes=self.num_classes).permute(0, 2, 1).float() + volumes = torch.sum(one_hot, dim=2) + alpha: torch.Tensor = 1.0 / (volumes + 1.0) + return alpha + + +dice = Dice = DiceLoss +generalized_dice = GeneralizedDiceLoss +generalized_wasserstein_dice = GeneralizedWassersteinDiceLoss diff --git a/testbed/Project-MONAI__MONAI/monai/losses/focal_loss.py b/testbed/Project-MONAI__MONAI/monai/losses/focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..59b892d18fcc4ae1b821d17c0ed0820c8264a13e --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/losses/focal_loss.py @@ -0,0 +1,136 @@ +# Copyright 2020 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 typing import Optional, Union + +import torch +import torch.nn.functional as F +from torch.nn.modules.loss import _WeightedLoss + +from monai.utils import LossReduction + + +class FocalLoss(_WeightedLoss): + """ + Reimplementation of the Focal Loss described in: + + - "Focal Loss for Dense Object Detection", T. Lin et al., ICCV 2017 + - "AnatomyNet: Deep learning for fast and fully automated whole‐volume segmentation of head and neck anatomy", + Zhu et al., Medical Physics 2018 + """ + + def __init__( + self, + gamma: float = 2.0, + weight: Optional[torch.Tensor] = None, + reduction: Union[LossReduction, str] = LossReduction.MEAN, + ) -> None: + """ + Args: + gamma: value of the exponent gamma in the definition of the Focal loss. + weight: weights to apply to the voxels of each class. If None no weights are applied. + This corresponds to the weights `\alpha` in [1]. + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + + Example: + .. code-block:: python + + import torch + from monai.losses import FocalLoss + + pred = torch.tensor([[1, 0], [0, 1], [1, 0]], dtype=torch.float32) + grnd = torch.tensor([[0], [1], [0]], dtype=torch.int64) + fl = FocalLoss() + fl(pred, grnd) + + """ + super(FocalLoss, self).__init__(weight=weight, reduction=LossReduction(reduction).value) + self.gamma = gamma + self.weight: Optional[torch.Tensor] + + def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """ + Args: + input: the shape should be BCH[WD]. + where C is the number of classes. + target: the shape should be B1H[WD] or BCH[WD]. + If the target's shape is B1H[WD], the target that this loss expects should be a class index + in the range [0, C-1] where C is the number of classes. + + Raises: + ValueError: When ``target`` ndim differs from ``input``. + ValueError: When ``target`` channel is not 1 and ``target`` shape differs from ``input``. + ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. + + """ + i = input + t = target + + if i.ndimension() != t.ndimension(): + raise ValueError(f"input and target ndim must match, got input={i.ndimension()} target={t.ndimension()}.") + + if target.shape[1] != 1 and target.shape[1] != i.shape[1]: + raise ValueError( + "target must have one channel or have the same shape as the input. " + "If it has one channel, it should be a class index in the range [0, C-1] " + f"where C is the number of classes inferred from 'input': C={i.shape[1]}. " + ) + # Change the shape of input and target to + # num_batch x num_class x num_voxels. + if input.dim() > 2: + i = i.view(i.size(0), i.size(1), -1) # N,C,H,W => N,C,H*W + t = t.view(t.size(0), t.size(1), -1) # N,1,H,W => N,1,H*W or N,C,H*W + else: # Compatibility with classification. + i = i.unsqueeze(2) # N,C => N,C,1 + t = t.unsqueeze(2) # N,1 => N,1,1 or N,C,1 + + # Compute the log proba (more stable numerically than softmax). + logpt = F.log_softmax(i, dim=1) # N,C,H*W + # Keep only log proba values of the ground truth class for each voxel. + if target.shape[1] == 1: + logpt = logpt.gather(1, t.long()) # N,C,H*W => N,1,H*W + logpt = torch.squeeze(logpt, dim=1) # N,1,H*W => N,H*W + + # Get the proba + pt = torch.exp(logpt) # N,H*W or N,C,H*W + + if self.weight is not None: + self.weight = self.weight.to(i) + # Convert the weight to a map in which each voxel + # has the weight associated with the ground-truth label + # associated with this voxel in target. + at = self.weight[None, :, None] # C => 1,C,1 + at = at.expand((t.size(0), -1, t.size(2))) # 1,C,1 => N,C,H*W + if target.shape[1] == 1: + at = at.gather(1, t.long()) # selection of the weights => N,1,H*W + at = torch.squeeze(at, dim=1) # N,1,H*W => N,H*W + # Multiply the log proba by their weights. + logpt = logpt * at + + # Compute the loss mini-batch. + weight = torch.pow(-pt + 1.0, self.gamma) + if target.shape[1] == 1: + loss = torch.mean(-weight * logpt, dim=1) # N + else: + loss = torch.mean(-weight * t * logpt, dim=-1) # N,C + + if self.reduction == LossReduction.SUM.value: + return loss.sum() + if self.reduction == LossReduction.NONE.value: + return loss + if self.reduction == LossReduction.MEAN.value: + return loss.mean() + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') diff --git a/testbed/Project-MONAI__MONAI/monai/losses/tversky.py b/testbed/Project-MONAI__MONAI/monai/losses/tversky.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9b28f1d2262cde97d9648108d1f6a6c3a91a94 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/losses/tversky.py @@ -0,0 +1,149 @@ +# Copyright 2020 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. + +import warnings +from typing import Callable, Optional, Union + +import torch +from torch.nn.modules.loss import _Loss + +from monai.networks import one_hot +from monai.utils import LossReduction + + +class TverskyLoss(_Loss): + + """ + Compute the Tversky loss defined in: + + Sadegh et al. (2017) Tversky loss function for image segmentation + using 3D fully convolutional deep networks. (https://arxiv.org/abs/1706.05721) + + Adapted from: + https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/layer/loss_segmentation.py#L631 + + """ + + def __init__( + self, + include_background: bool = True, + to_onehot_y: bool = False, + sigmoid: bool = False, + softmax: bool = False, + other_act: Optional[Callable] = None, + alpha: float = 0.5, + beta: float = 0.5, + reduction: Union[LossReduction, str] = LossReduction.MEAN, + ) -> None: + """ + Args: + include_background: If False channel index 0 (background category) is excluded from the calculation. + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + sigmoid: If True, apply a sigmoid function to the prediction. + softmax: If True, apply a softmax function to the prediction. + other_act: if don't want to use `sigmoid` or `softmax`, use other callable function to execute + other activation layers, Defaults to ``None``. for example: + `other_act = torch.tanh`. + alpha: weight of false positives + beta: weight of false negatives + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + + Raises: + TypeError: When ``other_act`` is not an ``Optional[Callable]``. + ValueError: When more than 1 of [``sigmoid=True``, ``softmax=True``, ``other_act is not None``]. + Incompatible values. + + """ + + super().__init__(reduction=LossReduction(reduction).value) + if other_act is not None and not callable(other_act): + raise TypeError(f"other_act must be None or callable but is {type(other_act).__name__}.") + if int(sigmoid) + int(softmax) + int(other_act is not None) > 1: + raise ValueError("Incompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None].") + self.include_background = include_background + self.to_onehot_y = to_onehot_y + self.sigmoid = sigmoid + self.softmax = softmax + self.other_act = other_act + self.alpha = alpha + self.beta = beta + + def forward(self, input: torch.Tensor, target: torch.Tensor, smooth: float = 1e-5) -> torch.Tensor: + """ + Args: + input: the shape should be BNH[WD]. + target: the shape should be BNH[WD]. + smooth: a small constant to avoid nan. + + Raises: + ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. + + """ + if self.sigmoid: + input = torch.sigmoid(input) + + n_pred_ch = input.shape[1] + if self.softmax: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `softmax=True` ignored.") + else: + input = torch.softmax(input, 1) + + if self.other_act is not None: + input = self.other_act(input) + + if self.to_onehot_y: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `to_onehot_y=True` ignored.") + else: + target = one_hot(target, num_classes=n_pred_ch) + + if not self.include_background: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `include_background=False` ignored.") + else: + # if skipping background, removing first channel + target = target[:, 1:] + input = input[:, 1:] + + assert ( + target.shape == input.shape + ), f"ground truth has differing shape ({target.shape}) from input ({input.shape})" + + p0 = input + p1 = 1 - p0 + g0 = target + g1 = 1 - g0 + + # reducing only spatial dimensions (not batch nor channels) + reduce_axis = list(range(2, len(input.shape))) + + tp = torch.sum(p0 * g0, reduce_axis) + fp = self.alpha * torch.sum(p0 * g1, reduce_axis) + fn = self.beta * torch.sum(p1 * g0, reduce_axis) + + numerator = tp + smooth + denominator = tp + fp + fn + smooth + + score: torch.Tensor = 1.0 - numerator / denominator + + if self.reduction == LossReduction.SUM.value: + return torch.sum(score) # sum over the batch and channel dims + if self.reduction == LossReduction.NONE.value: + return score # returns [N, n_classes] losses + if self.reduction == LossReduction.MEAN.value: + return torch.mean(score) + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') diff --git a/testbed/Project-MONAI__MONAI/monai/metrics/__init__.py b/testbed/Project-MONAI__MONAI/monai/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8a0043d6788281176cfe27085746ff57c812ffda --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/metrics/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2020 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 .confusion_matrix import compute_confusion_metric +from .confusion_matrix_utils import * +from .meandice import DiceMetric, compute_meandice +from .rocauc import compute_roc_auc diff --git a/testbed/Project-MONAI__MONAI/monai/metrics/confusion_matrix.py b/testbed/Project-MONAI__MONAI/monai/metrics/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..1721b3938c00b89f466f4c95e3bf642fbf19ceb3 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/metrics/confusion_matrix.py @@ -0,0 +1,107 @@ +# Copyright 2020 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 typing import Callable, List, Optional, Sequence, Union + +import numpy as np +import torch + +from monai.metrics.confusion_matrix_utils import * +from monai.networks import one_hot +from monai.utils import Average + + +def compute_confusion_metric( + y_pred: torch.Tensor, + y: torch.Tensor, + to_onehot_y: bool = False, + activation: Optional[Union[str, Callable]] = None, + bin_mode: Optional[str] = "threshold", + bin_threshold: Union[float, Sequence[float]] = 0.5, + metric_name: str = "hit_rate", + average: Union[Average, str] = Average.MACRO, + zero_division: int = 0, +) -> Union[np.ndarray, List[float], float]: + """ + Compute confusion matrix related metrics. This function supports to calcuate all metrics + mentioned in: `Confusion matrix `_. + Before calculating, an activation function and/or a binarization manipulation can be employed + to pre-process the original inputs. Zero division is handled by replacing the result into a + single value. Referring to: + `sklearn.metrics `_. + + Args: + y_pred: predictions. As for classification tasks, + `y_pred` should has the shape [B] or [BN]. As for segmentation tasks, + the shape should be [BNHW] or [BNHWD]. + y: ground truth, the first dim is batch. + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + activation: [``"sigmoid"``, ``"softmax"``] + Activation method, if specified, an activation function will be employed for `y_pred`. + Defaults to None. + The parameter can also be a callable function, for example: + ``activation = lambda x: torch.log_softmax(x)``. + bin_mode: [``"threshold"``, ``"mutually_exclusive"``] + Binarization method, if specified, a binarization manipulation will be employed + for `y_pred`. + + - ``"threshold"``, a single threshold or a sequence of thresholds should be set. + - ``"mutually_exclusive"``, `y_pred` will be converted by a combination of `argmax` and `to_onehot`. + bin_threshold: the threshold for binarization, can be a single value or a sequence of + values that each one of the value represents a threshold for a class. + metric_name: [``"sensitivity"``, ``"specificity"``, ``"precision"``, ``"negative predictive value"``, + ``"miss rate"``, ``"fall out"``, ``"false discovery rate"``, ``"false omission rate"``, + ``"prevalence threshold"``, ``"threat score"``, ``"accuracy"``, ``"balanced accuracy"``, + ``"f1 score"``, ``"matthews correlation coefficient"``, ``"fowlkes mallows index"``, + ``"informedness"``, ``"markedness"``] + Some of the metrics have multiple aliases (as shown in the wikipedia page aforementioned), + and you can also input those names instead. + average: [``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``] + Type of averaging performed if not binary classification. + Defaults to ``"macro"``. + + - ``"macro"``: calculate metrics for each label, and find their unweighted mean. + This does not take label imbalance into account. + - ``"weighted"``: calculate metrics for each label, and find their average, + weighted by support (the number of true instances for each label). + - ``"micro"``: calculate metrics globally by considering each element of the label + indicator matrix as a label. + - ``"none"``: the scores for each class are returned. + zero_division: the value to return when there is a zero division, for example, when all + predictions and labels are negative. Defaults to 0. + Raises: + AssertionError: when data shapes of `y_pred` and `y` do not match. + AssertionError: when specify activation function and ``mutually_exclusive`` mode at the same time. + """ + + y_pred_ndim, y_ndim = y_pred.ndimension(), y.ndimension() + # one-hot for ground truth + if to_onehot_y: + if y_pred_ndim == 1: + warnings.warn("y_pred has only one channel, to_onehot_y=True ignored.") + else: + n_classes = y_pred.shape[1] + y = one_hot(y, num_classes=n_classes) + # check shape + assert y.shape == y_pred.shape, "data shapes of y_pred and y do not match." + # activation for predictions + if activation is not None: + assert bin_mode != "mutually_exclusive", "activation is unnecessary for mutually exclusive classes." + y_pred = do_activation(y_pred, activation=activation) + # binarization for predictions + if bin_mode is not None: + y_pred = do_binarization(y_pred, bin_mode=bin_mode, bin_threshold=bin_threshold) + # get confusion matrix elements + con_list = cal_confusion_matrix_elements(y_pred, y) + # get simplified metric name + metric_name = check_metric_name_and_unify(metric_name) + result = do_calculate_metric(con_list, metric_name, average=average, zero_division=zero_division) + return result diff --git a/testbed/Project-MONAI__MONAI/monai/metrics/confusion_matrix_utils.py b/testbed/Project-MONAI__MONAI/monai/metrics/confusion_matrix_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3d85b474dd6e69536e44e1fa25b8791dda6196 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/metrics/confusion_matrix_utils.py @@ -0,0 +1,309 @@ +# Copyright 2020 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. + +import warnings +from typing import Callable, List, Optional, Sequence, Union + +import numpy as np +import torch + +from monai.networks import one_hot +from monai.utils import Average + + +def do_activation(input_data: torch.Tensor, activation: Union[str, Callable] = "softmax") -> torch.Tensor: + """ + This function is used to do activation for inputs. + + Args: + input_data: the input that to be acitvated, in the shape [B] or [BN] or [BNHW] or [BNHWD]. + activation: can be ``"sigmoid"`` or ``"softmax"``, or a callable function. Defaults to ``"softmax"``. + An example for callable function: ``activation = lambda x: torch.log_softmax(x)``. + + Raises: + NotImplementedError: When input an activation name that is not implemented. + """ + input_ndim = input_data.ndimension() + if activation == "softmax": + if input_ndim == 1: + warnings.warn("input_data has only one channel, softmax ignored.") + else: + input_data = input_data.float().softmax(dim=1) + elif activation == "sigmoid": + input_data = input_data.float().sigmoid() + elif callable(activation): + input_data = activation(input_data) + else: + raise NotImplementedError("activation can only be sigmoid, softmax or a callable function.") + return input_data + + +def do_binarization( + input_data: torch.Tensor, + bin_mode: str = "threshold", + bin_threshold: Union[float, Sequence[float]] = 0.5, +) -> torch.Tensor: + """ + Args: + input_data: the input that to be binarized, in the shape [B] or [BN] or [BNHW] or [BNHWD]. + bin_mode: can be ``"threshold"`` or ``"mutually_exclusive"``, or a callable function. + - ``"threshold"``, a single threshold or a sequence of thresholds should be set. + - ``"mutually_exclusive"``, `input_data` will be converted by a combination of + argmax and to_onehot. + bin_threshold: the threshold to binarize the input data, can be a single value or a sequence of + values that each one of the value represents a threshold for a class. + + Raises: + AssertionError: when `bin_threshold` is a sequence and the input has the shape [B]. + AssertionError: when `bin_threshold` is a sequence but the length != the number of classes. + AssertionError: when `bin_mode` is ``"mutually_exclusive"`` the input has the shape [B]. + AssertionError: when `bin_mode` is ``"mutually_exclusive"`` the input has the shape [B, 1]. + """ + input_ndim = input_data.ndimension() + if bin_mode == "threshold": + if isinstance(bin_threshold, Sequence): + assert input_ndim > 1, "a sequence of thresholds are used for multi-class tasks." + error_hint = "the length of the sequence should be the same as the number of classes." + assert input_data.shape[1] == len(bin_threshold), "{}".format(error_hint) + for cls_num in range(input_data.shape[1]): + input_data[:, cls_num] = (input_data[:, cls_num] > bin_threshold[cls_num]).float() + else: + input_data = (input_data > bin_threshold).float() + elif bin_mode == "mutually_exclusive": + assert input_ndim > 1, "mutually_exclusive is used for multi-class tasks." + n_classes = input_data.shape[1] + assert n_classes > 1, "mutually_exclusive is used for multi-class tasks." + input_data = torch.argmax(input_data, dim=1, keepdim=True) + input_data = one_hot(input_data, num_classes=n_classes) + return input_data + + +def cal_confusion_matrix_elements(p: torch.Tensor, t: torch.Tensor) -> List[np.ndarray]: + """ + This function is used to calculate the number of true positives (tp), true negatives(tn), + false positives (fp), false negatives (fn), total positives and total negatives, and + return a list of these values. + + Args: + p: predictions, a binarized torch.Tensor that its first dimension represents the batch size. + t: ground truth, a binarized torch.Tensor that its first dimension represents the batch size. + parameter t and p should have same shapes. + + Notes: + If the input shape is [B], each element in the returned list is an int value. + Else, each element in the returned list is an np.ndarray with shape (N,), where each element in + this array represents the value for the corresponding class. + + Raises: + AssertionError: when `p` and `t` have different shapes. + """ + assert p.shape == t.shape, "predictions and targets should have same shapes." + with torch.no_grad(): + dims = p.ndimension() + if dims > 1: # in the form of [BNS], where S is the number of pixels for one sample. + batch_size, n_class = p.shape[:2] + p = p.view(batch_size, n_class, -1) + t = t.view(batch_size, n_class, -1) + tp = ((p + t) == 2).float() + tn = ((p + t) == 0).float() + if dims > 1: + tp = tp.sum(dim=[0, 2]) + tn = tn.sum(dim=[0, 2]) + total_p = t.sum(dim=[0, 2]) + total_n = batch_size * t.shape[-1] - total_p + else: + tp, tn = tp.sum(), tn.sum() + total_p = t.sum() + total_n = t.shape[-1] - total_p + fn = total_p - tp + fp = total_n - tn + result = [tp, tn, fp, fn, total_p, total_n] + result = [l.data.cpu().numpy() for l in result] + return result + + +def handle_zero_divide( + numerator: Union[np.ndarray, torch.Tensor, float, int], + denominator: Union[np.ndarray, torch.Tensor, float, int], + zero_division: int = 0, +) -> Union[np.ndarray, torch.Tensor, float]: + """ + This function is used to handle the division case that the denominator has 0. + This function takes sklearn for reference, see: + https://github.com/scikit-learn/scikit-learn/blob/0fb307bf3/sklearn/metrics/_classification.py#L1179 + """ + if isinstance(denominator, (float, int)): + if denominator != 0: + return numerator / denominator + else: + return zero_division + else: + mask = denominator == 0.0 + denominator[mask] = 1 + result = numerator / denominator + if not mask.any(): + return result + else: + result[mask] = zero_division + return result + + +def do_calculate_metric( + confusion_ele_list: List[np.ndarray], + metric_name: str, + average: Union[Average, str] = "none", + zero_division: int = 0, +): + """ + Args: + confusion_ele_list: the returned result of function ``cal_confusion_matrix_elements``. + metric_name: the simplified metric name from function ``check_metric_name_and_unify``. + average: type of averaging performed if not binary classification. + Defaults to ``"macro"``. + - ``"macro"``: calculate metrics for each label, and find their unweighted mean. + This does not take label imbalance into account. + - ``"weighted"``: calculate metrics for each label, and find their average + weighted by support (the number of true instances for each label). + - ``"micro"``: calculate metrics globally by considering each element of the label + indicator matrix as a label. + - ``"none"``: the scores for each class are returned. + zero_division: the value to return when there is a zero division, for example, when all + predictions and labels are negative. Defaults to 0. + """ + ele_list: List[Union[np.ndarray, int, float]] + metric = metric_name + div_0 = zero_division + # pre-process average + average = Average(average) + bin_flag: bool + if len(confusion_ele_list[0].shape) == 0: + bin_flag = True + average = Average.NONE # for binary tasks, other average methods are meaningless. + ele_list = [int(l) for l in confusion_ele_list] + else: + bin_flag = False + if average == Average.MICRO: + ele_list = [int(l.sum()) for l in confusion_ele_list] + else: + ele_list = confusion_ele_list + tp, tn, fp, fn, p, n = ele_list + # calculate + numerator: Union[np.ndarray, int, float] + denominator: Union[np.ndarray, int, float] + if metric == "tpr": + numerator, denominator = tp, p + elif metric == "tnr": + numerator, denominator = tn, n + elif metric == "ppv": + numerator, denominator = tp, (tp + fp) + elif metric == "npv": + numerator, denominator = tn, (tn + fn) + elif metric == "fnr": + numerator, denominator = fn, p + elif metric == "fpr": + numerator, denominator = fp, n + elif metric == "fdr": + numerator, denominator = fp, (fp + tp) + elif metric == "for": + numerator, denominator = fn, (fn + tn) + elif metric == "pt": + tpr = handle_zero_divide(tp, p, div_0) + tnr = handle_zero_divide(tn, n, div_0) + numerator = np.sqrt(tpr * (1 - tnr)) + tnr - 1 + denominator = tpr + tnr - 1 + elif metric == "ts": + numerator, denominator = tp, (tp + fn + fp) + elif metric == "acc": + numerator, denominator = (tp + tp), (p + n) + elif metric == "ba": + tpr = handle_zero_divide(tp, p, div_0) + tnr = handle_zero_divide(tn, n, div_0) + numerator, denominator = (tpr + tnr), 2 + elif metric == "f1": + numerator, denominator = tp * 2, (tp * 2 + fn + fp) + elif metric == "mcc": + numerator = tp * tn - fp * fn + denominator = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) + elif metric == "fm": + tpr = handle_zero_divide(tp, p, div_0) + ppv = handle_zero_divide(tp, (tp + fp), div_0) + numerator = np.sqrt(ppv * tpr) + denominator = 1 + elif metric == "bm": + tpr = handle_zero_divide(tp, p, div_0) + tnr = handle_zero_divide(tn, n, div_0) + numerator = tpr + tnr - 1 + denominator = 1 + elif metric == "mk": + ppv = handle_zero_divide(tp, (tp + fp), div_0) + npv = handle_zero_divide(tn, (tn + fn), div_0) + numerator = ppv + npv - 1 + denominator = 1 + else: + raise NotImplementedError("the metric is not implemented.") + result = handle_zero_divide(numerator, denominator, div_0) + + if average == Average.MICRO or average == Average.NONE: + return result + + weights: Optional[np.ndarray] + if average == Average.MACRO: + weights = None + elif average == Average.WEIGHTED: + weights = p + result = np.average(result, weights=weights) + return result + + +def check_metric_name_and_unify(metric_name: str): + """ + There are many metrics related to confusion matrix, and some of the metrics have + more than one names. In addition, some of the names are very long. + Therefore, this function is used to simplify the implementaton. + """ + metric_name = metric_name.replace(" ", "_") + metric_name = metric_name.lower() + if metric_name in ["sensitivity", "recall", "hit_rate", "true_positive_rate", "tpr"]: + return "tpr" + elif metric_name in ["specificity", "selectivity", "true_negative_rate", "tnr"]: + return "tnr" + elif metric_name in ["precision", "positive_predictive_value", "ppv"]: + return "ppv" + elif metric_name in ["negative_predictive_value", "npv"]: + return "npv" + elif metric_name in ["miss_rate", "false_negative_rate", "fnr"]: + return "fnr" + elif metric_name in ["fall_out", "false_positive_rate", "fpr"]: + return "fpr" + elif metric_name in ["false_discovery_rate", "fdr"]: + return "fdr" + elif metric_name in ["false_omission_rate", "for"]: + return "for" + elif metric_name in ["prevalence_threshold", "pt"]: + return "pt" + elif metric_name in ["threat_score", "critical_success_index", "ts", "csi"]: + return "ts" + elif metric_name in ["accuracy", "acc"]: + return "acc" + elif metric_name in ["balanced_accuracy", "ba"]: + return "ba" + elif metric_name in ["f1_score", "f1"]: + return "f1" + elif metric_name in ["matthews_correlation_coefficient", "mcc"]: + return "mcc" + elif metric_name in ["fowlkes_mallows_index", "fm"]: + return "fm" + elif metric_name in ["informedness", "bookmaker_informedness", "bm"]: + return "bm" + elif metric_name in ["markedness", "deltap", "mk"]: + return "mk" + else: + raise NotImplementedError("the metric is not implemented.") diff --git a/testbed/Project-MONAI__MONAI/monai/metrics/meandice.py b/testbed/Project-MONAI__MONAI/monai/metrics/meandice.py new file mode 100644 index 0000000000000000000000000000000000000000..f51a686d05cd1d6515929021f4ec9edcf9c5acff --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/metrics/meandice.py @@ -0,0 +1,245 @@ +# Copyright 2020 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. + +import warnings +from typing import Callable, Optional, Union + +import torch + +from monai.networks import one_hot +from monai.utils import MetricReduction + + +class DiceMetric: + """ + Compute average Dice loss between two tensors. It can support both multi-classes and multi-labels tasks. + Input logits `y_pred` (BNHW[D] where N is number of classes) is compared with ground truth `y` (BNHW[D]). + Axis N of `y_preds` is expected to have logit predictions for each class rather than being image channels, + while the same axis of `y` can be 1 or N (one-hot format). The `include_background` class attribute can be + set to False for an instance of DiceLoss to exclude the first category (channel index 0) which is by + convention assumed to be background. If the non-background segmentations are small compared to the total + image size they can get overwhelmed by the signal from the background so excluding it in such cases helps + convergence. + + Args: + include_background: whether to skip Dice computation on the first channel of + the predicted output. Defaults to True. + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + mutually_exclusive: if True, `y_pred` will be converted into a binary matrix using + a combination of argmax and to_onehot. Defaults to False. + sigmoid: whether to add sigmoid function to y_pred before computation. Defaults to False. + other_act: callable function to replace `sigmoid` as activation layer if needed, Defaults to ``None``. + for example: `other_act = torch.tanh`. + logit_thresh: the threshold value used to convert (for example, after sigmoid if `sigmoid=True`) + `y_pred` into a binary matrix. Defaults to 0.5. + reduction: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``} + Define the mode to reduce computation result of 1 batch data. Defaults to ``"mean"``. + + Raises: + ValueError: When ``sigmoid=True`` and ``other_act is not None``. Incompatible values. + + """ + + def __init__( + self, + include_background: bool = True, + to_onehot_y: bool = False, + mutually_exclusive: bool = False, + sigmoid: bool = False, + other_act: Optional[Callable] = None, + logit_thresh: float = 0.5, + reduction: Union[MetricReduction, str] = MetricReduction.MEAN, + ) -> None: + super().__init__() + if sigmoid and other_act is not None: + raise ValueError("Incompatible values: ``sigmoid=True`` and ``other_act is not None``.") + self.include_background = include_background + self.to_onehot_y = to_onehot_y + self.mutually_exclusive = mutually_exclusive + self.sigmoid = sigmoid + self.other_act = other_act + self.logit_thresh = logit_thresh + self.reduction: MetricReduction = MetricReduction(reduction) + + self.not_nans: Optional[torch.Tensor] = None # keep track for valid elements in the batch + + def __call__(self, y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """ + Args: + y_pred: input data to compute, typical segmentation model output. + it must be one-hot format and first dim is batch. + y: ground truth to compute mean dice metric, the first dim is batch. + + Raises: + ValueError: When ``self.reduction`` is not one of + ["mean", "sum", "mean_batch", "sum_batch", "mean_channel", "sum_channel" "none"]. + + """ + + # compute dice (BxC) for each channel for each batch + f = compute_meandice( + y_pred=y_pred, + y=y, + include_background=self.include_background, + to_onehot_y=self.to_onehot_y, + mutually_exclusive=self.mutually_exclusive, + sigmoid=self.sigmoid, + other_act=self.other_act, + logit_thresh=self.logit_thresh, + ) + + # some dice elements might be Nan (if ground truth y was missing (zeros)) + # we need to account for it + + nans = torch.isnan(f) + not_nans = (~nans).float() + f[nans] = 0 + + t_zero = torch.zeros(1, device=f.device, dtype=torch.float) + + if self.reduction == MetricReduction.MEAN: + # 2 steps, first, mean by channel (accounting for nans), then by batch + + not_nans = not_nans.sum(dim=1) + f = torch.where(not_nans > 0, f.sum(dim=1) / not_nans, t_zero) # channel average + + not_nans = (not_nans > 0).float().sum() + f = torch.where(not_nans > 0, f.sum() / not_nans, t_zero) # batch average + + elif self.reduction == MetricReduction.SUM: + not_nans = not_nans.sum() + f = torch.sum(f) # sum over the batch and channel dims + elif self.reduction == MetricReduction.MEAN_BATCH: + not_nans = not_nans.sum(dim=0) + f = torch.where(not_nans > 0, f.sum(dim=0) / not_nans, t_zero) # batch average + elif self.reduction == MetricReduction.SUM_BATCH: + not_nans = not_nans.sum(dim=0) + f = f.sum(dim=0) # the batch sum + elif self.reduction == MetricReduction.MEAN_CHANNEL: + not_nans = not_nans.sum(dim=1) + f = torch.where(not_nans > 0, f.sum(dim=1) / not_nans, t_zero) # channel average + elif self.reduction == MetricReduction.SUM_CHANNEL: + not_nans = not_nans.sum(dim=1) + f = f.sum(dim=1) # the channel sum + elif self.reduction == MetricReduction.NONE: + pass + else: + raise ValueError( + f"Unsupported reduction: {self.reduction}, available options are " + '["mean", "sum", "mean_batch", "sum_batch", "mean_channel", "sum_channel" "none"].' + ) + + # save not_nans since we may need it later to know how many elements were valid + self.not_nans = not_nans + + return f + + +def compute_meandice( + y_pred: torch.Tensor, + y: torch.Tensor, + include_background: bool = True, + to_onehot_y: bool = False, + mutually_exclusive: bool = False, + sigmoid: bool = False, + other_act: Optional[Callable] = None, + logit_thresh: float = 0.5, +) -> torch.Tensor: + """Computes Dice score metric from full size Tensor and collects average. + + Args: + y_pred: input data to compute, typical segmentation model output. + it must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. + y: ground truth to compute mean dice metric, the first dim is batch. + example shape: [16, 1, 32, 32] will be converted into [16, 3, 32, 32]. + alternative shape: [16, 3, 32, 32] and set `to_onehot_y=False` to use 3-class labels directly. + include_background: whether to skip Dice computation on the first channel of + the predicted output. Defaults to True. + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + mutually_exclusive: if True, `y_pred` will be converted into a binary matrix using + a combination of argmax and to_onehot. Defaults to False. + sigmoid: whether to add sigmoid function to y_pred before computation. Defaults to False. + other_act: callable function to replace `sigmoid` as activation layer if needed, Defaults to ``None``. + for example: `other_act = torch.tanh`. + logit_thresh: the threshold value used to convert (for example, after sigmoid if `sigmoid=True`) + `y_pred` into a binary matrix. Defaults to 0.5. + + Raises: + ValueError: When ``sigmoid=True`` and ``other_act is not None``. Incompatible values. + TypeError: When ``other_act`` is not an ``Optional[Callable]``. + ValueError: When ``sigmoid=True`` and ``mutually_exclusive=True``. Incompatible values. + + Returns: + Dice scores per batch and per class, (shape [batch_size, n_classes]). + + Note: + This method provides two options to convert `y_pred` into a binary matrix + (1) when `mutually_exclusive` is True, it uses a combination of ``argmax`` and ``to_onehot``, + (2) when `mutually_exclusive` is False, it uses a threshold ``logit_thresh`` + (optionally with a ``sigmoid`` function before thresholding). + + """ + n_classes = y_pred.shape[1] + n_len = len(y_pred.shape) + if sigmoid and other_act is not None: + raise ValueError("Incompatible values: sigmoid=True and other_act is not None.") + if sigmoid: + y_pred = y_pred.float().sigmoid() + + if other_act is not None: + if not callable(other_act): + raise TypeError(f"other_act must be None or callable but is {type(other_act).__name__}.") + y_pred = other_act(y_pred) + + if n_classes == 1: + if mutually_exclusive: + warnings.warn("y_pred has only one class, mutually_exclusive=True ignored.") + if to_onehot_y: + warnings.warn("y_pred has only one channel, to_onehot_y=True ignored.") + if not include_background: + warnings.warn("y_pred has only one channel, include_background=False ignored.") + # make both y and y_pred binary + y_pred = (y_pred >= logit_thresh).float() + y = (y > 0).float() + else: # multi-channel y_pred + # make both y and y_pred binary + if mutually_exclusive: + if sigmoid: + raise ValueError("Incompatible values: sigmoid=True and mutually_exclusive=True.") + y_pred = torch.argmax(y_pred, dim=1, keepdim=True) + y_pred = one_hot(y_pred, num_classes=n_classes) + else: + y_pred = (y_pred >= logit_thresh).float() + if to_onehot_y: + y = one_hot(y, num_classes=n_classes) + + if not include_background: + y = y[:, 1:] if y.shape[1] > 1 else y + y_pred = y_pred[:, 1:] if y_pred.shape[1] > 1 else y_pred + + assert y.shape == y_pred.shape, "Ground truth one-hot has differing shape (%r) from source (%r)" % ( + y.shape, + y_pred.shape, + ) + y = y.float() + y_pred = y_pred.float() + + # reducing only spatial dimensions (not batch nor channels) + reduce_axis = list(range(2, n_len)) + intersection = torch.sum(y * y_pred, dim=reduce_axis) + + y_o = torch.sum(y, reduce_axis) + y_pred_o = torch.sum(y_pred, dim=reduce_axis) + denominator = y_o + y_pred_o + + f = torch.where(y_o > 0, (2.0 * intersection) / denominator, torch.tensor(float("nan"), device=y_o.device)) + return f # returns array of Dice shape: [batch, n_classes] diff --git a/testbed/Project-MONAI__MONAI/monai/metrics/rocauc.py b/testbed/Project-MONAI__MONAI/monai/metrics/rocauc.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c1cf20d21b51c087cd4fbc5026ebc7e3839538 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/metrics/rocauc.py @@ -0,0 +1,147 @@ +# Copyright 2020 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. + +import warnings +from typing import Callable, List, Optional, Union, cast + +import numpy as np +import torch + +from monai.networks import one_hot +from monai.utils import Average + + +def _calculate(y: torch.Tensor, y_pred: torch.Tensor) -> float: + assert y.ndimension() == y_pred.ndimension() == 1 and len(y) == len( + y_pred + ), "y and y_pred must be 1 dimension data with same length." + assert y.unique().equal( + torch.tensor([0, 1], dtype=y.dtype, device=y.device) + ), "y values must be 0 or 1, can not be all 0 or all 1." + n = len(y) + indices = y_pred.argsort() + y = y[indices].cpu().numpy() + y_pred = y_pred[indices].cpu().numpy() + nneg = auc = tmp_pos = tmp_neg = 0.0 + + for i in range(n): + y_i = cast(float, y[i]) + if i + 1 < n and y_pred[i] == y_pred[i + 1]: + tmp_pos += y_i + tmp_neg += 1 - y_i + continue + if tmp_pos + tmp_neg > 0: + tmp_pos += y_i + tmp_neg += 1 - y_i + nneg += tmp_neg + auc += tmp_pos * (nneg - tmp_neg / 2) + tmp_pos = tmp_neg = 0 + continue + if y_i == 1: + auc += nneg + else: + nneg += 1 + return auc / (nneg * (n - nneg)) + + +def compute_roc_auc( + y_pred: torch.Tensor, + y: torch.Tensor, + to_onehot_y: bool = False, + softmax: bool = False, + other_act: Optional[Callable] = None, + average: Union[Average, str] = Average.MACRO, +) -> Union[np.ndarray, List[float], float]: + """Computes Area Under the Receiver Operating Characteristic Curve (ROC AUC). Referring to: + `sklearn.metrics.roc_auc_score `_. + + Args: + y_pred: input data to compute, typical classification model output. + it must be One-Hot format and first dim is batch, example shape: [16] or [16, 2]. + y: ground truth to compute ROC AUC metric, the first dim is batch. + example shape: [16, 1] will be converted into [16, 2] (where `2` is inferred from `y_pred`). + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + softmax: whether to add softmax function to `y_pred` before computation. Defaults to False. + other_act: callable function to replace `softmax` as activation layer if needed, Defaults to ``None``. + for example: `other_act = lambda x: torch.log_softmax(x)`. + average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} + Type of averaging performed if not binary classification. + Defaults to ``"macro"``. + + - ``"macro"``: calculate metrics for each label, and find their unweighted mean. + This does not take label imbalance into account. + - ``"weighted"``: calculate metrics for each label, and find their average, + weighted by support (the number of true instances for each label). + - ``"micro"``: calculate metrics globally by considering each element of the label + indicator matrix as a label. + - ``"none"``: the scores for each class are returned. + + Raises: + ValueError: When ``y_pred`` dimension is not one of [1, 2]. + ValueError: When ``y`` dimension is not one of [1, 2]. + ValueError: When ``softmax=True`` and ``other_act is not None``. Incompatible values. + TypeError: When ``other_act`` is not an ``Optional[Callable]``. + ValueError: When ``average`` is not one of ["macro", "weighted", "micro", "none"]. + + Note: + ROCAUC expects y to be comprised of 0's and 1's. `y_pred` must be either prob. estimates or confidence values. + + """ + y_pred_ndim = y_pred.ndimension() + y_ndim = y.ndimension() + if y_pred_ndim not in (1, 2): + raise ValueError("Predictions should be of shape (batch_size, n_classes) or (batch_size, ).") + if y_ndim not in (1, 2): + raise ValueError("Targets should be of shape (batch_size, n_classes) or (batch_size, ).") + if y_pred_ndim == 2 and y_pred.shape[1] == 1: + y_pred = y_pred.squeeze(dim=-1) + y_pred_ndim = 1 + if y_ndim == 2 and y.shape[1] == 1: + y = y.squeeze(dim=-1) + + if y_pred_ndim == 1: + if to_onehot_y: + warnings.warn("y_pred has only one channel, to_onehot_y=True ignored.") + if softmax: + warnings.warn("y_pred has only one channel, softmax=True ignored.") + return _calculate(y, y_pred) + else: + n_classes = y_pred.shape[1] + if to_onehot_y: + y = one_hot(y, n_classes) + if softmax and other_act is not None: + raise ValueError("Incompatible values: softmax=True and other_act is not None.") + if softmax: + y_pred = y_pred.float().softmax(dim=1) + if other_act is not None: + if not callable(other_act): + raise TypeError(f"other_act must be None or callable but is {type(other_act).__name__}.") + y_pred = other_act(y_pred) + + assert y.shape == y_pred.shape, "data shapes of y_pred and y do not match." + + average = Average(average) + if average == Average.MICRO: + return _calculate(y.flatten(), y_pred.flatten()) + else: + y, y_pred = y.transpose(0, 1), y_pred.transpose(0, 1) + auc_values = [_calculate(y_, y_pred_) for y_, y_pred_ in zip(y, y_pred)] + if average == Average.NONE: + return auc_values + if average == Average.MACRO: + return np.mean(auc_values) + if average == Average.WEIGHTED: + weights = [sum(y_) for y_ in y] + return np.average(auc_values, weights=weights) + raise ValueError( + f'Unsupported average: {average}, available options are ["macro", "weighted", "micro", "none"].' + ) diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/__init__.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1740ae4df00cc905eea67e4fb7814853ffddf1dc --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2020 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 .aspp import SimpleASPP +from .convolutions import Convolution, ResidualUnit +from .downsample import MaxAvgPool +from .fcn import FCN, GCN, MCFCN, Refine +from .segresnet_block import ResBlock +from .squeeze_and_excitation import ( + ChannelSELayer, + ResidualSELayer, + SEBlock, + SEBottleneck, + SEResNetBottleneck, + SEResNeXtBottleneck, +) +from .upsample import SubpixelUpsample, UpSample diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/aspp.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/aspp.py new file mode 100644 index 0000000000000000000000000000000000000000..041ecd94b186fb71ee7eb320f08e03c7c390cff4 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/aspp.py @@ -0,0 +1,100 @@ +# Copyright 2020 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 typing import Sequence + +import torch +import torch.nn as nn + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.layers import same_padding +from monai.networks.layers.factories import Act, Conv, Norm + + +class SimpleASPP(nn.Module): + """ + A simplified version of the atrous spatial pyramid pooling (ASPP) module. + + Chen et al., Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation. + https://arxiv.org/abs/1802.02611 + + Wang et al., A Noise-robust Framework for Automatic Segmentation of COVID-19 Pneumonia Lesions + from CT Images. https://ieeexplore.ieee.org/document/9109297 + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + conv_out_channels: int, + kernel_sizes: Sequence[int] = (1, 3, 3, 3), + dilations: Sequence[int] = (1, 2, 4, 6), + norm_type=Norm.BATCH, + acti_type=Act.LEAKYRELU, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + conv_out_channels: number of output channels of each atrous conv. + The final number of output channels is conv_out_channels * len(kernel_sizes). + kernel_sizes: a sequence of four convolutional kernel sizes. + Defaults to (1, 3, 3, 3) for four (dilated) convolutions. + dilations: a sequence of four convolutional dilation parameters. + Defaults to (1, 2, 4, 6) for four (dilated) convolutions. + norm_type: final kernel-size-one convolution normalization type. + Defaults to batch norm. + acti_type: final kernel-size-one convolution activation type. + Defaults to leaky ReLU. + + Raises: + ValueError: When ``kernel_sizes`` length differs from ``dilations``. + + See also: + + :py:class:`monai.networks.layers.Act` + :py:class:`monai.networks.layers.Conv` + :py:class:`monai.networks.layers.Norm` + + """ + super().__init__() + if len(kernel_sizes) != len(dilations): + raise ValueError( + "kernel_sizes and dilations length must match, " + f"got kernel_sizes={len(kernel_sizes)} dilations={len(dilations)}." + ) + pads = tuple(same_padding(k, d) for k, d in zip(kernel_sizes, dilations)) + + self.convs = nn.ModuleList() + for k, d, p in zip(kernel_sizes, dilations, pads): + _conv = Conv[Conv.CONV, spatial_dims]( + in_channels=in_channels, out_channels=conv_out_channels, kernel_size=k, dilation=d, padding=p + ) + self.convs.append(_conv) + + out_channels = conv_out_channels * len(pads) # final conv. output channels + self.conv_k1 = Convolution( + dimensions=spatial_dims, + in_channels=out_channels, + out_channels=out_channels, + kernel_size=1, + act=acti_type, + norm=norm_type, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, channel, spatial_1[, spatial_2, ...]). + """ + x_out = torch.cat([conv(x) for conv in self.convs], dim=1) + x_out = self.conv_k1(x_out) + return x_out diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/convolutions.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/convolutions.py new file mode 100644 index 0000000000000000000000000000000000000000..523af87ead8dd1139cd411cfc2890d23f138f789 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/convolutions.py @@ -0,0 +1,249 @@ +# Copyright 2020 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 typing import Optional, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn + +from monai.networks.layers.convutils import same_padding +from monai.networks.layers.factories import Act, Conv, Dropout, Norm, split_args + + +class Convolution(nn.Sequential): + """ + Constructs a convolution with normalization, optional dropout, and optional activation layers:: + + -- (Conv|ConvTrans) -- Norm -- (Dropout) -- (Acti) -- + + if ``conv_only`` set to ``True``:: + + -- (Conv|ConvTrans) -- + + Args: + dimensions: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + strides: convolution stride. Defaults to 1. + kernel_size: convolution kernel size. Defaults to 3. + act: activation type and arguments. Defaults to PReLU. + norm: feature normalization type and arguments. Defaults to instance norm. + dropout: dropout ratio. Defaults to no dropout. + dropout_dim: determine the dimensions of dropout. Defaults to 1. + When dropout_dim = 1, randomly zeroes some of the elements for each channel. + When dropout_dim = 2, Randomly zeroes out entire channels (a channel is a 2D feature map). + When dropout_dim = 3, Randomly zeroes out entire channels (a channel is a 3D feature map). + The value of dropout_dim should be no no larger than the value of dimensions. + dilation: dilation rate. Defaults to 1. + groups: controls the connections between inputs and outputs. Defaults to 1. + bias: whether to have a bias term. Defaults to True. + conv_only: whether to use the convolutional layer only. Defaults to False. + is_transposed: if True uses ConvTrans instead of Conv. Defaults to False. + + See also: + + :py:class:`monai.networks.layers.Conv` + :py:class:`monai.networks.layers.Dropout` + :py:class:`monai.networks.layers.Act` + :py:class:`monai.networks.layers.Norm` + :py:class:`monai.networks.layers.split_args` + + """ + + def __init__( + self, + dimensions: int, + in_channels: int, + out_channels: int, + strides: int = 1, + kernel_size: Union[Sequence[int], int] = 3, + act: Optional[Union[Tuple, str]] = Act.PRELU, + norm: Union[Tuple, str] = Norm.INSTANCE, + dropout: Optional[Union[Tuple, str, float]] = None, + dropout_dim: int = 1, + dilation: Union[Sequence[int], int] = 1, + groups: int = 1, + bias: bool = True, + conv_only: bool = False, + is_transposed: bool = False, + ) -> None: + super().__init__() + self.dimensions = dimensions + self.in_channels = in_channels + self.out_channels = out_channels + self.is_transposed = is_transposed + + padding = same_padding(kernel_size, dilation) + conv_type = Conv[Conv.CONVTRANS if is_transposed else Conv.CONV, dimensions] + + # define the normalisation type and the arguments to the constructor + if norm is not None: + norm_name, norm_args = split_args(norm) + norm_type = Norm[norm_name, dimensions] + else: + norm_type = norm_args = None + + # define the activation type and the arguments to the constructor + if act is not None: + act_name, act_args = split_args(act) + act_type = Act[act_name] + else: + act_type = act_args = None + + if dropout: + # if dropout was specified simply as a p value, use default name and make a keyword map with the value + if isinstance(dropout, (int, float)): + drop_name = Dropout.DROPOUT + drop_args = {"p": dropout} + else: + drop_name, drop_args = split_args(dropout) + + if dropout_dim > dimensions: + raise ValueError( + f"dropout_dim should be no larger than dimensions, got dropout_dim={dropout_dim} and dimensions={dimensions}." + ) + drop_type = Dropout[drop_name, dropout_dim] + + if is_transposed: + conv = conv_type( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=strides, + padding=padding, + output_padding=strides - 1, + groups=groups, + bias=bias, + dilation=dilation, + ) + else: + conv = conv_type( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=strides, + padding=padding, + dilation=dilation, + groups=groups, + bias=bias, + ) + + self.add_module("conv", conv) + + if not conv_only: + if norm is not None: + self.add_module("norm", norm_type(out_channels, **norm_args)) + + if dropout: + self.add_module("dropout", drop_type(**drop_args)) + + if act is not None: + self.add_module("act", act_type(**act_args)) + + +class ResidualUnit(nn.Module): + """ + Residual module with multiple convolutions and a residual connection. + + Args: + dimensions: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + strides: convolution stride. Defaults to 1. + kernel_size: convolution kernel size. Defaults to 3. + subunits: number of convolutions. Defaults to 2. + act: activation type and arguments. Defaults to PReLU. + norm: feature normalization type and arguments. Defaults to instance norm. + dropout: dropout ratio. Defaults to no dropout. + dropout_dim: determine the dimensions of dropout. Defaults to 1. + When dropout_dim = 1, randomly zeroes some of the elements for each channel. + When dropout_dim = 2, Randomly zero out entire channels (a channel is a 2D feature map). + When dropout_dim = 3, Randomly zero out entire channels (a channel is a 3D feature map). + The value of dropout_dim should be no no larger than the value of dimensions. + dilation: dilation rate. Defaults to 1. + bias: whether to have a bias term. Defaults to True. + last_conv_only: for the last subunit, whether to use the convolutional layer only. + Defaults to False. + + See also: + + :py:class:`monai.networks.blocks.Convolution` + + """ + + def __init__( + self, + dimensions: int, + in_channels: int, + out_channels: int, + strides: int = 1, + kernel_size: Union[Sequence[int], int] = 3, + subunits: int = 2, + act: Optional[Union[Tuple, str]] = Act.PRELU, + norm: Union[Tuple, str] = Norm.INSTANCE, + dropout: Optional[Union[Tuple, str, float]] = None, + dropout_dim: int = 1, + dilation: Union[Sequence[int], int] = 1, + bias: bool = True, + last_conv_only: bool = False, + ) -> None: + super().__init__() + self.dimensions = dimensions + self.in_channels = in_channels + self.out_channels = out_channels + self.conv = nn.Sequential() + self.residual = nn.Identity() + + padding = same_padding(kernel_size, dilation) + schannels = in_channels + sstrides = strides + subunits = max(1, subunits) + + for su in range(subunits): + conv_only = last_conv_only and su == (subunits - 1) + unit = Convolution( + dimensions, + schannels, + out_channels, + strides=sstrides, + kernel_size=kernel_size, + act=act, + norm=norm, + dropout=dropout, + dropout_dim=dropout_dim, + dilation=dilation, + bias=bias, + conv_only=conv_only, + ) + + self.conv.add_module(f"unit{su:d}", unit) + + # after first loop set channels and strides to what they should be for subsequent units + schannels = out_channels + sstrides = 1 + + # apply convolution to input to change number of output channels and size to match that coming from self.conv + if np.prod(strides) != 1 or in_channels != out_channels: + rkernel_size = kernel_size + rpadding = padding + + if np.prod(strides) == 1: # if only adapting number of channels a 1x1 kernel is used with no padding + rkernel_size = 1 + rpadding = 0 + + conv_type = Conv[Conv.CONV, dimensions] + self.residual = conv_type(in_channels, out_channels, rkernel_size, strides, rpadding, bias=bias) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + res: torch.Tensor = self.residual(x) # create the additive residual from x + cx: torch.Tensor = self.conv(x) # apply x to sequence of operations + return cx + res # add the residual to the output diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/downsample.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/downsample.py new file mode 100644 index 0000000000000000000000000000000000000000..adcbec2850b0d0192854a50f026875c5e19e0628 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/downsample.py @@ -0,0 +1,62 @@ +# Copyright 2020 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 typing import Optional, Sequence, Union + +import torch +import torch.nn as nn + +from monai.networks.layers.factories import Pool +from monai.utils import ensure_tuple_rep + + +class MaxAvgPool(nn.Module): + """ + Downsample with both maxpooling and avgpooling, + double the channel size by concatenating the downsampled feature maps. + """ + + def __init__( + self, + spatial_dims: int, + kernel_size: Union[Sequence[int], int], + stride: Optional[Union[Sequence[int], int]] = None, + padding: Union[Sequence[int], int] = 0, + ceil_mode: bool = False, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + kernel_size: the kernel size of both pooling operations. + stride: the stride of the window. Default value is `kernel_size`. + padding: implicit zero padding to be added to both pooling operations. + ceil_mode: when True, will use ceil instead of floor to compute the output shape. + """ + super().__init__() + _params = { + "kernel_size": ensure_tuple_rep(kernel_size, spatial_dims), + "stride": None if stride is None else ensure_tuple_rep(stride, spatial_dims), + "padding": ensure_tuple_rep(padding, spatial_dims), + "ceil_mode": ceil_mode, + } + self.max_pool = Pool[Pool.MAX, spatial_dims](**_params) + self.avg_pool = Pool[Pool.AVG, spatial_dims](**_params) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: Tensor in shape (batch, channel, spatial_1[, spatial_2, ...]). + + Returns: + Tensor in shape (batch, 2*channel, spatial_1[, spatial_2, ...]). + """ + x_d = torch.cat([self.max_pool(x), self.avg_pool(x)], dim=1) + return x_d diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/fcn.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/fcn.py new file mode 100644 index 0000000000000000000000000000000000000000..7781f427321b87db1954769271413c36a267247c --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/fcn.py @@ -0,0 +1,242 @@ +# Copyright 2020 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 typing import Type + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.blocks.upsample import UpSample +from monai.networks.layers.factories import Act, Conv, Norm +from monai.utils import optional_import + +models, _ = optional_import("torchvision", "0.5.0", name="models") + + +class GCN(nn.Module): + """ + The Global Convolutional Network module using large 1D + Kx1 and 1xK kernels to represent 2D kernels. + """ + + def __init__(self, inplanes: int, planes: int, ks: int = 7): + """ + Args: + inplanes: number of input channels. + planes: number of output channels. + ks: kernel size for one dimension. Defaults to 7. + """ + super(GCN, self).__init__() + + conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2] + self.conv_l1 = conv2d_type(in_channels=inplanes, out_channels=planes, kernel_size=(ks, 1), padding=(ks // 2, 0)) + self.conv_l2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=(1, ks), padding=(0, ks // 2)) + self.conv_r1 = conv2d_type(in_channels=inplanes, out_channels=planes, kernel_size=(1, ks), padding=(0, ks // 2)) + self.conv_r2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=(ks, 1), padding=(ks // 2, 0)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, inplanes, spatial_1, spatial_2). + """ + x_l = self.conv_l1(x) + x_l = self.conv_l2(x_l) + x_r = self.conv_r1(x) + x_r = self.conv_r2(x_r) + x = x_l + x_r + return x + + +class Refine(nn.Module): + """ + Simple residual block to refine the details of the activation maps. + """ + + def __init__(self, planes: int): + """ + Args: + planes: number of input channels. + """ + super(Refine, self).__init__() + + relu_type: Type[nn.ReLU] = Act[Act.RELU] + conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2] + norm2d_type: Type[nn.BatchNorm2d] = Norm[Norm.BATCH, 2] + + self.bn = norm2d_type(num_features=planes) + self.relu = relu_type(inplace=True) + self.conv1 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=3, padding=1) + self.conv2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=3, padding=1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, planes, spatial_1, spatial_2). + """ + residual = x + x = self.bn(x) + x = self.relu(x) + x = self.conv1(x) + x = self.bn(x) + x = self.relu(x) + x = self.conv2(x) + + out = residual + x + return out + + +class FCN(nn.Module): + """ + 2D FCN network with 3 input channels. The small decoder is built + with the GCN and Refine modules. + The code is adapted from `lsqshr's official 2D code `_. + + Args: + out_channels: number of output channels. Defaults to 1. + upsample_mode: [``"transpose"``, ``"bilinear"``] + The mode of upsampling manipulations. + Using the second mode cannot guarantee the model's reproducibility. Defaults to ``bilinear``. + + - ``transpose``, uses transposed convolution layers. + - ``bilinear``, uses bilinear interpolate. + """ + + def __init__(self, out_channels: int = 1, upsample_mode: str = "bilinear"): + super(FCN, self).__init__() + + conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2] + + self.upsample_mode = upsample_mode + self.conv2d_type = conv2d_type + self.out_channels = out_channels + resnet = models.resnet50(pretrained=True) + + self.conv1 = resnet.conv1 + self.bn0 = resnet.bn1 + self.relu = resnet.relu + self.maxpool = resnet.maxpool + + self.layer1 = resnet.layer1 + self.layer2 = resnet.layer2 + self.layer3 = resnet.layer3 + self.layer4 = resnet.layer4 + + self.gcn1 = GCN(2048, self.out_channels) + self.gcn2 = GCN(1024, self.out_channels) + self.gcn3 = GCN(512, self.out_channels) + self.gcn4 = GCN(64, self.out_channels) + self.gcn5 = GCN(64, self.out_channels) + + self.refine1 = Refine(self.out_channels) + self.refine2 = Refine(self.out_channels) + self.refine3 = Refine(self.out_channels) + self.refine4 = Refine(self.out_channels) + self.refine5 = Refine(self.out_channels) + self.refine6 = Refine(self.out_channels) + self.refine7 = Refine(self.out_channels) + self.refine8 = Refine(self.out_channels) + self.refine9 = Refine(self.out_channels) + self.refine10 = Refine(self.out_channels) + self.transformer = self.conv2d_type(in_channels=256, out_channels=64, kernel_size=1) + + if self.upsample_mode == "transpose": + self.up_conv = UpSample( + dimensions=2, + in_channels=self.out_channels, + out_channels=self.out_channels, + scale_factor=2, + with_conv=True, + ) + + def forward(self, x: torch.Tensor): + """ + Args: + x: in shape (batch, 3, spatial_1, spatial_2). + """ + org_input = x + x = self.conv1(x) + x = self.bn0(x) + x = self.relu(x) + conv_x = x + x = self.maxpool(x) + pool_x = x + + fm1 = self.layer1(x) + fm2 = self.layer2(fm1) + fm3 = self.layer3(fm2) + fm4 = self.layer4(fm3) + + gcfm1 = self.refine1(self.gcn1(fm4)) + gcfm2 = self.refine2(self.gcn2(fm3)) + gcfm3 = self.refine3(self.gcn3(fm2)) + gcfm4 = self.refine4(self.gcn4(pool_x)) + gcfm5 = self.refine5(self.gcn5(conv_x)) + + if self.upsample_mode == "transpose": + fs1 = self.refine6(self.up_conv(gcfm1) + gcfm2) + fs2 = self.refine7(self.up_conv(fs1) + gcfm3) + fs3 = self.refine8(self.up_conv(fs2) + gcfm4) + fs4 = self.refine9(self.up_conv(fs3) + gcfm5) + out = self.refine10(self.up_conv(fs4)) + else: + fs1 = self.refine6( + F.interpolate(gcfm1, fm3.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm2 + ) + fs2 = self.refine7(F.interpolate(fs1, fm2.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm3) + fs3 = self.refine8( + F.interpolate(fs2, pool_x.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm4 + ) + fs4 = self.refine9( + F.interpolate(fs3, conv_x.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm5 + ) + out = self.refine10(F.interpolate(fs4, org_input.size()[2:], mode=self.upsample_mode, align_corners=True)) + return out + + +class MCFCN(FCN): + """ + The multi-channel version of the 2D FCN module. + Adds a projection layer to take arbitrary number of inputs. + + Args: + in_channels: number of input channels. Defaults to 3. + out_channels: number of output channels. Defaults to 1. + upsample_mode: [``"transpose"``, ``"bilinear"``] + The mode of upsampling manipulations. + Using the second mode cannot guarantee the model's reproducibility. Defaults to ``bilinear``. + + - ``transpose``, uses transposed convolution layers. + - ``bilinear``, uses bilinear interpolate. + """ + + def __init__(self, in_channels: int = 3, out_channels: int = 1, upsample_mode: str = "bilinear"): + super(MCFCN, self).__init__(out_channels=out_channels, upsample_mode=upsample_mode) + + self.init_proj = Convolution( + dimensions=2, + in_channels=in_channels, + out_channels=3, + kernel_size=1, + act=("relu", {"inplace": True}), + norm=Norm.BATCH, + bias=False, + ) + + def forward(self, x: torch.Tensor): + """ + Args: + x: in shape (batch, in_channels, spatial_1, spatial_2). + """ + x = self.init_proj(x) + out = super(MCFCN, self).forward(x) + return out diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/segresnet_block.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/segresnet_block.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6fd132037b53556b403588b1ebe0040a52f179 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/segresnet_block.py @@ -0,0 +1,119 @@ +# Copyright 2020 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. + +import torch.nn as nn + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.blocks.upsample import UpSample +from monai.networks.layers.factories import Act, Norm + + +def get_norm_layer(spatial_dims: int, in_channels: int, norm_name: str, num_groups: int = 8): + if norm_name not in ["batch", "instance", "group"]: + raise ValueError(f"Unsupported normalization mode: {norm_name}") + else: + if norm_name == "group": + norm = Norm[norm_name](num_groups=num_groups, num_channels=in_channels) + else: + norm = Norm[norm_name, spatial_dims](in_channels) + if norm.bias is not None: + nn.init.zeros_(norm.bias) + if norm.weight is not None: + nn.init.ones_(norm.weight) + return norm + + +def get_conv_layer( + spatial_dims: int, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, bias: bool = False +): + + return Convolution( + spatial_dims, + in_channels, + out_channels, + strides=stride, + kernel_size=kernel_size, + bias=bias, + conv_only=True, + ) + + +def get_upsample_layer(spatial_dims: int, in_channels: int, upsample_mode: str = "trilinear", scale_factor: int = 2): + up_module: nn.Module + if upsample_mode == "transpose": + up_module = UpSample( + spatial_dims, + in_channels, + scale_factor=scale_factor, + with_conv=True, + ) + else: + upsample_mode = "bilinear" if spatial_dims == 2 else "trilinear" + up_module = nn.Upsample(scale_factor=scale_factor, mode=upsample_mode, align_corners=False) + return up_module + + +class ResBlock(nn.Module): + """ + ResBlock employs skip connection and two convolution blocks and is used + in SegResNet based on `3D MRI brain tumor segmentation using autoencoder regularization + `_. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + kernel_size: int = 3, + stride: int = 1, + bias: bool = False, + norm_name: str = "group", + num_groups: int = 8, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2 or 3. + in_channels: number of input channels. + kernel_size: convolution kernel size, the value should be an odd number. Defaults to 3. + stride: convolution stride. Defaults to 1. + bias: whether to have a bias term in convolution layer. Defaults to ``True``. + norm_name: feature normalization type, this module only supports group norm, + batch norm and instance norm. Defaults to ``group``. + num_groups: number of groups to separate the channels into, in this module, + in_channels should be divisible by num_groups. Defaults to 8. + """ + + super().__init__() + + assert kernel_size % 2 == 1, "kernel_size should be an odd number." + assert in_channels % num_groups == 0, "in_channels should be divisible by num_groups." + + self.norm1 = get_norm_layer(spatial_dims, in_channels, norm_name, num_groups=num_groups) + self.norm2 = get_norm_layer(spatial_dims, in_channels, norm_name, num_groups=num_groups) + self.relu = Act[Act.RELU](inplace=True) + self.conv1 = get_conv_layer(spatial_dims, in_channels, in_channels) + self.conv2 = get_conv_layer(spatial_dims, in_channels, in_channels) + + def forward(self, x): + + identity = x + + x = self.norm1(x) + x = self.relu(x) + x = self.conv1(x) + + x = self.norm2(x) + x = self.relu(x) + x = self.conv2(x) + + x += identity + + return x diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/squeeze_and_excitation.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/squeeze_and_excitation.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6b823497ecfdfb1aa4a740bb84ca751e8bd7ae --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/squeeze_and_excitation.py @@ -0,0 +1,372 @@ +# Copyright 2020 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. + +import math +from typing import Dict, Optional, Tuple, Union + +import torch +import torch.nn as nn + +from monai.networks.blocks import Convolution +from monai.networks.layers.factories import Act, Conv, Norm, Pool, split_args + + +class ChannelSELayer(nn.Module): + """ + Re-implementation of the Squeeze-and-Excitation block based on: + "Hu et al., Squeeze-and-Excitation Networks, https://arxiv.org/abs/1709.01507". + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + r: int = 2, + acti_type_1: Union[Tuple[str, Dict], str] = ("relu", {"inplace": True}), + acti_type_2: Union[Tuple[str, Dict], str] = "sigmoid", + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + r: the reduction ratio r in the paper. Defaults to 2. + acti_type_1: activation type of the hidden squeeze layer. Defaults to ``("relu", {"inplace": True})``. + acti_type_2: activation type of the output squeeze layer. Defaults to "sigmoid". + + Raises: + ValueError: When ``r`` is nonpositive or larger than ``in_channels``. + + See also: + + :py:class:`monai.networks.layers.Act` + + """ + super(ChannelSELayer, self).__init__() + + pool_type = Pool[Pool.ADAPTIVEAVG, spatial_dims] + self.avg_pool = pool_type(1) # spatial size (1, 1, ...) + + channels = int(in_channels // r) + if channels <= 0: + raise ValueError(f"r must be positive and smaller than in_channels, got r={r} in_channels={in_channels}.") + + act_1, act_1_args = split_args(acti_type_1) + act_2, act_2_args = split_args(acti_type_2) + self.fc = nn.Sequential( + nn.Linear(in_channels, channels, bias=True), + Act[act_1](**act_1_args), + nn.Linear(channels, in_channels, bias=True), + Act[act_2](**act_2_args), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]). + """ + b, c = x.shape[:2] + y: torch.Tensor = self.avg_pool(x).view(b, c) + y = self.fc(y).view([b, c] + [1] * (x.ndimension() - 2)) + return x * y + + +class ResidualSELayer(ChannelSELayer): + """ + A "squeeze-and-excitation"-like layer with a residual connection:: + + --+-- SE --o-- + | | + +--------+ + + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + r: int = 2, + acti_type_1: Union[Tuple[str, Dict], str] = "leakyrelu", + acti_type_2: Union[Tuple[str, Dict], str] = "relu", + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + r: the reduction ratio r in the paper. Defaults to 2. + acti_type_1: defaults to "leakyrelu". + acti_type_2: defaults to "relu". + + See also: + + :py:class:`monai.networks.blocks.ChannelSELayer` + + """ + super().__init__( + spatial_dims=spatial_dims, in_channels=in_channels, r=r, acti_type_1=acti_type_1, acti_type_2=acti_type_2 + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]). + """ + return x + super().forward(x) + + +class SEBlock(nn.Module): + """ + Residual module enhanced with Squeeze-and-Excitation:: + + ----+- conv1 -- conv2 -- conv3 -- SE -o--- + | | + +---(channel project if needed)----+ + + Re-implementation of the SE-Resnet block based on: + "Hu et al., Squeeze-and-Excitation Networks, https://arxiv.org/abs/1709.01507". + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + n_chns_1: int, + n_chns_2: int, + n_chns_3: int, + conv_param_1: Optional[Dict] = None, + conv_param_2: Optional[Dict] = None, + conv_param_3: Optional[Dict] = None, + project: Optional[Convolution] = None, + r: int = 2, + acti_type_1: Union[Tuple[str, Dict], str] = ("relu", {"inplace": True}), + acti_type_2: Union[Tuple[str, Dict], str] = "sigmoid", + acti_type_final: Optional[Union[Tuple[str, Dict], str]] = ("relu", {"inplace": True}), + ): + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + n_chns_1: number of output channels in the 1st convolution. + n_chns_2: number of output channels in the 2nd convolution. + n_chns_3: number of output channels in the 3rd convolution. + conv_param_1: additional parameters to the 1st convolution. + Defaults to ``{"kernel_size": 1, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})}`` + conv_param_2: additional parameters to the 2nd convolution. + Defaults to ``{"kernel_size": 3, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})}`` + conv_param_3: additional parameters to the 3rd convolution. + Defaults to ``{"kernel_size": 1, "norm": Norm.BATCH, "act": None}`` + project: in the case of residual chns and output chns doesn't match, a project + (Conv) layer/block is used to adjust the number of chns. In SENET, it is + consisted with a Conv layer as well as a Norm layer. + Defaults to None (chns are matchable) or a Conv layer with kernel size 1. + r: the reduction ratio r in the paper. Defaults to 2. + acti_type_1: activation type of the hidden squeeze layer. Defaults to "relu". + acti_type_2: activation type of the output squeeze layer. Defaults to "sigmoid". + acti_type_final: activation type of the end of the block. Defaults to "relu". + + See also: + + :py:class:`monai.networks.blocks.ChannelSELayer` + + """ + super(SEBlock, self).__init__() + + if not conv_param_1: + conv_param_1 = {"kernel_size": 1, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})} + self.conv1 = Convolution( + dimensions=spatial_dims, in_channels=in_channels, out_channels=n_chns_1, **conv_param_1 + ) + + if not conv_param_2: + conv_param_2 = {"kernel_size": 3, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})} + self.conv2 = Convolution(dimensions=spatial_dims, in_channels=n_chns_1, out_channels=n_chns_2, **conv_param_2) + + if not conv_param_3: + conv_param_3 = {"kernel_size": 1, "norm": Norm.BATCH, "act": None} + self.conv3 = Convolution(dimensions=spatial_dims, in_channels=n_chns_2, out_channels=n_chns_3, **conv_param_3) + + self.se_layer = ChannelSELayer( + spatial_dims=spatial_dims, in_channels=n_chns_3, r=r, acti_type_1=acti_type_1, acti_type_2=acti_type_2 + ) + + self.project = project + if self.project is None and in_channels != n_chns_3: + self.project = Conv[Conv.CONV, spatial_dims](in_channels, n_chns_3, kernel_size=1) + + self.act = None + if acti_type_final is not None: + act_final, act_final_args = split_args(acti_type_final) + self.act = Act[act_final](**act_final_args) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]). + """ + residual = x if self.project is None else self.project(x) + x = self.conv1(x) + x = self.conv2(x) + x = self.conv3(x) + x = self.se_layer(x) + x += residual + if self.act is not None: + x = self.act(x) + return x + + +class SEBottleneck(SEBlock): + """ + Bottleneck for SENet154. + """ + + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + groups: int, + reduction: int, + stride: int = 1, + downsample: Optional[Convolution] = None, + ) -> None: + + conv_param_1 = { + "strides": 1, + "kernel_size": 1, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "bias": False, + } + conv_param_2 = { + "strides": stride, + "kernel_size": 3, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "groups": groups, + "bias": False, + } + conv_param_3 = {"strides": 1, "kernel_size": 1, "act": None, "norm": Norm.BATCH, "bias": False} + + super(SEBottleneck, self).__init__( + spatial_dims=spatial_dims, + in_channels=inplanes, + n_chns_1=planes * 2, + n_chns_2=planes * 4, + n_chns_3=planes * 4, + conv_param_1=conv_param_1, + conv_param_2=conv_param_2, + conv_param_3=conv_param_3, + project=downsample, + r=reduction, + ) + + +class SEResNetBottleneck(SEBlock): + """ + ResNet bottleneck with a Squeeze-and-Excitation module. It follows Caffe + implementation and uses `strides=stride` in `conv1` and not in `conv2` + (the latter is used in the torchvision implementation of ResNet). + """ + + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + groups: int, + reduction: int, + stride: int = 1, + downsample: Optional[Convolution] = None, + ) -> None: + + conv_param_1 = { + "strides": stride, + "kernel_size": 1, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "bias": False, + } + conv_param_2 = { + "strides": 1, + "kernel_size": 3, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "groups": groups, + "bias": False, + } + conv_param_3 = {"strides": 1, "kernel_size": 1, "act": None, "norm": Norm.BATCH, "bias": False} + + super(SEResNetBottleneck, self).__init__( + spatial_dims=spatial_dims, + in_channels=inplanes, + n_chns_1=planes, + n_chns_2=planes, + n_chns_3=planes * 4, + conv_param_1=conv_param_1, + conv_param_2=conv_param_2, + conv_param_3=conv_param_3, + project=downsample, + r=reduction, + ) + + +class SEResNeXtBottleneck(SEBlock): + """ + ResNeXt bottleneck type C with a Squeeze-and-Excitation module. + """ + + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + groups: int, + reduction: int, + stride: int = 1, + downsample: Optional[Convolution] = None, + base_width: int = 4, + ) -> None: + + conv_param_1 = { + "strides": 1, + "kernel_size": 1, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "bias": False, + } + conv_param_2 = { + "strides": stride, + "kernel_size": 3, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "groups": groups, + "bias": False, + } + conv_param_3 = {"strides": 1, "kernel_size": 1, "act": None, "norm": Norm.BATCH, "bias": False} + width = math.floor(planes * (base_width / 64)) * groups + + super(SEResNeXtBottleneck, self).__init__( + spatial_dims=spatial_dims, + in_channels=inplanes, + n_chns_1=width, + n_chns_2=width, + n_chns_3=planes * 4, + conv_param_1=conv_param_1, + conv_param_2=conv_param_2, + conv_param_3=conv_param_3, + project=downsample, + r=reduction, + ) diff --git a/testbed/Project-MONAI__MONAI/monai/networks/blocks/upsample.py b/testbed/Project-MONAI__MONAI/monai/networks/blocks/upsample.py new file mode 100644 index 0000000000000000000000000000000000000000..bab8b17273d72508224aa8d1c3272291119d9778 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/blocks/upsample.py @@ -0,0 +1,162 @@ +# Copyright 2020 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 typing import Optional, Sequence, Union + +import torch +import torch.nn as nn + +from monai.networks.layers.factories import Conv, Pad, Pool +from monai.networks.utils import icnr_init, pixelshuffle +from monai.utils import UpsampleMode, ensure_tuple_rep + + +class UpSample(nn.Module): + """ + Upsample with either kernel 1 conv + interpolation or transposed conv. + """ + + def __init__( + self, + dimensions: int, + in_channels: int, + out_channels: Optional[int] = None, + scale_factor: Union[Sequence[float], float] = 2, + with_conv: bool = False, + mode: Union[UpsampleMode, str] = UpsampleMode.LINEAR, + align_corners: Optional[bool] = True, + ) -> None: + """ + Args: + dimensions: number of spatial dimensions of the input image. + in_channels: number of channels of the input image. + out_channels: number of channels of the output image. Defaults to `in_channels`. + scale_factor: multiplier for spatial size. Has to match input size if it is a tuple. Defaults to 2. + with_conv: whether to use a transposed convolution for upsampling. Defaults to False. + mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``} + If ends with ``"linear"`` will use ``spatial dims`` to determine the correct interpolation. + This corresponds to linear, bilinear, trilinear for 1D, 2D, and 3D respectively. + The interpolation mode. Defaults to ``"linear"``. + See also: https://pytorch.org/docs/stable/nn.html#upsample + align_corners: set the align_corners parameter of `torch.nn.Upsample`. Defaults to True. + """ + super().__init__() + scale_factor_ = ensure_tuple_rep(scale_factor, dimensions) + if not out_channels: + out_channels = in_channels + if not with_conv: + mode = UpsampleMode(mode) + linear_mode = [UpsampleMode.LINEAR, UpsampleMode.BILINEAR, UpsampleMode.TRILINEAR] + if mode in linear_mode: # choose mode based on dimensions + mode = linear_mode[dimensions - 1] + self.upsample = nn.Sequential( + Conv[Conv.CONV, dimensions](in_channels=in_channels, out_channels=out_channels, kernel_size=1), + nn.Upsample(scale_factor=scale_factor_, mode=mode.value, align_corners=align_corners), + ) + else: + self.upsample = Conv[Conv.CONVTRANS, dimensions]( + in_channels=in_channels, out_channels=out_channels, kernel_size=scale_factor_, stride=scale_factor_ + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: Tensor in shape (batch, channel, spatial_1[, spatial_2, ...). + """ + return torch.as_tensor(self.upsample(x)) + + +class SubpixelUpsample(nn.Module): + """ + Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. + The module is consisted with two parts. First of all, a convolutional layer is employed + to increase the number of channels into: ``in_channels * (scale_factor ** dimensions)``. + Secondly, a pixel shuffle manipulation is utilized to aggregates the feature maps from + low resolution space and build the super resolution space. + The first part of the module is not fixed, a sequential layers can be used to replace the + default single layer. + + See: Shi et al., 2016, "Real-Time Single Image and Video Super-Resolution + Using a nEfficient Sub-Pixel Convolutional Neural Network." + + See: Aitken et al., 2017, "Checkerboard artifact free sub-pixel convolution". + + The idea comes from: + https://arxiv.org/abs/1609.05158 + + The pixel shuffle mechanism refers to: + https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/PixelShuffle.cpp + and: + https://github.com/pytorch/pytorch/pull/6340/files + + """ + + def __init__( + self, + dimensions: int, + in_channels: int, + scale_factor: int = 2, + conv_block: Optional[nn.Module] = None, + apply_pad_pool: bool = True, + ) -> None: + """ + Args: + dimensions: number of spatial dimensions of the input image. + in_channels: number of channels of the input image. + scale_factor: multiplier for spatial size. Defaults to 2. + conv_block: a conv block to extract feature maps before upsampling. Defaults to None. + When ``conv_block is None``, one reserved conv layer will be utilized. + apply_pad_pool: if True the upsampled tensor is padded then average pooling is applied with a kernel the + size of `scale_factor` with a stride of 1. This implements the nearest neighbour resize convolution + component of subpixel convolutions described in Aitken et al. + """ + super().__init__() + + if scale_factor <= 0: + raise ValueError(f"The `scale_factor` multiplier must be an integer greater than 0, got {scale_factor}.") + + self.dimensions = dimensions + self.scale_factor = scale_factor + + if conv_block is None: + conv_out_channels = in_channels * (scale_factor ** dimensions) + self.conv_block = Conv[Conv.CONV, dimensions]( + in_channels=in_channels, + out_channels=conv_out_channels, + kernel_size=3, + stride=1, + padding=1, + ) + + icnr_init(self.conv_block, self.scale_factor) + else: + self.conv_block = conv_block + + self.pad_pool: nn.Module = nn.Identity() + + if apply_pad_pool: + pool_type = Pool[Pool.AVG, self.dimensions] + pad_type = Pad[Pad.CONSTANTPAD, self.dimensions] + + self.pad_pool = nn.Sequential( + pad_type(padding=(self.scale_factor - 1, 0) * self.dimensions, value=0.0), + pool_type(kernel_size=self.scale_factor, stride=1), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: Tensor in shape (batch, channel, spatial_1[, spatial_2, ...). + """ + x = self.conv_block(x) + x = pixelshuffle(x, self.dimensions, self.scale_factor) + x = self.pad_pool(x) + return x diff --git a/testbed/Project-MONAI__MONAI/monai/networks/extensions/lltm/lltm_cuda.cpp b/testbed/Project-MONAI__MONAI/monai/networks/extensions/lltm/lltm_cuda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed27c258359ea7397b86e9b7654a9c29809afca9 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/extensions/lltm/lltm_cuda.cpp @@ -0,0 +1,94 @@ +/* +Copyright 2020 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. +*/ + +#include + +#include + +// CUDA forward declarations + +std::vector lltm_cuda_forward( + torch::Tensor input, + torch::Tensor weights, + torch::Tensor bias, + torch::Tensor old_h, + torch::Tensor old_cell); + +std::vector lltm_cuda_backward( + torch::Tensor grad_h, + torch::Tensor grad_cell, + torch::Tensor new_cell, + torch::Tensor input_gate, + torch::Tensor output_gate, + torch::Tensor candidate_cell, + torch::Tensor X, + torch::Tensor gate_weights, + torch::Tensor weights); + +// C++ interface + +// NOTE: AT_ASSERT has become AT_CHECK on master after 0.4. +#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") +#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) + +std::vector lltm_forward( + torch::Tensor input, + torch::Tensor weights, + torch::Tensor bias, + torch::Tensor old_h, + torch::Tensor old_cell) { + CHECK_INPUT(input); + CHECK_INPUT(weights); + CHECK_INPUT(bias); + CHECK_INPUT(old_h); + CHECK_INPUT(old_cell); + + return lltm_cuda_forward(input, weights, bias, old_h, old_cell); +} + +std::vector lltm_backward( + torch::Tensor grad_h, + torch::Tensor grad_cell, + torch::Tensor new_cell, + torch::Tensor input_gate, + torch::Tensor output_gate, + torch::Tensor candidate_cell, + torch::Tensor X, + torch::Tensor gate_weights, + torch::Tensor weights) { + CHECK_INPUT(grad_h); + CHECK_INPUT(grad_cell); + CHECK_INPUT(input_gate); + CHECK_INPUT(output_gate); + CHECK_INPUT(candidate_cell); + CHECK_INPUT(X); + CHECK_INPUT(gate_weights); + CHECK_INPUT(weights); + + return lltm_cuda_backward( + grad_h, + grad_cell, + new_cell, + input_gate, + output_gate, + candidate_cell, + X, + gate_weights, + weights); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("lltm_forward", &lltm_forward, "LLTM forward (CUDA)"); + m.def("lltm_backward", &lltm_backward, "LLTM backward (CUDA)"); +} diff --git a/testbed/Project-MONAI__MONAI/monai/networks/extensions/lltm/lltm_cuda_kernel.cu b/testbed/Project-MONAI__MONAI/monai/networks/extensions/lltm/lltm_cuda_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..dd9aeeb024f79a5c77c1fd3d5acc26ce78b91631 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/extensions/lltm/lltm_cuda_kernel.cu @@ -0,0 +1,187 @@ +/* +Copyright 2020 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. +*/ + +#include + +#include +#include + +#include + +namespace { +template +__device__ __forceinline__ scalar_t sigmoid(scalar_t z) { + return 1.0 / (1.0 + exp(-z)); +} + +template +__device__ __forceinline__ scalar_t d_sigmoid(scalar_t z) { + const auto s = sigmoid(z); + return (1.0 - s) * s; +} + +template +__device__ __forceinline__ scalar_t d_tanh(scalar_t z) { + const auto t = tanh(z); + return 1 - (t * t); +} + +template +__device__ __forceinline__ scalar_t elu(scalar_t z, scalar_t alpha = 1.0) { + return fmaxf(0.0, z) + fminf(0.0, alpha * (exp(z) - 1.0)); +} + +template +__device__ __forceinline__ scalar_t d_elu(scalar_t z, scalar_t alpha = 1.0) { + const auto e = exp(z); + const auto d_relu = z < 0.0 ? 0.0 : 1.0; + return d_relu + (((alpha * (e - 1.0)) < 0.0) ? (alpha * e) : 0.0); +} + +template +__global__ void lltm_cuda_forward_kernel( + const torch::PackedTensorAccessor gates, + const torch::PackedTensorAccessor old_cell, + torch::PackedTensorAccessor new_h, + torch::PackedTensorAccessor new_cell, + torch::PackedTensorAccessor input_gate, + torch::PackedTensorAccessor output_gate, + torch::PackedTensorAccessor candidate_cell) { + //batch index + const int n = blockIdx.y; + // column index + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c < gates.size(2)){ + input_gate[n][c] = sigmoid(gates[n][0][c]); + output_gate[n][c] = sigmoid(gates[n][1][c]); + candidate_cell[n][c] = elu(gates[n][2][c]); + new_cell[n][c] = + old_cell[n][c] + candidate_cell[n][c] * input_gate[n][c]; + new_h[n][c] = tanh(new_cell[n][c]) * output_gate[n][c]; + } +} + +template +__global__ void lltm_cuda_backward_kernel( + torch::PackedTensorAccessor d_old_cell, + torch::PackedTensorAccessor d_gates, + const torch::PackedTensorAccessor grad_h, + const torch::PackedTensorAccessor grad_cell, + const torch::PackedTensorAccessor new_cell, + const torch::PackedTensorAccessor input_gate, + const torch::PackedTensorAccessor output_gate, + const torch::PackedTensorAccessor candidate_cell, + const torch::PackedTensorAccessor gate_weights) { + //batch index + const int n = blockIdx.y; + // column index + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c < d_gates.size(2)){ + const auto d_output_gate = tanh(new_cell[n][c]) * grad_h[n][c]; + const auto d_tanh_new_cell = output_gate[n][c] * grad_h[n][c]; + const auto d_new_cell = + d_tanh(new_cell[n][c]) * d_tanh_new_cell + grad_cell[n][c]; + + + d_old_cell[n][c] = d_new_cell; + const auto d_candidate_cell = input_gate[n][c] * d_new_cell; + const auto d_input_gate = candidate_cell[n][c] * d_new_cell; + + d_gates[n][0][c] = + d_input_gate * d_sigmoid(gate_weights[n][0][c]); + d_gates[n][1][c] = + d_output_gate * d_sigmoid(gate_weights[n][1][c]); + d_gates[n][2][c] = + d_candidate_cell * d_elu(gate_weights[n][2][c]); + } +} +} // namespace + +std::vector lltm_cuda_forward( + torch::Tensor input, + torch::Tensor weights, + torch::Tensor bias, + torch::Tensor old_h, + torch::Tensor old_cell) { + auto X = torch::cat({old_h, input}, /*dim=*/1); + auto gate_weights = torch::addmm(bias, X, weights.transpose(0, 1)); + + const auto batch_size = old_cell.size(0); + const auto state_size = old_cell.size(1); + + auto gates = gate_weights.reshape({batch_size, 3, state_size}); + auto new_h = torch::zeros_like(old_cell); + auto new_cell = torch::zeros_like(old_cell); + auto input_gate = torch::zeros_like(old_cell); + auto output_gate = torch::zeros_like(old_cell); + auto candidate_cell = torch::zeros_like(old_cell); + + const int threads = 1024; + const dim3 blocks((state_size + threads - 1) / threads, batch_size); + + AT_DISPATCH_FLOATING_TYPES(gates.type(), "lltm_forward_cuda", ([&] { + lltm_cuda_forward_kernel<<>>( + gates.packed_accessor(), + old_cell.packed_accessor(), + new_h.packed_accessor(), + new_cell.packed_accessor(), + input_gate.packed_accessor(), + output_gate.packed_accessor(), + candidate_cell.packed_accessor()); + })); + + return {new_h, new_cell, input_gate, output_gate, candidate_cell, X, gates}; +} + +std::vector lltm_cuda_backward( + torch::Tensor grad_h, + torch::Tensor grad_cell, + torch::Tensor new_cell, + torch::Tensor input_gate, + torch::Tensor output_gate, + torch::Tensor candidate_cell, + torch::Tensor X, + torch::Tensor gates, + torch::Tensor weights) { + auto d_old_cell = torch::zeros_like(new_cell); + auto d_gates = torch::zeros_like(gates); + + const auto batch_size = new_cell.size(0); + const auto state_size = new_cell.size(1); + + const int threads = 1024; + const dim3 blocks((state_size + threads - 1) / threads, batch_size); + + AT_DISPATCH_FLOATING_TYPES(X.type(), "lltm_forward_cuda", ([&] { + lltm_cuda_backward_kernel<<>>( + d_old_cell.packed_accessor(), + d_gates.packed_accessor(), + grad_h.packed_accessor(), + grad_cell.packed_accessor(), + new_cell.packed_accessor(), + input_gate.packed_accessor(), + output_gate.packed_accessor(), + candidate_cell.packed_accessor(), + gates.packed_accessor()); + })); + + auto d_gate_weights = d_gates.flatten(1, 2); + auto d_weights = d_gate_weights.t().mm(X); + auto d_bias = d_gate_weights.sum(/*dim=*/0, /*keepdim=*/true); + + auto d_X = d_gate_weights.mm(weights); + auto d_old_h = d_X.slice(/*dim=*/1, 0, state_size); + auto d_input = d_X.slice(/*dim=*/1, state_size); + + return {d_old_h, d_input, d_weights, d_bias, d_old_cell, d_gates}; +} diff --git a/testbed/Project-MONAI__MONAI/monai/networks/layers/__init__.py b/testbed/Project-MONAI__MONAI/monai/networks/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9125dc38cfd3445f860a900f5803066f5463d0d0 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/layers/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2020 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 .convutils import * +from .factories import * +from .simplelayers import * +from .spatial_transforms import * diff --git a/testbed/Project-MONAI__MONAI/monai/networks/layers/convutils.py b/testbed/Project-MONAI__MONAI/monai/networks/layers/convutils.py new file mode 100644 index 0000000000000000000000000000000000000000..eb24d6b46325e351996a4acb4fdc9907be32ce73 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/layers/convutils.py @@ -0,0 +1,90 @@ +# Copyright 2020 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 typing import Sequence, Tuple, Union + +import numpy as np + +__all__ = ["same_padding", "calculate_out_shape", "gaussian_1d"] + + +def same_padding( + kernel_size: Union[Sequence[int], int], dilation: Union[Sequence[int], int] = 1 +) -> Union[Tuple[int, ...], int]: + """ + Return the padding value needed to ensure a convolution using the given kernel size produces an output of the same + shape as the input for a stride of 1, otherwise ensure a shape of the input divided by the stride rounded down. + + Raises: + NotImplementedError: When ``np.any((kernel_size - 1) * dilation % 2 == 1)``. + + """ + + kernel_size_np = np.atleast_1d(kernel_size) + dilation_np = np.atleast_1d(dilation) + + if np.any((kernel_size_np - 1) * dilation % 2 == 1): + raise NotImplementedError( + f"Same padding not available for kernel_size={kernel_size_np} and dilation={dilation_np}." + ) + + padding_np = (kernel_size_np - 1) / 2 * dilation_np + padding = tuple(int(p) for p in padding_np) + + return padding if len(padding) > 1 else padding[0] + + +def calculate_out_shape( + in_shape: Union[Sequence[int], int], + kernel_size: Union[Sequence[int], int], + stride: Union[Sequence[int], int], + padding: Union[Sequence[int], int], +) -> Union[Tuple[int, ...], int]: + """ + Calculate the output tensor shape when applying a convolution to a tensor of shape `inShape` with kernel size + `kernel_size`, stride value `stride`, and input padding value `padding`. All arguments can be scalars or multiple + values, return value is a scalar if all inputs are scalars. + """ + in_shape_np = np.atleast_1d(in_shape) + kernel_size_np = np.atleast_1d(kernel_size) + stride_np = np.atleast_1d(stride) + padding_np = np.atleast_1d(padding) + + out_shape_np = ((in_shape_np - kernel_size_np + padding_np + padding_np) // stride_np) + 1 + out_shape = tuple(int(s) for s in out_shape_np) + + return out_shape if len(out_shape) > 1 else out_shape[0] + + +def gaussian_1d(sigma: float, truncated: float = 4.0) -> np.ndarray: + """ + one dimensional gaussian kernel. + + Args: + sigma: std of the kernel + truncated: tail length + + Raises: + ValueError: When ``sigma`` is nonpositive. + + Returns: + 1D numpy array + + """ + if sigma <= 0: + raise ValueError(f"sigma must be positive, got {sigma}.") + + tail = int(sigma * truncated + 0.5) + sigma2 = sigma * sigma + x = np.arange(-tail, tail + 1) + out = np.exp(-0.5 / sigma2 * x ** 2) + out /= out.sum() + return out diff --git a/testbed/Project-MONAI__MONAI/monai/networks/layers/factories.py b/testbed/Project-MONAI__MONAI/monai/networks/layers/factories.py new file mode 100644 index 0000000000000000000000000000000000000000..d35ede3d1ee137634d2273a004ef8dfd21977540 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/layers/factories.py @@ -0,0 +1,283 @@ +# Copyright 2020 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. + +""" +Defines factories for creating layers in generic, extensible, and dimensionally independent ways. A separate factory +object is created for each type of layer, and factory functions keyed to names are added to these objects. Whenever +a layer is requested the factory name and any necessary arguments are passed to the factory object. The return value +is typically a type but can be any callable producing a layer object. + +The factory objects contain functions keyed to names converted to upper case, these names can be referred to as members +of the factory so that they can function as constant identifiers. eg. instance normalisation is named `Norm.INSTANCE`. + +For example, to get a transpose convolution layer the name is needed and then a dimension argument is provided which is +passed to the factory function: + +.. code-block:: python + + dimension = 3 + name = Conv.CONVTRANS + conv = Conv[name, dimension] + +This allows the `dimension` value to be set in the constructor, for example so that the dimensionality of a network is +parameterizable. Not all factories require arguments after the name, the caller must be aware which are required. + +Defining new factories involves creating the object then associating it with factory functions: + +.. code-block:: python + + fact = LayerFactory() + + @fact.factory_function('test') + def make_something(x, y): + # do something with x and y to choose which layer type to return + return SomeLayerType + ... + + # request object from factory TEST with 1 and 2 as values for x and y + layer = fact[fact.TEST, 1, 2] + +Typically the caller of a factory would know what arguments to pass (ie. the dimensionality of the requested type) but +can be parameterized with the factory name and the arguments to pass to the created type at instantiation time: + +.. code-block:: python + + def use_factory(fact_args): + fact_name, type_args = split_args + layer_type = fact[fact_name, 1, 2] + return layer_type(**type_args) + ... + + kw_args = {'arg0':0, 'arg1':True} + layer = use_factory( (fact.TEST, kwargs) ) +""" + +from typing import Any, Callable, Dict, Tuple, Type, Union + +import torch.nn as nn + +__all__ = ["LayerFactory", "Dropout", "Norm", "Act", "Conv", "Pool", "split_args"] + + +class LayerFactory: + """ + Factory object for creating layers, this uses given factory functions to actually produce the types or constructing + callables. These functions are referred to by name and can be added at any time. + """ + + def __init__(self) -> None: + self.factories: Dict[str, Callable] = {} + + @property + def names(self) -> Tuple[str, ...]: + """ + Produces all factory names. + """ + + return tuple(self.factories) + + def add_factory_callable(self, name: str, func: Callable) -> None: + """ + Add the factory function to this object under the given name. + """ + + self.factories[name.upper()] = func + self.__doc__ = ( + "The supported member" + + ("s are: " if len(self.names) > 1 else " is: ") + + ", ".join(f"``{name}``" for name in self.names) + + ".\nPlease see :py:class:`monai.networks.layers.split_args` for additional args parsing." + ) + + def factory_function(self, name: str) -> Callable: + """ + Decorator for adding a factory function with the given name. + """ + + def _add(func: Callable) -> Callable: + self.add_factory_callable(name, func) + return func + + return _add + + def get_constructor(self, factory_name: str, *args) -> Any: + """ + Get the constructor for the given factory name and arguments. + + Raises: + TypeError: When ``factory_name`` is not a ``str``. + + """ + + if not isinstance(factory_name, str): + raise TypeError(f"factory_name must a str but is {type(factory_name).__name__}.") + + fact = self.factories[factory_name.upper()] + return fact(*args) + + def __getitem__(self, args) -> Any: + """ + Get the given name or name/arguments pair. If `args` is a callable it is assumed to be the constructor + itself and is returned, otherwise it should be the factory name or a pair containing the name and arguments. + """ + + # `args[0]` is actually a type or constructor + if callable(args): + return args + + # `args` is a factory name or a name with arguments + if isinstance(args, str): + name_obj, args = args, () + else: + name_obj, *args = args + + return self.get_constructor(name_obj, *args) + + def __getattr__(self, key): + """ + If `key` is a factory name, return it, otherwise behave as inherited. This allows referring to factory names + as if they were constants, eg. `Fact.FOO` for a factory Fact with factory function foo. + """ + + if key in self.factories: + return key + + return super().__getattribute__(key) + + +def split_args(args): + """ + Split arguments in a way to be suitable for using with the factory types. If `args` is a string it's interpreted as + the type name. + + Args: + args (str or a tuple of object name and kwarg dict): input arguments to be parsed. + + Raises: + TypeError: When ``args`` type is not in ``Union[str, Tuple[Union[str, Callable], dict]]``. + + Examples:: + + >>> act_type, args = split_args("PRELU") + >>> monai.networks.layers.Act[act_type] + + + >>> act_type, args = split_args(("PRELU", {"num_parameters": 1, "init": 0.25})) + >>> monai.networks.layers.Act[act_type](**args) + PReLU(num_parameters=1) + + """ + + if isinstance(args, str): + return args, {} + else: + name_obj, name_args = args + + if not isinstance(name_obj, (str, Callable)) or not isinstance(name_args, dict): + msg = "Layer specifiers must be single strings or pairs of the form (name/object-types, argument dict)" + raise TypeError(msg) + + return name_obj, name_args + + +# Define factories for these layer types + +Dropout = LayerFactory() +Norm = LayerFactory() +Act = LayerFactory() +Conv = LayerFactory() +Pool = LayerFactory() +Pad = LayerFactory() + + +@Dropout.factory_function("dropout") +def dropout_factory(dim: int) -> Type[Union[nn.Dropout, nn.Dropout2d, nn.Dropout3d]]: + types = (nn.Dropout, nn.Dropout2d, nn.Dropout3d) + return types[dim - 1] + + +@Norm.factory_function("instance") +def instance_factory(dim: int) -> Type[Union[nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d]]: + types = (nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d) + return types[dim - 1] + + +@Norm.factory_function("batch") +def batch_factory(dim: int) -> Type[Union[nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d]]: + types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d) + return types[dim - 1] + + +Norm.add_factory_callable("group", lambda: nn.modules.GroupNorm) +Act.add_factory_callable("elu", lambda: nn.modules.ELU) +Act.add_factory_callable("relu", lambda: nn.modules.ReLU) +Act.add_factory_callable("leakyrelu", lambda: nn.modules.LeakyReLU) +Act.add_factory_callable("prelu", lambda: nn.modules.PReLU) +Act.add_factory_callable("relu6", lambda: nn.modules.ReLU6) +Act.add_factory_callable("selu", lambda: nn.modules.SELU) +Act.add_factory_callable("celu", lambda: nn.modules.CELU) +Act.add_factory_callable("gelu", lambda: nn.modules.GELU) +Act.add_factory_callable("sigmoid", lambda: nn.modules.Sigmoid) +Act.add_factory_callable("tanh", lambda: nn.modules.Tanh) +Act.add_factory_callable("softmax", lambda: nn.modules.Softmax) +Act.add_factory_callable("logsoftmax", lambda: nn.modules.LogSoftmax) + + +@Conv.factory_function("conv") +def conv_factory(dim: int) -> Type[Union[nn.Conv1d, nn.Conv2d, nn.Conv3d]]: + types = (nn.Conv1d, nn.Conv2d, nn.Conv3d) + return types[dim - 1] + + +@Conv.factory_function("convtrans") +def convtrans_factory(dim: int) -> Type[Union[nn.ConvTranspose1d, nn.ConvTranspose2d, nn.ConvTranspose3d]]: + types = (nn.ConvTranspose1d, nn.ConvTranspose2d, nn.ConvTranspose3d) + return types[dim - 1] + + +@Pool.factory_function("max") +def maxpooling_factory(dim: int) -> Type[Union[nn.MaxPool1d, nn.MaxPool2d, nn.MaxPool3d]]: + types = (nn.MaxPool1d, nn.MaxPool2d, nn.MaxPool3d) + return types[dim - 1] + + +@Pool.factory_function("adaptivemax") +def adaptive_maxpooling_factory( + dim: int, +) -> Type[Union[nn.AdaptiveMaxPool1d, nn.AdaptiveMaxPool2d, nn.AdaptiveMaxPool3d]]: + types = (nn.AdaptiveMaxPool1d, nn.AdaptiveMaxPool2d, nn.AdaptiveMaxPool3d) + return types[dim - 1] + + +@Pool.factory_function("avg") +def avgpooling_factory(dim: int) -> Type[Union[nn.AvgPool1d, nn.AvgPool2d, nn.AvgPool3d]]: + types = (nn.AvgPool1d, nn.AvgPool2d, nn.AvgPool3d) + return types[dim - 1] + + +@Pool.factory_function("adaptiveavg") +def adaptive_avgpooling_factory( + dim: int, +) -> Type[Union[nn.AdaptiveAvgPool1d, nn.AdaptiveAvgPool2d, nn.AdaptiveAvgPool3d]]: + types = (nn.AdaptiveAvgPool1d, nn.AdaptiveAvgPool2d, nn.AdaptiveAvgPool3d) + return types[dim - 1] + + +@Pad.factory_function("replicationpad") +def replication_pad_factory(dim: int) -> Type[Union[nn.ReplicationPad1d, nn.ReplicationPad2d, nn.ReplicationPad3d]]: + types = (nn.ReplicationPad1d, nn.ReplicationPad2d, nn.ReplicationPad3d) + return types[dim - 1] + + +@Pad.factory_function("constantpad") +def constant_pad_factory(dim: int) -> Type[Union[nn.ConstantPad1d, nn.ConstantPad2d, nn.ConstantPad3d]]: + types = (nn.ConstantPad1d, nn.ConstantPad2d, nn.ConstantPad3d) + return types[dim - 1] diff --git a/testbed/Project-MONAI__MONAI/monai/networks/layers/simplelayers.py b/testbed/Project-MONAI__MONAI/monai/networks/layers/simplelayers.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba2ccac89600c9c0d89c5c3d6e2a88a6079deaf --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/layers/simplelayers.py @@ -0,0 +1,175 @@ +# Copyright 2020 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. + +import math +from typing import Sequence, Union, cast + +import torch +import torch.nn.functional as F +from torch import nn +from torch.autograd import Function + +from monai.networks.layers.convutils import gaussian_1d, same_padding +from monai.utils import ensure_tuple_rep, optional_import + +_C, _ = optional_import("monai._C") +_C_CUDA, _ = optional_import("monai._C_CUDA") + +__all__ = ["SkipConnection", "Flatten", "GaussianFilter", "LLTM"] + + +class SkipConnection(nn.Module): + """ + Concats the forward pass input with the result from the given submodule. + """ + + def __init__(self, submodule, cat_dim: int = 1) -> None: + super().__init__() + self.submodule = submodule + self.cat_dim = cat_dim + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return torch.cat([x, self.submodule(x)], self.cat_dim) + + +class Flatten(nn.Module): + """ + Flattens the given input in the forward pass to be [B,-1] in shape. + """ + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x.view(x.size(0), -1) + + +class Reshape(nn.Module): + """ + Reshapes input tensors to the given shape (minus batch dimension), retaining original batch size. + """ + + def __init__(self, *shape: int) -> None: + """ + Given a shape list/tuple `shape` of integers (s0, s1, ... , sn), this layer will reshape input tensors of + shape (batch, s0 * s1 * ... * sn) to shape (batch, s0, s1, ... , sn). + + Args: + shape: list/tuple of integer shape dimensions + """ + super().__init__() + self.shape = (1,) + tuple(shape) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shape = list(self.shape) + shape[0] = x.shape[0] # done this way for Torchscript + return x.reshape(shape) + + +class GaussianFilter(nn.Module): + def __init__(self, spatial_dims: int, sigma: Union[Sequence[float], float], truncated: float = 4.0) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + must have shape (Batch, channels, H[, W, ...]). + sigma: std. + truncated: spreads how many stds. + """ + super().__init__() + self.spatial_dims = int(spatial_dims) + _sigma = ensure_tuple_rep(sigma, self.spatial_dims) + self.kernel = [ + torch.nn.Parameter(torch.as_tensor(gaussian_1d(s, truncated), dtype=torch.float), False) for s in _sigma + ] + self.padding = [cast(int, (same_padding(k.size()[0]))) for k in self.kernel] + self.conv_n = [F.conv1d, F.conv2d, F.conv3d][spatial_dims - 1] + for idx, param in enumerate(self.kernel): + self.register_parameter(f"kernel_{idx}", param) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape [Batch, chns, H, W, D]. + + Raises: + TypeError: When ``x`` is not a ``torch.Tensor``. + + """ + if not torch.is_tensor(x): + raise TypeError(f"x must be a torch.Tensor but is {type(x).__name__}.") + chns = x.shape[1] + sp_dim = self.spatial_dims + x = x.clone() # no inplace change of x + + def _conv(input_: torch.Tensor, d: int) -> torch.Tensor: + if d < 0: + return input_ + s = [1] * (sp_dim + 2) + s[d + 2] = -1 + kernel = self.kernel[d].reshape(s) + kernel = kernel.repeat([chns, 1] + [1] * sp_dim) + padding = [0] * sp_dim + padding[d] = self.padding[d] + return self.conv_n(input=_conv(input_, d - 1), weight=kernel, padding=padding, groups=chns) + + return _conv(x, sp_dim - 1) + + +class LLTMFunction(Function): + @staticmethod + def forward(ctx, input, weights, bias, old_h, old_cell): + ext = _C_CUDA if weights.is_cuda else _C + outputs = ext.lltm_forward(input, weights, bias, old_h, old_cell) + new_h, new_cell = outputs[:2] + variables = outputs[1:] + [weights] + ctx.save_for_backward(*variables) + + return new_h, new_cell + + @staticmethod + def backward(ctx, grad_h, grad_cell): + if grad_h.is_cuda: + outputs = _C_CUDA.lltm_backward(grad_h.contiguous(), grad_cell.contiguous(), *ctx.saved_tensors) + d_old_h, d_input, d_weights, d_bias, d_old_cell, d_gates = outputs + else: + outputs = _C.lltm_backward(grad_h.contiguous(), grad_cell.contiguous(), *ctx.saved_tensors) + d_old_h, d_input, d_weights, d_bias, d_old_cell = outputs + + return d_input, d_weights, d_bias, d_old_h, d_old_cell + + +class LLTM(nn.Module): + """ + This recurrent unit is similar to an LSTM, but differs in that it lacks a forget + gate and uses an Exponential Linear Unit (ELU) as its internal activation function. + Because this unit never forgets, call it LLTM, or Long-Long-Term-Memory unit. + It has both C++ and CUDA implementation, automatically switch according to the + target device where put this module to. + + Args: + input_features: size of input feature data + state_size: size of the state of recurrent unit + + Referring to: https://pytorch.org/tutorials/advanced/cpp_extension.html + """ + + def __init__(self, input_features: int, state_size: int): + super(LLTM, self).__init__() + self.input_features = input_features + self.state_size = state_size + self.weights = nn.Parameter(torch.empty(3 * state_size, input_features + state_size)) + self.bias = nn.Parameter(torch.empty(1, 3 * state_size)) + self.reset_parameters() + + def reset_parameters(self): + stdv = 1.0 / math.sqrt(self.state_size) + for weight in self.parameters(): + weight.data.uniform_(-stdv, +stdv) + + def forward(self, input, state): + return LLTMFunction.apply(input, self.weights, self.bias, *state) diff --git a/testbed/Project-MONAI__MONAI/monai/networks/layers/spatial_transforms.py b/testbed/Project-MONAI__MONAI/monai/networks/layers/spatial_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9fffa473fae6e39a82978b281beb5b7f0763c5 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/layers/spatial_transforms.py @@ -0,0 +1,159 @@ +# Copyright 2020 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 typing import Optional, Sequence, Union + +import torch +import torch.nn as nn + +from monai.networks import to_norm_affine +from monai.utils import GridSampleMode, GridSamplePadMode, ensure_tuple + +__all__ = ["AffineTransform"] + + +class AffineTransform(nn.Module): + def __init__( + self, + spatial_size: Optional[Union[Sequence[int], int]] = None, + normalized: bool = False, + mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, + padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.ZEROS, + align_corners: bool = False, + reverse_indexing: bool = True, + ) -> None: + """ + Apply affine transformations with a batch of affine matrices. + + When `normalized=False` and `reverse_indexing=True`, + it does the commonly used resampling in the 'pull' direction + following the ``scipy.ndimage.affine_transform`` convention. + In this case `theta` is equivalent to (ndim+1, ndim+1) input ``matrix`` of ``scipy.ndimage.affine_transform``, + operates on homogeneous coordinates. + See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html + + When `normalized=True` and `reverse_indexing=False`, + it applies `theta` to the normalized coordinates (coords. in the range of [-1, 1]) directly. + This is often used with `align_corners=False` to achieve resolution-agnostic resampling, + thus useful as a part of trainable modules such as the spatial transformer networks. + See also: https://pytorch.org/tutorials/intermediate/spatial_transformer_tutorial.html + + Args: + spatial_size: output spatial shape, the full output shape will be + `[N, C, *spatial_size]` where N and C are inferred from the `src` input of `self.forward`. + normalized: indicating whether the provided affine matrix `theta` is defined + for the normalized coordinates. If `normalized=False`, `theta` will be converted + to operate on normalized coordinates as pytorch affine_grid works with the normalized + coordinates. + mode: {``"bilinear"``, ``"nearest"``} + Interpolation mode to calculate output values. Defaults to ``"bilinear"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} + Padding mode for outside grid values. Defaults to ``"zeros"``. + See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample + align_corners: see also https://pytorch.org/docs/stable/nn.functional.html#grid-sample. + reverse_indexing: whether to reverse the spatial indexing of image and coordinates. + set to `False` if `theta` follows pytorch's default "D, H, W" convention. + set to `True` if `theta` follows `scipy.ndimage` default "i, j, k" convention. + """ + super().__init__() + self.spatial_size = ensure_tuple(spatial_size) if spatial_size is not None else None + self.normalized = normalized + self.mode: GridSampleMode = GridSampleMode(mode) + self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) + self.align_corners = align_corners + self.reverse_indexing = reverse_indexing + + def forward( + self, src: torch.Tensor, theta: torch.Tensor, spatial_size: Optional[Union[Sequence[int], int]] = None + ) -> torch.Tensor: + """ + ``theta`` must be an affine transformation matrix with shape + 3x3 or Nx3x3 or Nx2x3 or 2x3 for spatial 2D transforms, + 4x4 or Nx4x4 or Nx3x4 or 3x4 for spatial 3D transforms, + where `N` is the batch size. `theta` will be converted into float Tensor for the computation. + + Args: + src (array_like): image in spatial 2D or 3D (N, C, spatial_dims), + where N is the batch dim, C is the number of channels. + theta (array_like): Nx3x3, Nx2x3, 3x3, 2x3 for spatial 2D inputs, + Nx4x4, Nx3x4, 3x4, 4x4 for spatial 3D inputs. When the batch dimension is omitted, + `theta` will be repeated N times, N is the batch dim of `src`. + spatial_size: output spatial shape, the full output shape will be + `[N, C, *spatial_size]` where N and C are inferred from the `src`. + + Raises: + TypeError: When ``theta`` is not a ``torch.Tensor``. + ValueError: When ``theta`` is not one of [Nxdxd, dxd]. + ValueError: When ``theta`` is not one of [Nx3x3, Nx4x4]. + TypeError: When ``src`` is not a ``torch.Tensor``. + ValueError: When ``src`` spatially is not one of [2D, 3D]. + ValueError: When affine and image batch dimension differ. + + """ + # validate `theta` + if not torch.is_tensor(theta): + raise TypeError(f"theta must be torch.Tensor but is {type(theta).__name__}.") + if theta.dim() not in (2, 3): + raise ValueError(f"theta must be Nxdxd or dxd, got {theta.shape}.") + if theta.dim() == 2: + theta = theta[None] # adds a batch dim. + theta = theta.clone() # no in-place change of theta + theta_shape = tuple(theta.shape[1:]) + if theta_shape in ((2, 3), (3, 4)): # needs padding to dxd + pad_affine = torch.tensor([0, 0, 1] if theta_shape[0] == 2 else [0, 0, 0, 1]) + pad_affine = pad_affine.repeat(theta.shape[0], 1, 1).to(theta) + pad_affine.requires_grad = False + theta = torch.cat([theta, pad_affine], dim=1) + if tuple(theta.shape[1:]) not in ((3, 3), (4, 4)): + raise ValueError(f"theta must be Nx3x3 or Nx4x4, got {theta.shape}.") + + # validate `src` + if not torch.is_tensor(src): + raise TypeError(f"src must be torch.Tensor but is {type(src).__name__}.") + sr = src.dim() - 2 # input spatial rank + if sr not in (2, 3): + raise ValueError(f"Unsupported src dimension: {sr}, available options are [2, 3].") + + # set output shape + src_size = tuple(src.shape) + dst_size = src_size # default to the src shape + if self.spatial_size is not None: + dst_size = src_size[:2] + self.spatial_size + if spatial_size is not None: + dst_size = src_size[:2] + ensure_tuple(spatial_size) + + # reverse and normalise theta if needed + if not self.normalized: + theta = to_norm_affine( + affine=theta, src_size=src_size[2:], dst_size=dst_size[2:], align_corners=self.align_corners + ) + if self.reverse_indexing: + rev_idx = torch.as_tensor(range(sr - 1, -1, -1), device=src.device) + theta[:, :sr] = theta[:, rev_idx] + theta[:, :, :sr] = theta[:, :, rev_idx] + if (theta.shape[0] == 1) and src_size[0] > 1: + # adds a batch dim to `theta` in order to match `src` + theta = theta.repeat(src_size[0], 1, 1) + if theta.shape[0] != src_size[0]: + raise ValueError( + f"affine and image batch dimension must match, got affine={theta.shape[0]} image={src_size[0]}." + ) + + grid = nn.functional.affine_grid(theta=theta[:, :sr], size=list(dst_size), align_corners=self.align_corners) + dst = nn.functional.grid_sample( + input=src.contiguous(), + grid=grid, + mode=self.mode.value, + padding_mode=self.padding_mode.value, + align_corners=self.align_corners, + ) + return dst diff --git a/testbed/Project-MONAI__MONAI/monai/networks/nets/ahnet.py b/testbed/Project-MONAI__MONAI/monai/networks/nets/ahnet.py new file mode 100644 index 0000000000000000000000000000000000000000..e583750426647c541b85730686ebafeb3ecab00e --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/nets/ahnet.py @@ -0,0 +1,556 @@ +# Copyright 2020 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. + +import math +from typing import Optional, Sequence, Type, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from monai.networks.layers.factories import Act, Conv, Norm, Pool + + +class Bottleneck3x3x1(nn.Module): + + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + stride: Union[Sequence[int], int] = 1, + downsample: Optional[nn.Sequential] = None, + ) -> None: + + super(Bottleneck3x3x1, self).__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: Type[Union[nn.BatchNorm2d, nn.BatchNorm3d]] = Norm[Norm.BATCH, spatial_dims] + pool_type: Type[Union[nn.MaxPool2d, nn.MaxPool3d]] = Pool[Pool.MAX, spatial_dims] + relu_type: Type[nn.ReLU] = Act[Act.RELU] + + self.conv1 = conv_type(inplanes, planes, kernel_size=1, bias=False) + self.bn1 = norm_type(planes) + self.conv2 = conv_type( + planes, + planes, + kernel_size=(3, 3, 1)[-spatial_dims:], + stride=stride, + padding=(1, 1, 0)[-spatial_dims:], + bias=False, + ) + self.bn2 = norm_type(planes) + self.conv3 = conv_type(planes, planes * 4, kernel_size=1, bias=False) + self.bn3 = norm_type(planes * 4) + self.relu = relu_type(inplace=True) + self.downsample = downsample + self.stride = stride + self.pool = pool_type(kernel_size=(1, 1, 2)[-spatial_dims:], stride=(1, 1, 2)[-spatial_dims:]) + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + if out.size() != residual.size(): + out = self.pool(out) + + out += residual + out = self.relu(out) + + return out + + +class Projection(nn.Sequential): + def __init__(self, spatial_dims: int, num_input_features: int, num_output_features: int): + super(Projection, self).__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: Type[Union[nn.BatchNorm2d, nn.BatchNorm3d]] = Norm[Norm.BATCH, spatial_dims] + relu_type: Type[nn.ReLU] = Act[Act.RELU] + + self.add_module("norm", norm_type(num_input_features)) + self.add_module("relu", relu_type(inplace=True)) + self.add_module("conv", conv_type(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)) + + +class DenseBlock(nn.Sequential): + def __init__( + self, + spatial_dims: int, + num_layers: int, + num_input_features: int, + bn_size: int, + growth_rate: int, + dropout_prob: float, + ): + super(DenseBlock, self).__init__() + for i in range(num_layers): + layer = Pseudo3DLayer( + spatial_dims, num_input_features + i * growth_rate, growth_rate, bn_size, dropout_prob + ) + self.add_module("denselayer%d" % (i + 1), layer) + + +class UpTransition(nn.Sequential): + def __init__( + self, spatial_dims: int, num_input_features: int, num_output_features: int, upsample_mode: str = "trilinear" + ): + super(UpTransition, self).__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: Type[Union[nn.BatchNorm2d, nn.BatchNorm3d]] = Norm[Norm.BATCH, spatial_dims] + relu_type: Type[nn.ReLU] = Act[Act.RELU] + + self.add_module("norm", norm_type(num_input_features)) + self.add_module("relu", relu_type(inplace=True)) + self.add_module("conv", conv_type(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)) + if upsample_mode == "transpose": + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + self.add_module( + "up", conv_trans_type(num_output_features, num_output_features, kernel_size=2, stride=2, bias=False) + ) + else: + self.add_module("up", nn.Upsample(scale_factor=2, mode=upsample_mode, align_corners=True)) + + +class Final(nn.Sequential): + def __init__( + self, spatial_dims: int, num_input_features: int, num_output_features: int, upsample_mode: str = "trilinear" + ): + super(Final, self).__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: Type[Union[nn.BatchNorm2d, nn.BatchNorm3d]] = Norm[Norm.BATCH, spatial_dims] + relu_type: Type[nn.ReLU] = Act[Act.RELU] + + self.add_module("norm", norm_type(num_input_features)) + self.add_module("relu", relu_type(inplace=True)) + self.add_module( + "conv", + conv_type( + num_input_features, + num_output_features, + kernel_size=(3, 3, 1)[-spatial_dims:], + stride=1, + padding=(1, 1, 0)[-spatial_dims:], + bias=False, + ), + ) + if upsample_mode == "transpose": + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + self.add_module( + "up", conv_trans_type(num_output_features, num_output_features, kernel_size=2, stride=2, bias=False) + ) + else: + upsample_mode = "bilinear" if spatial_dims == 2 else "trilinear" + self.add_module("up", nn.Upsample(scale_factor=2, mode=upsample_mode, align_corners=True)) + + +class Pseudo3DLayer(nn.Module): + def __init__(self, spatial_dims: int, num_input_features: int, growth_rate: int, bn_size: int, dropout_prob: float): + super(Pseudo3DLayer, self).__init__() + # 1x1x1 + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: Type[Union[nn.BatchNorm2d, nn.BatchNorm3d]] = Norm[Norm.BATCH, spatial_dims] + relu_type: Type[nn.ReLU] = Act[Act.RELU] + + self.bn1 = norm_type(num_input_features) + self.relu1 = relu_type(inplace=True) + self.conv1 = conv_type(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False) + # 3x3x1 + self.bn2 = norm_type(bn_size * growth_rate) + self.relu2 = relu_type(inplace=True) + self.conv2 = conv_type( + bn_size * growth_rate, + growth_rate, + kernel_size=(3, 3, 1)[-spatial_dims:], + stride=1, + padding=(1, 1, 0)[-spatial_dims:], + bias=False, + ) + # 1x1x3 + self.bn3 = norm_type(growth_rate) + self.relu3 = relu_type(inplace=True) + self.conv3 = conv_type( + growth_rate, + growth_rate, + kernel_size=(1, 1, 3)[-spatial_dims:], + stride=1, + padding=(0, 0, 1)[-spatial_dims:], + bias=False, + ) + # 1x1x1 + self.bn4 = norm_type(growth_rate) + self.relu4 = relu_type(inplace=True) + self.conv4 = conv_type(growth_rate, growth_rate, kernel_size=1, stride=1, bias=False) + self.dropout_prob = dropout_prob + + def forward(self, x): + inx = x + x = self.bn1(x) + x = self.relu1(x) + x = self.conv1(x) + + x = self.bn2(x) + x = self.relu2(x) + x3x3x1 = self.conv2(x) + + x = self.bn3(x3x3x1) + x = self.relu3(x) + x1x1x3 = self.conv3(x) + + x = x3x3x1 + x1x1x3 + x = self.bn4(x) + x = self.relu4(x) + new_features = self.conv4(x) + + self.dropout_prob = 0 # Dropout will make trouble! + # since we use the train mode for inference + if self.dropout_prob > 0: + new_features = F.dropout(new_features, p=self.dropout_prob, training=self.training) + return torch.cat([inx, new_features], 1) + + +class PSP(nn.Module): + def __init__(self, spatial_dims: int, in_ch: int, upsample_mode: str = "trilinear"): + super(PSP, self).__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + pool_type: Type[Union[nn.MaxPool2d, nn.MaxPool3d]] = Pool[Pool.MAX, spatial_dims] + + self.pool64 = pool_type(kernel_size=(64, 64, 1)[-spatial_dims:], stride=(64, 64, 1)[-spatial_dims:]) + self.pool32 = pool_type(kernel_size=(32, 32, 1)[-spatial_dims:], stride=(32, 32, 1)[-spatial_dims:]) + self.pool16 = pool_type(kernel_size=(16, 16, 1)[-spatial_dims:], stride=(16, 16, 1)[-spatial_dims:]) + self.pool8 = pool_type(kernel_size=(8, 8, 1)[-spatial_dims:], stride=(8, 8, 1)[-spatial_dims:]) + + self.proj64 = conv_type( + in_ch, 1, kernel_size=(1, 1, 1)[-spatial_dims:], stride=1, padding=(1, 1, 0)[-spatial_dims:] + ) + self.proj32 = conv_type( + in_ch, 1, kernel_size=(1, 1, 1)[-spatial_dims:], stride=1, padding=(1, 1, 0)[-spatial_dims:] + ) + self.proj16 = conv_type( + in_ch, 1, kernel_size=(1, 1, 1)[-spatial_dims:], stride=1, padding=(1, 1, 0)[-spatial_dims:] + ) + self.proj8 = conv_type( + in_ch, 1, kernel_size=(1, 1, 1)[-spatial_dims:], stride=1, padding=(1, 1, 0)[-spatial_dims:] + ) + + self.upsample_mode = upsample_mode + self.spatial_dims = spatial_dims + if self.upsample_mode == "transpose": + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + self.up64 = conv_trans_type( + 1, + 1, + kernel_size=(64, 64, 1)[-spatial_dims:], + stride=(64, 64, 1)[-spatial_dims:], + padding=(64, 64, 0)[-spatial_dims:], + ) + self.up32 = conv_trans_type( + 1, + 1, + kernel_size=(32, 32, 1)[-spatial_dims:], + stride=(32, 32, 1)[-spatial_dims:], + padding=(32, 32, 0)[-spatial_dims:], + ) + self.up16 = conv_trans_type( + 1, + 1, + kernel_size=(16, 16, 1)[-spatial_dims:], + stride=(16, 16, 1)[-spatial_dims:], + padding=(16, 16, 0)[-spatial_dims:], + ) + self.up8 = conv_trans_type( + 1, + 1, + kernel_size=(8, 8, 1)[-spatial_dims:], + stride=(8, 8, 1)[-spatial_dims:], + padding=(8, 8, 0)[-spatial_dims:], + ) + + def forward(self, x): + if self.upsample_mode == "transpose": + x64 = self.up64(self.proj64(self.pool64(x))) + x32 = self.up32(self.proj32(self.pool32(x))) + x16 = self.up16(self.proj16(self.pool16(x))) + x8 = self.up8(self.proj8(self.pool8(x))) + else: + interpolate_size = tuple(x.size()[2:]) + x64 = F.interpolate( + self.proj64(self.pool64(x)), + size=interpolate_size, + mode=self.upsample_mode, + align_corners=True, + ) + x32 = F.interpolate( + self.proj32(self.pool32(x)), + size=interpolate_size, + mode=self.upsample_mode, + align_corners=True, + ) + x16 = F.interpolate( + self.proj16(self.pool16(x)), + size=interpolate_size, + mode=self.upsample_mode, + align_corners=True, + ) + x8 = F.interpolate( + self.proj8(self.pool8(x)), + size=interpolate_size, + mode=self.upsample_mode, + align_corners=True, + ) + x = torch.cat((x64, x32, x16, x8), dim=1) + return x + + +class AHNet(nn.Module): + """ + AHNet based on `Anisotropic Hybrid Network `_. + Adapted from `lsqshr's official code `_. + The model supports 2D or 3D inputs, as for the original 3D version. + To meet to requirements of the structure, the input size of the first ``dim-1`` dimensions should be divided + by 32 and no less than 128. If you need to use lower sizes, please reduce the largest blocks in PSP + module and change the ``num_input_features`` in Final module. + In addition, to utilize the "transpose" upsample mode, please ensure that the input size of the first ``dim-1`` dimensions + should be divisible by 128. In order to use pretrained weights from 2D FCN/MCFCN, please call the `copy_from` function, + for example: + + .. code-block:: python + + model = monai.networks.nets.AHNet(out_channels=2, upsample_mode='transpose') + model2d = monai.networks.blocks.FCN() + model.copy_from(model2d) + + Args: + layers: number of residual blocks for 4 layers of the network (layer1...layer4). Defaults to ``(3, 4, 6, 3)``. + spatial_dims: spatial dimension of the input data. Defaults to 3. + out_channels: number of output channels for the network. Defaults to 1. + upsample_mode: [``"transpose"``, ``"bilinear"``, ``"trilinear"``] + The mode of upsampling manipulations. + Using the last two modes cannot guarantee the model's reproducibility. Defaults to ``trilinear``. + + - ``"transpose"``, uses transposed convolution layers. + - ``"bilinear"``, uses bilinear interpolate. + - ``"trilinear"``, uses trilinear interpolate. + """ + + def __init__( + self, + layers: tuple = (3, 4, 6, 3), + spatial_dims: int = 3, + out_channels: int = 1, + upsample_mode: str = "trilinear", + ): + self.inplanes = 64 + super(AHNet, self).__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + norm_type = Norm[Norm.BATCH, spatial_dims] + pool_type: Type[Union[nn.MaxPool2d, nn.MaxPool3d]] = Pool[Pool.MAX, spatial_dims] + relu_type: Type[nn.ReLU] = Act[Act.RELU] + conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2] + norm2d_type: Type[nn.BatchNorm2d] = Norm[Norm.BATCH, 2] + + self.conv2d_type = conv2d_type + self.norm2d_type = norm2d_type + self.conv_type = conv_type + self.norm_type = norm_type + self.relu_type = relu_type + self.pool_type = pool_type + self.spatial_dims = spatial_dims + + assert spatial_dims == 2 or spatial_dims == 3, "spatial_dims can only be 2 or 3." + + self.conv1 = conv_type( + 1, + 64, + kernel_size=(7, 7, 3)[-spatial_dims:], + stride=(2, 2, 1)[-spatial_dims:], + padding=(3, 3, 1)[-spatial_dims:], + bias=False, + ) + self.pool1 = pool_type(kernel_size=(1, 1, 2)[-spatial_dims:], stride=(1, 1, 2)[-spatial_dims:]) + self.bn0 = norm_type(64) + self.relu = relu_type(inplace=True) + if upsample_mode == "transpose": + self.maxpool = pool_type(kernel_size=(2, 2, 2)[-spatial_dims:], stride=2) + else: + self.maxpool = pool_type(kernel_size=(3, 3, 3)[-spatial_dims:], stride=2, padding=1) + + self.layer1 = self._make_layer(Bottleneck3x3x1, 64, layers[0], stride=1) + self.layer2 = self._make_layer(Bottleneck3x3x1, 128, layers[1], stride=2) + self.layer3 = self._make_layer(Bottleneck3x3x1, 256, layers[2], stride=2) + self.layer4 = self._make_layer(Bottleneck3x3x1, 512, layers[3], stride=2) + + # Make the 3D dense decoder layers + densegrowth = 20 + densebn = 4 + ndenselayer = 3 + + num_init_features = 64 + noutres1 = 256 + noutres2 = 512 + noutres3 = 1024 + noutres4 = 2048 + + self.up0 = UpTransition(spatial_dims, noutres4, noutres3, upsample_mode) + self.dense0 = DenseBlock(spatial_dims, ndenselayer, noutres3, densebn, densegrowth, 0.0) + noutdense = noutres3 + ndenselayer * densegrowth + + self.up1 = UpTransition(spatial_dims, noutdense, noutres2, upsample_mode) + self.dense1 = DenseBlock(spatial_dims, ndenselayer, noutres2, densebn, densegrowth, 0.0) + noutdense1 = noutres2 + ndenselayer * densegrowth + + self.up2 = UpTransition(spatial_dims, noutdense1, noutres1, upsample_mode) + self.dense2 = DenseBlock(spatial_dims, ndenselayer, noutres1, densebn, densegrowth, 0.0) + noutdense2 = noutres1 + ndenselayer * densegrowth + + self.trans1 = Projection(spatial_dims, noutdense2, num_init_features) + self.dense3 = DenseBlock(spatial_dims, ndenselayer, num_init_features, densebn, densegrowth, 0.0) + noutdense3 = num_init_features + densegrowth * ndenselayer + + self.up3 = UpTransition(spatial_dims, noutdense3, num_init_features, upsample_mode) + self.dense4 = DenseBlock(spatial_dims, ndenselayer, num_init_features, densebn, densegrowth, 0.0) + noutdense4 = num_init_features + densegrowth * ndenselayer + + self.psp = PSP(spatial_dims, noutdense4, upsample_mode) + self.final = Final(spatial_dims, 4 + noutdense4, out_channels, upsample_mode) + + # Initialise parameters + for m in self.modules(): + if isinstance(m, (conv_type, conv_trans_type)): + n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + m.weight.data.normal_(0, math.sqrt(2.0 / n)) + elif isinstance(m, norm_type): + m.weight.data.fill_(1) + m.bias.data.zero_() + + def _make_layer( + self, + block: Type[Bottleneck3x3x1], + planes: int, + blocks: int, + stride: int = 1, + ) -> nn.Sequential: + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + self.conv_type( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=(stride, stride, 1)[: self.spatial_dims], + bias=False, + ), + self.pool_type( + kernel_size=(1, 1, stride)[: self.spatial_dims], stride=(1, 1, stride)[: self.spatial_dims] + ), + self.norm_type(planes * block.expansion), + ) + + layers = [] + layers.append( + block(self.spatial_dims, self.inplanes, planes, (stride, stride, 1)[: self.spatial_dims], downsample) + ) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append(block(self.spatial_dims, self.inplanes, planes)) + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + x = self.pool1(x) + x = self.bn0(x) + x = self.relu(x) + conv_x = x + x = self.maxpool(x) + pool_x = x + + fm1 = self.layer1(x) + fm2 = self.layer2(fm1) + fm3 = self.layer3(fm2) + fm4 = self.layer4(fm3) + + sum0 = self.up0(fm4) + fm3 + d0 = self.dense0(sum0) + + sum1 = self.up1(d0) + fm2 + d1 = self.dense1(sum1) + + sum2 = self.up2(d1) + fm1 + d2 = self.dense2(sum2) + + sum3 = self.trans1(d2) + pool_x + d3 = self.dense3(sum3) + + sum4 = self.up3(d3) + conv_x + d4 = self.dense4(sum4) + + psp = self.psp(d4) + x = torch.cat((psp, d4), dim=1) + return self.final(x) + + def copy_from(self, net): + # This method only supports for 3D AHNet, the input channel should be 1. + p2d, p3d = next(net.conv1.parameters()), next(self.conv1.parameters()) + + # From 64x3x7x7 -> 64x3x7x7x1 -> 64x1x7x7x3 + p3d.data = p2d.data.unsqueeze(dim=4).permute(0, 4, 2, 3, 1).clone() + + # Copy the initial module BN0 + copy_bn_param(net.bn0, self.bn0) + + # Copy layer1 to layer4 + for i in range(1, 5): + layer_num = "layer" + str(i) + + layer_2d = [] + layer_3d = [] + for m1 in vars(net)["_modules"][layer_num].modules(): + if isinstance(m1, (self.norm2d_type, self.conv2d_type)): + layer_2d.append(m1) + for m2 in vars(self)["_modules"][layer_num].modules(): + if isinstance(m2, (self.norm_type, self.conv_type)): + layer_3d.append(m2) + + for m1, m2 in zip(layer_2d, layer_3d): + if isinstance(m1, self.conv2d_type): + copy_conv_param(m1, m2) + if isinstance(m1, self.norm2d_type): + copy_bn_param(m1, m2) + + +def copy_conv_param(module2d, module3d): + for p2d, p3d in zip(module2d.parameters(), module3d.parameters()): + p3d.data[:] = p2d.data.unsqueeze(dim=4).clone()[:] + + +def copy_bn_param(module2d, module3d): + for p2d, p3d in zip(module2d.parameters(), module3d.parameters()): + p3d.data[:] = p2d.data[:] # Two parameter gamma and beta diff --git a/testbed/Project-MONAI__MONAI/monai/networks/nets/classifier.py b/testbed/Project-MONAI__MONAI/monai/networks/nets/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..2bfeca48a3b9638891b4301efa903762ab00d9ed --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/nets/classifier.py @@ -0,0 +1,140 @@ +# Copyright 2020 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 typing import Optional, Sequence, Union + +import torch +import torch.nn as nn + +from monai.networks.layers.factories import Act, Norm, split_args +from monai.networks.nets.regressor import Regressor + + +class Classifier(Regressor): + """ + Defines a classification network from Regressor by specifying the output shape as a single dimensional tensor + with size equal to the number of classes to predict. The final activation function can also be specified, eg. + softmax or sigmoid. + """ + + def __init__( + self, + in_shape: Sequence[int], + classes: int, + channels: Sequence[int], + strides: Sequence[int], + kernel_size: Union[Sequence[int], int] = 3, + num_res_units: int = 2, + act=Act.PRELU, + norm=Norm.INSTANCE, + dropout: Optional[float] = None, + bias: bool = True, + last_act: Optional[str] = None, + ) -> None: + """ + Args: + in_shape: tuple of integers stating the dimension of the input tensor (minus batch dimension) + classes: integer stating the dimension of the final output tensor + channels: tuple of integers stating the output channels of each convolutional layer + strides: tuple of integers stating the stride (downscale factor) of each convolutional layer + kernel_size: integer or tuple of integers stating size of convolutional kernels + num_res_units: integer stating number of convolutions in residual units, 0 means no residual units + act: name or type defining activation layers + norm: name or type defining normalization layers + dropout: optional float value in range [0, 1] stating dropout probability for layers, None for no dropout + bias: boolean stating if convolution layers should have a bias component + last_act: name defining the last activation layer + """ + super().__init__(in_shape, (classes,), channels, strides, kernel_size, num_res_units, act, norm, dropout, bias) + + if last_act is not None: + last_act_name, last_act_args = split_args(last_act) + last_act_type = Act[last_act_name] + + self.final.add_module("lastact", last_act_type(**last_act_args)) + + +class Discriminator(Classifier): + """ + Defines a discriminator network from Classifier with a single output value and sigmoid activation by default. This + is meant for use with GANs or other applications requiring a generic discriminator network. + """ + + def __init__( + self, + in_shape: Sequence[int], + channels: Sequence[int], + strides: Sequence[int], + kernel_size: Union[Sequence[int], int] = 3, + num_res_units: int = 2, + act=Act.PRELU, + norm=Norm.INSTANCE, + dropout: Optional[float] = 0.25, + bias: bool = True, + last_act=Act.SIGMOID, + ) -> None: + """ + Args: + in_shape: tuple of integers stating the dimension of the input tensor (minus batch dimension) + channels: tuple of integers stating the output channels of each convolutional layer + strides: tuple of integers stating the stride (downscale factor) of each convolutional layer + kernel_size: integer or tuple of integers stating size of convolutional kernels + num_res_units: integer stating number of convolutions in residual units, 0 means no residual units + act: name or type defining activation layers + norm: name or type defining normalization layers + dropout: optional float value in range [0, 1] stating dropout probability for layers, None for no dropout + bias: boolean stating if convolution layers should have a bias component + last_act: name defining the last activation layer + """ + super().__init__(in_shape, 1, channels, strides, kernel_size, num_res_units, act, norm, dropout, bias, last_act) + + +class Critic(Classifier): + """ + Defines a critic network from Classifier with a single output value and no final activation. The final layer is + `nn.Flatten` instead of `nn.Linear`, the final result is computed as the mean over the first dimension. This is + meant to be used with Wassertein GANs. + """ + + def __init__( + self, + in_shape: Sequence[int], + channels: Sequence[int], + strides: Sequence[int], + kernel_size: Union[Sequence[int], int] = 3, + num_res_units: int = 2, + act=Act.PRELU, + norm=Norm.INSTANCE, + dropout: Optional[float] = 0.25, + bias: bool = True, + ) -> None: + """ + Args: + in_shape: tuple of integers stating the dimension of the input tensor (minus batch dimension) + channels: tuple of integers stating the output channels of each convolutional layer + strides: tuple of integers stating the stride (downscale factor) of each convolutional layer + kernel_size: integer or tuple of integers stating size of convolutional kernels + num_res_units: integer stating number of convolutions in residual units, 0 means no residual units + act: name or type defining activation layers + norm: name or type defining normalization layers + dropout: optional float value in range [0, 1] stating dropout probability for layers, None for no dropout + bias: boolean stating if convolution layers should have a bias component + """ + super().__init__(in_shape, 1, channels, strides, kernel_size, num_res_units, act, norm, dropout, bias, None) + + def _get_final_layer(self, in_shape: Sequence[int]): + return nn.Flatten() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.net(x) + x = self.final(x) + x = x.mean(1) + return x.view((x.shape[0], -1)) diff --git a/testbed/Project-MONAI__MONAI/monai/networks/nets/densenet.py b/testbed/Project-MONAI__MONAI/monai/networks/nets/densenet.py new file mode 100644 index 0000000000000000000000000000000000000000..a202f708eeb6956e6297bb0eda01795787e53aeb --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/nets/densenet.py @@ -0,0 +1,212 @@ +# Copyright 2020 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 collections import OrderedDict +from typing import Callable, Sequence, Type, Union + +import torch +import torch.nn as nn + +from monai.networks.layers.factories import Conv, Dropout, Norm, Pool + + +class _DenseLayer(nn.Sequential): + def __init__( + self, spatial_dims: int, in_channels: int, growth_rate: int, bn_size: int, dropout_prob: float + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + in_channels: number of the input channel. + growth_rate: how many filters to add each layer (k in paper). + bn_size: multiplicative factor for number of bottle neck layers. + (i.e. bn_size * k features in the bottleneck layer) + dropout_prob: dropout rate after each dense layer. + """ + super(_DenseLayer, self).__init__() + + out_channels = bn_size * growth_rate + conv_type: Callable = Conv[Conv.CONV, spatial_dims] + norm_type: Callable = Norm[Norm.BATCH, spatial_dims] + dropout_type: Callable = Dropout[Dropout.DROPOUT, spatial_dims] + + self.add_module("norm1", norm_type(in_channels)) + self.add_module("relu1", nn.ReLU(inplace=True)) + self.add_module("conv1", conv_type(in_channels, out_channels, kernel_size=1, bias=False)) + + self.add_module("norm2", norm_type(out_channels)) + self.add_module("relu2", nn.ReLU(inplace=True)) + self.add_module("conv2", conv_type(out_channels, growth_rate, kernel_size=3, padding=1, bias=False)) + + if dropout_prob > 0: + self.add_module("dropout", dropout_type(dropout_prob)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + new_features = super(_DenseLayer, self).forward(x) + return torch.cat([x, new_features], 1) + + +class _DenseBlock(nn.Sequential): + def __init__( + self, spatial_dims: int, layers: int, in_channels: int, bn_size: int, growth_rate: int, dropout_prob: float + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + layers: number of layers in the block. + in_channels: number of the input channel. + bn_size: multiplicative factor for number of bottle neck layers. + (i.e. bn_size * k features in the bottleneck layer) + growth_rate: how many filters to add each layer (k in paper). + dropout_prob: dropout rate after each dense layer. + """ + super(_DenseBlock, self).__init__() + for i in range(layers): + layer = _DenseLayer(spatial_dims, in_channels, growth_rate, bn_size, dropout_prob) + in_channels += growth_rate + self.add_module("denselayer%d" % (i + 1), layer) + + +class _Transition(nn.Sequential): + def __init__(self, spatial_dims: int, in_channels: int, out_channels: int) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + in_channels: number of the input channel. + out_channels: number of the output classes. + """ + super(_Transition, self).__init__() + + conv_type: Callable = Conv[Conv.CONV, spatial_dims] + norm_type: Callable = Norm[Norm.BATCH, spatial_dims] + pool_type: Callable = Pool[Pool.AVG, spatial_dims] + + self.add_module("norm", norm_type(in_channels)) + self.add_module("relu", nn.ReLU(inplace=True)) + self.add_module("conv", conv_type(in_channels, out_channels, kernel_size=1, bias=False)) + self.add_module("pool", pool_type(kernel_size=2, stride=2)) + + +class DenseNet(nn.Module): + """ + Densenet based on: `Densely Connected Convolutional Networks `_. + Adapted from `PyTorch Hub 2D version + `_. + + Args: + spatial_dims: number of spatial dimensions of the input image. + in_channels: number of the input channel. + out_channels: number of the output classes. + init_features: number of filters in the first convolution layer. + growth_rate: how many filters to add each layer (k in paper). + block_config: how many layers in each pooling block. + bn_size: multiplicative factor for number of bottle neck layers. + (i.e. bn_size * k features in the bottleneck layer) + dropout_prob: dropout rate after each dense layer. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + init_features: int = 64, + growth_rate: int = 32, + block_config: Sequence[int] = (6, 12, 24, 16), + bn_size: int = 4, + dropout_prob: float = 0.0, + ) -> None: + + super(DenseNet, self).__init__() + + conv_type: Type[Union[nn.Conv1d, nn.Conv2d, nn.Conv3d]] = Conv[Conv.CONV, spatial_dims] + norm_type: Type[Union[nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d]] = Norm[Norm.BATCH, spatial_dims] + pool_type: Type[Union[nn.MaxPool1d, nn.MaxPool2d, nn.MaxPool3d]] = Pool[Pool.MAX, spatial_dims] + avg_pool_type: Type[Union[nn.AdaptiveAvgPool1d, nn.AdaptiveAvgPool2d, nn.AdaptiveAvgPool3d]] = Pool[ + Pool.ADAPTIVEAVG, spatial_dims + ] + + self.features = nn.Sequential( + OrderedDict( + [ + ("conv0", conv_type(in_channels, init_features, kernel_size=7, stride=2, padding=3, bias=False)), + ("norm0", norm_type(init_features)), + ("relu0", nn.ReLU(inplace=True)), + ("pool0", pool_type(kernel_size=3, stride=2, padding=1)), + ] + ) + ) + + in_channels = init_features + for i, num_layers in enumerate(block_config): + block = _DenseBlock( + spatial_dims=spatial_dims, + layers=num_layers, + in_channels=in_channels, + bn_size=bn_size, + growth_rate=growth_rate, + dropout_prob=dropout_prob, + ) + self.features.add_module(f"denseblock{i + 1}", block) + in_channels += num_layers * growth_rate + if i == len(block_config) - 1: + self.features.add_module("norm5", norm_type(in_channels)) + else: + _out_channels = in_channels // 2 + trans = _Transition(spatial_dims, in_channels=in_channels, out_channels=_out_channels) + self.features.add_module(f"transition{i + 1}", trans) + in_channels = _out_channels + + # pooling and classification + self.class_layers = nn.Sequential( + OrderedDict( + [ + ("relu", nn.ReLU(inplace=True)), + ("norm", avg_pool_type(1)), + ("flatten", nn.Flatten(1)), + ("class", nn.Linear(in_channels, out_channels)), + ] + ) + ) + + for m in self.modules(): + if isinstance(m, conv_type): + nn.init.kaiming_normal_(torch.as_tensor(m.weight)) + elif isinstance(m, norm_type): + nn.init.constant_(torch.as_tensor(m.weight), 1) + nn.init.constant_(torch.as_tensor(m.bias), 0) + elif isinstance(m, nn.Linear): + nn.init.constant_(torch.as_tensor(m.bias), 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.class_layers(x) + return x + + +def densenet121(**kwargs) -> DenseNet: + model = DenseNet(init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), **kwargs) + return model + + +def densenet169(**kwargs) -> DenseNet: + model = DenseNet(init_features=64, growth_rate=32, block_config=(6, 12, 32, 32), **kwargs) + return model + + +def densenet201(**kwargs) -> DenseNet: + model = DenseNet(init_features=64, growth_rate=32, block_config=(6, 12, 48, 32), **kwargs) + return model + + +def densenet264(**kwargs) -> DenseNet: + model = DenseNet(init_features=64, growth_rate=32, block_config=(6, 12, 64, 48), **kwargs) + return model diff --git a/testbed/Project-MONAI__MONAI/monai/networks/nets/regressor.py b/testbed/Project-MONAI__MONAI/monai/networks/nets/regressor.py new file mode 100644 index 0000000000000000000000000000000000000000..e049a56923db7ca302e9404784ebe8487421bf7f --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/nets/regressor.py @@ -0,0 +1,142 @@ +# Copyright 2020 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 typing import Optional, Sequence, Union + +import numpy as np +import torch +import torch.nn as nn + +from monai.networks.blocks import Convolution, ResidualUnit +from monai.networks.layers.convutils import calculate_out_shape, same_padding +from monai.networks.layers.factories import Act, Norm +from monai.networks.layers.simplelayers import Reshape +from monai.utils import ensure_tuple, ensure_tuple_rep + + +class Regressor(nn.Module): + """ + This defines a network for relating large-sized input tensors to small output tensors, ie. regressing large + values to a prediction. An output of a single dimension can be used as value regression or multi-label + classification prediction, an output of a single value can be used as a discriminator or critic prediction. + """ + + def __init__( + self, + in_shape: Sequence[int], + out_shape: Sequence[int], + channels: Sequence[int], + strides: Sequence[int], + kernel_size: Union[Sequence[int], int] = 3, + num_res_units: int = 2, + act=Act.PRELU, + norm=Norm.INSTANCE, + dropout: Optional[float] = None, + bias: bool = True, + ) -> None: + """ + Construct the regressor network with the number of layers defined by `channels` and `strides`. Inputs are + first passed through the convolutional layers in the forward pass, the output from this is then pass + through a fully connected layer to relate them to the final output tensor. + + Args: + in_shape: tuple of integers stating the dimension of the input tensor (minus batch dimension) + out_shape: tuple of integers stating the dimension of the final output tensor + channels: tuple of integers stating the output channels of each convolutional layer + strides: tuple of integers stating the stride (downscale factor) of each convolutional layer + kernel_size: integer or tuple of integers stating size of convolutional kernels + num_res_units: integer stating number of convolutions in residual units, 0 means no residual units + act: name or type defining activation layers + norm: name or type defining normalization layers + dropout: optional float value in range [0, 1] stating dropout probability for layers, None for no dropout + bias: boolean stating if convolution layers should have a bias component + """ + super().__init__() + + self.in_channels, *self.in_shape = ensure_tuple(in_shape) + self.dimensions = len(self.in_shape) + self.channels = ensure_tuple(channels) + self.strides = ensure_tuple(strides) + self.out_shape = ensure_tuple(out_shape) + self.kernel_size = ensure_tuple_rep(kernel_size, self.dimensions) + self.num_res_units = num_res_units + self.act = act + self.norm = norm + self.dropout = dropout + self.bias = bias + self.net = nn.Sequential() + + echannel = self.in_channels + + padding = same_padding(kernel_size) + + self.final_size = np.asarray(self.in_shape, np.int) + self.reshape = Reshape(*self.out_shape) + + # encode stage + for i, (c, s) in enumerate(zip(self.channels, self.strides)): + layer = self._get_layer(echannel, c, s, i == len(channels) - 1) + echannel = c # use the output channel number as the input for the next loop + self.net.add_module("layer_%i" % i, layer) + self.final_size = calculate_out_shape(self.final_size, kernel_size, s, padding) + + self.final = self._get_final_layer((echannel,) + self.final_size) + + def _get_layer( + self, in_channels: int, out_channels: int, strides: int, is_last: bool + ) -> Union[ResidualUnit, Convolution]: + """ + Returns a layer accepting inputs with `in_channels` number of channels and producing outputs of `out_channels` + number of channels. The `strides` indicates downsampling factor, ie. convolutional stride. If `is_last` + is True this is the final layer and is not expected to include activation and normalization layers. + """ + + layer: Union[ResidualUnit, Convolution] + + if self.num_res_units > 0: + layer = ResidualUnit( + subunits=self.num_res_units, + last_conv_only=is_last, + dimensions=self.dimensions, + in_channels=in_channels, + out_channels=out_channels, + strides=strides, + kernel_size=self.kernel_size, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + ) + else: + layer = Convolution( + conv_only=is_last, + dimensions=self.dimensions, + in_channels=in_channels, + out_channels=out_channels, + strides=strides, + kernel_size=self.kernel_size, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + ) + + return layer + + def _get_final_layer(self, in_shape: Sequence[int]): + linear = nn.Linear(int(np.product(in_shape)), int(np.product(self.out_shape))) + return nn.Sequential(nn.Flatten(), linear) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.net(x) + x = self.final(x) + x = self.reshape(x) + return x diff --git a/testbed/Project-MONAI__MONAI/monai/networks/utils.py b/testbed/Project-MONAI__MONAI/monai/networks/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..84846cd55dbe4f8a8d86db704f5845f77233b56b --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/networks/utils.py @@ -0,0 +1,234 @@ +# Copyright 2020 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. +""" +Utilities and types for defining networks, these depend on PyTorch. +""" + +import warnings +from typing import Any, Callable, Optional, Sequence, cast + +import torch +import torch.nn as nn + +from monai.utils import ensure_tuple_size + + +def one_hot(labels: torch.Tensor, num_classes: int, dtype: torch.dtype = torch.float, dim: int = 1) -> torch.Tensor: + """ + For a tensor `labels` of dimensions B1[spatial_dims], return a tensor of dimensions `BN[spatial_dims]` + for `num_classes` N number of classes. + + Example: + + For every value v = labels[b,1,h,w], the value in the result at [b,v,h,w] will be 1 and all others 0. + Note that this will include the background label, thus a binary mask should be treated as having 2 classes. + """ + assert labels.dim() > 0, "labels should have dim of 1 or more." + + # if `dim` is bigger, add singelton dim at the end + if labels.ndimension() < dim + 1: + shape = ensure_tuple_size(labels.shape, dim + 1, 1) + labels = labels.reshape(*shape) + + sh = list(labels.shape) + + assert sh[dim] == 1, "labels should have a channel with length equals to one." + sh[dim] = num_classes + + o = torch.zeros(size=sh, dtype=dtype, device=labels.device) + labels = o.scatter_(dim=dim, index=labels.long(), value=1) + + return labels + + +def slice_channels(tensor: torch.Tensor, *slicevals: Optional[int]) -> torch.Tensor: + slices = [slice(None)] * len(tensor.shape) + slices[1] = slice(*slicevals) + + return tensor[slices] + + +def predict_segmentation( + logits: torch.Tensor, mutually_exclusive: bool = False, threshold: float = 0.0 +) -> torch.Tensor: + """ + Given the logits from a network, computing the segmentation by thresholding all values above 0 + if multi-labels task, computing the `argmax` along the channel axis if multi-classes task, + logits has shape `BCHW[D]`. + + Args: + logits: raw data of model output. + mutually_exclusive: if True, `logits` will be converted into a binary matrix using + a combination of argmax, which is suitable for multi-classes task. Defaults to False. + threshold: thresholding the prediction values if multi-labels task. + """ + if not mutually_exclusive: + return (cast(torch.Tensor, logits >= threshold)).int() + else: + if logits.shape[1] == 1: + warnings.warn("single channel prediction, `mutually_exclusive=True` ignored, use threshold instead.") + return (cast(torch.Tensor, logits >= threshold)).int() + return logits.argmax(1, keepdim=True) + + +def normalize_transform( + shape: Sequence[int], + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + align_corners: bool = False, +) -> torch.Tensor: + """ + Compute an affine matrix according to the input shape. + The transform normalizes the homogeneous image coordinates to the + range of `[-1, 1]`. + + Args: + shape: input spatial shape + device: device on which the returned affine will be allocated. + dtype: data type of the returned affine + align_corners: if True, consider -1 and 1 to refer to the centers of the + corner pixels rather than the image corners. + See also: https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.grid_sample + """ + norm = torch.tensor(shape, dtype=torch.float64, device=device) # no in-place change + if align_corners: + norm[norm <= 1.0] = 2.0 + norm = 2.0 / (norm - 1.0) + norm = torch.diag(torch.cat((norm, torch.ones((1,), dtype=torch.float64, device=device)))) + norm[:-1, -1] = -1.0 + else: + norm[norm <= 0.0] = 2.0 + norm = 2.0 / norm + norm = torch.diag(torch.cat((norm, torch.ones((1,), dtype=torch.float64, device=device)))) + norm[:-1, -1] = 1.0 / torch.tensor(shape, dtype=torch.float64, device=device) - 1.0 + norm = norm.unsqueeze(0).to(dtype=dtype) + norm.requires_grad = False + return norm + + +def to_norm_affine( + affine: torch.Tensor, src_size: Sequence[int], dst_size: Sequence[int], align_corners: bool = False +) -> torch.Tensor: + """ + Given ``affine`` defined for coordinates in the pixel space, compute the corresponding affine + for the normalized coordinates. + + Args: + affine: Nxdxd batched square matrix + src_size: source image spatial shape + dst_size: target image spatial shape + align_corners: if True, consider -1 and 1 to refer to the centers of the + corner pixels rather than the image corners. + See also: https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.grid_sample + + Raises: + TypeError: When ``affine`` is not a ``torch.Tensor``. + ValueError: When ``affine`` is not Nxdxd. + ValueError: When ``src_size`` or ``dst_size`` dimensions differ from ``affine``. + + """ + if not torch.is_tensor(affine): + raise TypeError(f"affine must be a torch.Tensor but is {type(affine).__name__}.") + if affine.ndimension() != 3 or affine.shape[1] != affine.shape[2]: + raise ValueError(f"affine must be Nxdxd, got {tuple(affine.shape)}.") + sr = affine.shape[1] - 1 + if sr != len(src_size) or sr != len(dst_size): + raise ValueError(f"affine suggests {sr}D, got src={len(src_size)}D, dst={len(dst_size)}D.") + + src_xform = normalize_transform(src_size, affine.device, affine.dtype, align_corners) + dst_xform = normalize_transform(dst_size, affine.device, affine.dtype, align_corners) + new_affine = src_xform @ affine @ torch.inverse(dst_xform) + return new_affine + + +def normal_init( + m, std: float = 0.02, normal_func: Callable[[torch.Tensor, float, float], Any] = torch.nn.init.normal_ +) -> None: + """ + Initialize the weight and bias tensors of `m' and its submodules to values from a normal distribution with a + stddev of `std'. Weight tensors of convolution and linear modules are initialized with a mean of 0, batch + norm modules with a mean of 1. The callable `normal_func', used to assign values, should have the same arguments + as its default normal_(). This can be used with `nn.Module.apply` to visit submodules of a network. + """ + cname = m.__class__.__name__ + + if getattr(m, "weight", None) is not None and (cname.find("Conv") != -1 or cname.find("Linear") != -1): + normal_func(m.weight.data, 0.0, std) + if getattr(m, "bias", None) is not None: + nn.init.constant_(m.bias.data, 0.0) + + elif cname.find("BatchNorm") != -1: + normal_func(m.weight.data, 1.0, std) + nn.init.constant_(m.bias.data, 0) + + +def icnr_init(conv, upsample_factor, init=nn.init.kaiming_normal_): + """ + ICNR initialization for 2D/3D kernels adapted from Aitken et al.,2017 , "Checkerboard artifact free + sub-pixel convolution". + """ + out_channels, in_channels, *dims = conv.weight.shape + scale_factor = upsample_factor ** len(dims) + + oc2 = int(out_channels / scale_factor) + + kernel = torch.zeros([oc2, in_channels] + dims) + kernel = init(kernel) + kernel = kernel.transpose(0, 1) + kernel = kernel.reshape(oc2, in_channels, -1) + kernel = kernel.repeat(1, 1, scale_factor) + kernel = kernel.reshape([in_channels, out_channels] + dims) + kernel = kernel.transpose(0, 1) + conv.weight.data.copy_(kernel) + + +def pixelshuffle(x: torch.Tensor, dimensions: int, scale_factor: int) -> torch.Tensor: + """ + Apply pixel shuffle to the tensor `x` with spatial dimensions `dimensions` and scaling factor `scale_factor`. + + See: Shi et al., 2016, "Real-Time Single Image and Video Super-Resolution + Using a nEfficient Sub-Pixel Convolutional Neural Network." + + See: Aitken et al., 2017, "Checkerboard artifact free sub-pixel convolution". + + Args: + x: Input tensor + dimensions: number of spatial dimensions, typically 2 or 3 for 2D or 3D + scale_factor: factor to rescale the spatial dimensions by, must be >=1 + + Returns: + Reshuffled version of `x`. + + Raises: + ValueError: When input channels of `x` are not divisible by (scale_factor ** dimensions) + """ + + dim, factor = dimensions, scale_factor + input_size = list(x.size()) + batch_size, channels = input_size[:2] + scale_divisor = factor ** dim + + if channels % scale_divisor != 0: + raise ValueError( + f"Number of input channels ({channels}) must be evenly \ + divisible by scale_factor ** dimensions ({scale_divisor})." + ) + + org_channels = channels // scale_divisor + output_size = [batch_size, org_channels] + [d * factor for d in input_size[2:]] + + indices = tuple(range(2, 2 + 2 * dim)) + indices_factor, indices_dim = indices[:dim], indices[dim:] + permute_indices = (0, 1) + sum(zip(indices_dim, indices_factor), ()) + + x = x.reshape(batch_size, org_channels, *([factor] * dim + input_size[2:])) + x = x.permute(permute_indices).reshape(output_size) + return x diff --git a/testbed/Project-MONAI__MONAI/monai/transforms/croppad/__init__.py b/testbed/Project-MONAI__MONAI/monai/transforms/croppad/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0044e3563d6ecc8c57373a7d62665bf07ba91c7 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/transforms/croppad/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2020 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. diff --git a/testbed/Project-MONAI__MONAI/monai/transforms/utility/array.py b/testbed/Project-MONAI__MONAI/monai/transforms/utility/array.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c74b9b81604678c7e6d2536dc42395a7ef2cac --- /dev/null +++ b/testbed/Project-MONAI__MONAI/monai/transforms/utility/array.py @@ -0,0 +1,503 @@ +# Copyright 2020 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. +""" +A collection of "vanilla" transforms for utility functions +https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design +""" + +import logging +import time +from typing import Callable, Optional, Sequence, Tuple, TypeVar, Union + +import numpy as np +import torch + +from monai.transforms.compose import Transform +from monai.transforms.utils import map_binary_to_indices +from monai.utils import ensure_tuple + +# Generic type which can represent either a numpy.ndarray or a torch.Tensor +# Unlike Union can create a dependence between parameter(s) / return(s) +NdarrayTensor = TypeVar("NdarrayTensor", np.ndarray, torch.Tensor) + + +class Identity(Transform): + """ + Convert the input to an np.ndarray, if input data is np.ndarray or subclasses, return unchanged data. + As the output value is same as input, it can be used as a testing tool to verify the transform chain, + Compose or transform adaptor, etc. + + """ + + def __call__(self, img: Union[np.ndarray, torch.Tensor]) -> np.ndarray: + """ + Apply the transform to `img`. + """ + return np.asanyarray(img) + + +class AsChannelFirst(Transform): + """ + Change the channel dimension of the image to the first dimension. + + Most of the image transformations in ``monai.transforms`` + assume the input image is in the channel-first format, which has the shape + (num_channels, spatial_dim_1[, spatial_dim_2, ...]). + + This transform could be used to convert, for example, a channel-last image array in shape + (spatial_dim_1[, spatial_dim_2, ...], num_channels) into the channel-first format, + so that the multidimensional image array can be correctly interpreted by the other transforms. + + Args: + channel_dim: which dimension of input image is the channel, default is the last dimension. + """ + + def __init__(self, channel_dim: int = -1) -> None: + assert isinstance(channel_dim, int) and channel_dim >= -1, "invalid channel dimension." + self.channel_dim = channel_dim + + def __call__(self, img: np.ndarray) -> np.ndarray: + """ + Apply the transform to `img`. + """ + return np.moveaxis(img, self.channel_dim, 0) + + +class AsChannelLast(Transform): + """ + Change the channel dimension of the image to the last dimension. + + Some of other 3rd party transforms assume the input image is in the channel-last format with shape + (spatial_dim_1[, spatial_dim_2, ...], num_channels). + + This transform could be used to convert, for example, a channel-first image array in shape + (num_channels, spatial_dim_1[, spatial_dim_2, ...]) into the channel-last format, + so that MONAI transforms can construct a chain with other 3rd party transforms together. + + Args: + channel_dim: which dimension of input image is the channel, default is the first dimension. + """ + + def __init__(self, channel_dim: int = 0) -> None: + assert isinstance(channel_dim, int) and channel_dim >= -1, "invalid channel dimension." + self.channel_dim = channel_dim + + def __call__(self, img: np.ndarray) -> np.ndarray: + """ + Apply the transform to `img`. + """ + return np.moveaxis(img, self.channel_dim, -1) + + +class AddChannel(Transform): + """ + Adds a 1-length channel dimension to the input image. + + Most of the image transformations in ``monai.transforms`` + assumes the input image is in the channel-first format, which has the shape + (num_channels, spatial_dim_1[, spatial_dim_2, ...]). + + This transform could be used, for example, to convert a (spatial_dim_1[, spatial_dim_2, ...]) + spatial image into the channel-first format so that the + multidimensional image array can be correctly interpreted by the other + transforms. + """ + + def __call__(self, img: NdarrayTensor) -> NdarrayTensor: + """ + Apply the transform to `img`. + """ + return img[None] + + +class RepeatChannel(Transform): + """ + Repeat channel data to construct expected input shape for models. + The `repeats` count includes the origin data, for example: + ``RepeatChannel(repeats=2)([[1, 2], [3, 4]])`` generates: ``[[1, 2], [1, 2], [3, 4], [3, 4]]`` + + Args: + repeats: the number of repetitions for each element. + """ + + def __init__(self, repeats: int) -> None: + assert repeats > 0, "repeats count must be greater than 0." + self.repeats = repeats + + def __call__(self, img: np.ndarray) -> np.ndarray: + """ + Apply the transform to `img`, assuming `img` is a "channel-first" array. + """ + return np.repeat(img, self.repeats, 0) + + +class CastToType(Transform): + """ + Cast the Numpy data to specified numpy data type, or cast the PyTorch Tensor to + specified PyTorch data type. + """ + + def __init__(self, dtype: Union[np.dtype, torch.dtype] = np.float32) -> None: + """ + Args: + dtype: convert image to this data type, default is `np.float32`. + """ + self.dtype = dtype + + def __call__( + self, img: Union[np.ndarray, torch.Tensor], dtype: Optional[Union[np.dtype, torch.dtype]] = None + ) -> Union[np.ndarray, torch.Tensor]: + """ + Apply the transform to `img`, assuming `img` is a numpy array or PyTorch Tensor. + + Args: + dtype: convert image to this data type, default is `self.dtype`. + + Raises: + TypeError: When ``img`` type is not in ``Union[numpy.ndarray, torch.Tensor]``. + + """ + if isinstance(img, np.ndarray): + return img.astype(self.dtype if dtype is None else dtype) + elif torch.is_tensor(img): + return torch.as_tensor(img, dtype=self.dtype if dtype is None else dtype) + else: + raise TypeError(f"img must be one of (numpy.ndarray, torch.Tensor) but is {type(img).__name__}.") + + +class ToTensor(Transform): + """ + Converts the input image to a tensor without applying any other transformations. + """ + + def __call__(self, img: Union[np.ndarray, torch.Tensor]) -> torch.Tensor: + """ + Apply the transform to `img` and make it contiguous. + """ + if torch.is_tensor(img): + return img.contiguous() + return torch.as_tensor(np.ascontiguousarray(img)) + + +class ToNumpy(Transform): + """ + Converts the input Tensor data to numpy array. + """ + + def __call__(self, img: Union[np.ndarray, torch.Tensor]) -> np.ndarray: + """ + Apply the transform to `img` and make it contiguous. + """ + if torch.is_tensor(img): + img = img.detach().cpu().numpy() + return np.ascontiguousarray(img) + + +class Transpose(Transform): + """ + Transposes the input image based on the given `indices` dimension ordering. + """ + + def __init__(self, indices: Optional[Sequence[int]]) -> None: + self.indices = None if indices is None else tuple(indices) + + def __call__(self, img: np.ndarray) -> np.ndarray: + """ + Apply the transform to `img`. + """ + return img.transpose(self.indices) + + +class SqueezeDim(Transform): + """ + Squeeze a unitary dimension. + """ + + def __init__(self, dim: Optional[int] = 0) -> None: + """ + Args: + dim: dimension to be squeezed. Default = 0 + "None" works when the input is numpy array. + + Raises: + TypeError: When ``dim`` is not an ``Optional[int]``. + + """ + if dim is not None and not isinstance(dim, int): + raise TypeError(f"dim must be None or a int but is {type(dim).__name__}.") + self.dim = dim + + def __call__(self, img: NdarrayTensor) -> NdarrayTensor: + """ + Args: + img: numpy arrays with required dimension `dim` removed + """ + return img.squeeze(self.dim) + + +class DataStats(Transform): + """ + Utility transform to show the statistics of data for debug or analysis. + It can be inserted into any place of a transform chain and check results of previous transforms. + It support both `numpy.ndarray` and `torch.tensor` as input data, + so it can be used in pre-processing and post-processing. + """ + + def __init__( + self, + prefix: str = "Data", + data_shape: bool = True, + value_range: bool = True, + data_value: bool = False, + additional_info: Optional[Callable] = None, + logger_handler: Optional[logging.Handler] = None, + ) -> None: + """ + Args: + prefix: will be printed in format: "{prefix} statistics". + data_shape: whether to show the shape of input data. + value_range: whether to show the value range of input data. + data_value: whether to show the raw value of input data. + a typical example is to print some properties of Nifti image: affine, pixdim, etc. + additional_info: user can define callable function to extract additional info from input data. + logger_handler: add additional handler to output data: save to file, etc. + add existing python logging handlers: https://docs.python.org/3/library/logging.handlers.html + + Raises: + TypeError: When ``additional_info`` is not an ``Optional[Callable]``. + + """ + assert isinstance(prefix, str), "prefix must be a string." + self.prefix = prefix + self.data_shape = data_shape + self.value_range = value_range + self.data_value = data_value + if additional_info is not None and not callable(additional_info): + raise TypeError(f"additional_info must be None or callable but is {type(additional_info).__name__}.") + self.additional_info = additional_info + self.output: Optional[str] = None + logging.basicConfig(level=logging.NOTSET) + self._logger = logging.getLogger("DataStats") + if logger_handler is not None: + self._logger.addHandler(logger_handler) + + def __call__( + self, + img: NdarrayTensor, + prefix: Optional[str] = None, + data_shape: Optional[bool] = None, + value_range: Optional[bool] = None, + data_value: Optional[bool] = None, + additional_info: Optional[Callable] = None, + ) -> NdarrayTensor: + """ + Apply the transform to `img`, optionally take arguments similar to the class constructor. + """ + lines = [f"{prefix or self.prefix} statistics:"] + + if self.data_shape if data_shape is None else data_shape: + lines.append(f"Shape: {img.shape}") + if self.value_range if value_range is None else value_range: + if isinstance(img, np.ndarray): + lines.append(f"Value range: ({np.min(img)}, {np.max(img)})") + elif torch.is_tensor(img): + lines.append(f"Value range: ({torch.min(img)}, {torch.max(img)})") + else: + lines.append(f"Value range: (not a PyTorch or Numpy array, type: {type(img)})") + if self.data_value if data_value is None else data_value: + lines.append(f"Value: {img}") + additional_info = self.additional_info if additional_info is None else additional_info + if additional_info is not None: + lines.append(f"Additional info: {additional_info(img)}") + separator = "\n" + self.output = f"{separator.join(lines)}" + self._logger.debug(self.output) + + return img + + +class SimulateDelay(Transform): + """ + This is a pass through transform to be used for testing purposes. It allows + adding fake behaviors that are useful for testing purposes to simulate + how large datasets behave without needing to test on large data sets. + + For example, simulating slow NFS data transfers, or slow network transfers + in testing by adding explicit timing delays. Testing of small test data + can lead to incomplete understanding of real world issues, and may lead + to sub-optimal design choices. + """ + + def __init__(self, delay_time: float = 0.0) -> None: + """ + Args: + delay_time: The minimum amount of time, in fractions of seconds, + to accomplish this delay task. + """ + super().__init__() + self.delay_time: float = delay_time + + def __call__(self, img: NdarrayTensor, delay_time: Optional[float] = None) -> NdarrayTensor: + """ + Args: + img: data remain unchanged throughout this transform. + delay_time: The minimum amount of time, in fractions of seconds, + to accomplish this delay task. + """ + time.sleep(self.delay_time if delay_time is None else delay_time) + return img + + +class Lambda(Transform): + """ + Apply a user-defined lambda as a transform. + + For example: + + .. code-block:: python + :emphasize-lines: 2 + + image = np.ones((10, 2, 2)) + lambd = Lambda(func=lambda x: x[:4, :, :]) + print(lambd(image).shape) + (4, 2, 2) + + Args: + func: Lambda/function to be applied. + + Raises: + TypeError: When ``func`` is not an ``Optional[Callable]``. + + """ + + def __init__(self, func: Optional[Callable] = None) -> None: + if func is not None and not callable(func): + raise TypeError(f"func must be None or callable but is {type(func).__name__}.") + self.func = func + + def __call__(self, img: Union[np.ndarray, torch.Tensor], func: Optional[Callable] = None): + """ + Apply `self.func` to `img`. + + Args: + func: Lambda/function to be applied. Defaults to `self.func`. + + Raises: + TypeError: When ``func`` is not an ``Optional[Callable]``. + ValueError: When ``func=None`` and ``self.func=None``. Incompatible values. + + """ + if func is not None: + if not callable(func): + raise TypeError(f"func must be None or callable but is {type(func).__name__}.") + return func(img) + if self.func is not None: + return self.func(img) + else: + raise ValueError("Incompatible values: func=None and self.func=None.") + + +class LabelToMask(Transform): + """ + Convert labels to mask for other tasks. A typical usage is to convert segmentation labels + to mask data to pre-process images and then feed the images into classification network. + It can support single channel labels or One-Hot labels with specified `select_labels`. + For example, users can select `label value = [2, 3]` to construct mask data, or select the + second and the third channels of labels to construct mask data. + The output mask data can be a multiple channels binary data or a single channel binary + data that merges all the channels. + + Args: + select_labels: labels to generate mask from. for 1 channel label, the `select_labels` + is the expected label values, like: [1, 2, 3]. for One-Hot format label, the + `select_labels` is the expected channel indices. + merge_channels: whether to use `np.any()` to merge the result on channel dim. if yes, + will return a single channel mask with binary data. + + """ + + def __init__( + self, + select_labels: Union[Sequence[int], int], + merge_channels: bool = False, + ) -> None: # pytype: disable=annotation-type-mismatch # pytype bug with bool + self.select_labels = ensure_tuple(select_labels) + self.merge_channels = merge_channels + + def __call__( + self, + img: np.ndarray, + select_labels: Optional[Union[Sequence[int], int]] = None, + merge_channels: Optional[bool] = None, + ) -> np.ndarray: + """ + Args: + select_labels: labels to generate mask from. for 1 channel label, the `select_labels` + is the expected label values, like: [1, 2, 3]. for One-Hot format label, the + `select_labels` is the expected channel indices. + merge_channels: whether to use `np.any()` to merge the result on channel dim. if yes, + will return a single channel mask with binary data. + """ + if select_labels is None: + select_labels = self.select_labels + else: + select_labels = ensure_tuple(select_labels) + if merge_channels is None: + merge_channels = self.merge_channels + + if img.shape[0] > 1: + data = img[[*(select_labels)]] + else: + data = np.where(np.in1d(img, select_labels), True, False).reshape(img.shape) + + return np.any(data, axis=0, keepdims=True) if merge_channels else data + + +class FgBgToIndices(Transform): + def __init__(self, image_threshold: float = 0.0, output_shape: Optional[Sequence[int]] = None) -> None: + """ + Compute foreground and background of the input label data, return the indices. + If no output_shape specified, output data will be 1 dim indices after flattening. + This transform can help pre-compute foreground and background regions for other transforms. + A typical usage is to randomly select foreground and background to crop. + The main logic is based on :py:class:`monai.transforms.utils.map_binary_to_indices`. + + Args: + image_threshold: if enabled `image` at runtime, use ``image > image_threshold`` to + determine the valid image content area and select background only in this area. + output_shape: expected shape of output indices. if not None, unravel indices to specified shape. + + """ + self.image_threshold = image_threshold + self.output_shape = output_shape + + def __call__( + self, + label: np.ndarray, + image: Optional[np.ndarray] = None, + output_shape: Optional[Sequence[int]] = None, + ) -> Tuple[np.ndarray, np.ndarray]: + """ + Args: + label: input data to compute foreground and background indices. + image: if image is not None, use ``label = 0 & image > image_threshold`` + to define background. so the output items will not map to all the voxels in the label. + output_shape: expected shape of output indices. if None, use `self.output_shape` instead. + + """ + if output_shape is None: + output_shape = self.output_shape + fg_indices, bg_indices = map_binary_to_indices(label, image, self.image_threshold) + if output_shape is not None: + fg_indices = np.stack([np.unravel_index(i, output_shape) for i in fg_indices]) + bg_indices = np.stack([np.unravel_index(i, output_shape) for i in bg_indices]) + + return fg_indices, bg_indices