diff --git a/source_code/SegMamba/monai/_extensions/gmm/gmm_cuda.cu b/source_code/SegMamba/monai/_extensions/gmm/gmm_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..0c808d3165d29c4e646bb0390e7ccb62a84a1f6e --- /dev/null +++ b/source_code/SegMamba/monai/_extensions/gmm/gmm_cuda.cu @@ -0,0 +1,516 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include + +#include "gmm.h" + +#include "gmm_cuda_linalg.cuh" + +#define EPSILON 1e-5 +#define BLOCK_SIZE 32 +#define TILE(SIZE, STRIDE) ((((SIZE)-1) / (STRIDE)) + 1) +#ifdef __HIP_PLATFORM_AMD__ +#define __SHFL_DOWN(a, b) __shfl_down(a, b) +#define __SHFL_XOR(a, b) __shfl_xor(a, b) +#else +#define __SHFL_DOWN(a, b) __shfl_down_sync(0xffffffff, a, b) +#define __SHFL_XOR(a, b) __shfl_xor_sync(0xffffffff, a, b) +#endif + +template +__global__ void CovarianceReductionKernel( + int gaussian_index, + const float* g_image, + const int* g_alpha, + float* g_matrices, + int element_count) { + constexpr int block_size = warp_count * 32; + + __shared__ float s_matrix_component[warp_count]; + + int batch_index = blockIdx.z; + + const float* g_batch_image = g_image + batch_index * element_count * CHANNEL_COUNT; + const int* g_batch_alpha = g_alpha + batch_index * element_count; + float* g_batch_matrices = g_matrices + batch_index * GMM_COUNT * GMM_COMPONENT_COUNT * gridDim.x; + + int local_index = threadIdx.x; + int block_index = blockIdx.x; + int warp_index = local_index >> 5; + int lane_index = local_index & 31; + int global_index = local_index + block_index * block_size * load_count; + int matrix_offset = (gaussian_index * gridDim.x + block_index) * GMM_COMPONENT_COUNT; + + float matrix[MATRIX_COMPONENT_COUNT]; + + for (int i = 0; i < MATRIX_COMPONENT_COUNT; i++) { + matrix[i] = 0; + } + + for (int load = 0; load < load_count; load++) { + global_index += load * block_size; + + if (global_index < element_count) { + int my_alpha = g_batch_alpha[global_index]; + + if (my_alpha != -1) { + if (gaussian_index == (my_alpha & 15) + (my_alpha >> 4) * MIXTURE_COUNT) { + float feature[CHANNEL_COUNT + 1]; + + feature[0] = 1; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + feature[i + 1] = g_batch_image[global_index + i * element_count]; + } + + for (int index = 0, i = 0; i < CHANNEL_COUNT + 1; i++) { + for (int j = i; j < CHANNEL_COUNT + 1; j++, index++) { + matrix[index] += feature[i] * feature[j]; + } + } + } + } + } + } + + __syncthreads(); + + for (int i = 0; i < MATRIX_COMPONENT_COUNT; i++) { + float matrix_component = matrix[i]; + matrix_component += __SHFL_DOWN(matrix_component, 16); + matrix_component += __SHFL_DOWN(matrix_component, 8); + matrix_component += __SHFL_DOWN(matrix_component, 4); + matrix_component += __SHFL_DOWN(matrix_component, 2); + matrix_component += __SHFL_DOWN(matrix_component, 1); + if (lane_index == 0) { + s_matrix_component[warp_index] = matrix_component; + } + + __syncthreads(); + + if (warp_index == 0) { + matrix_component = s_matrix_component[lane_index]; + if (warp_count >= 32) { + matrix_component += __SHFL_DOWN(matrix_component, 16); + } + if (warp_count >= 16) { + matrix_component += __SHFL_DOWN(matrix_component, 8); + } + if (warp_count >= 8) { + matrix_component += __SHFL_DOWN(matrix_component, 4); + } + if (warp_count >= 4) { + matrix_component += __SHFL_DOWN(matrix_component, 2); + } + if (warp_count >= 2) { + matrix_component += __SHFL_DOWN(matrix_component, 1); + } + if (lane_index == 0) { + g_batch_matrices[matrix_offset + i] = matrix_component; + } + } + + __syncthreads(); + } +} + +template +__global__ void CovarianceFinalizationKernel(const float* g_matrices, float* g_gmm, int matrix_count) { + constexpr int block_size = warp_count * 32; + + __shared__ float s_matrix_component[warp_count]; + __shared__ float s_gmm[GMM_COMPONENT_COUNT]; + + int batch_index = blockIdx.z; + + const float* g_batch_matrices = g_matrices + batch_index * GMM_COUNT * GMM_COMPONENT_COUNT * matrix_count; + float* g_batch_gmm = g_gmm + batch_index * GMM_COUNT * GMM_COMPONENT_COUNT; + + int local_index = threadIdx.x; + int warp_index = local_index >> 5; + int lane_index = local_index & 31; + int gmm_index = blockIdx.x; + int matrix_offset = gmm_index * matrix_count; + + int load_count = TILE(matrix_count, block_size); + + float norm_factor = 1.0f; + + for (int index = 0, i = 0; i < CHANNEL_COUNT + 1; i++) { + for (int j = i; j < CHANNEL_COUNT + 1; j++, index++) { + float matrix_component = 0.0f; + + for (int load = 0; load < load_count; load++) { + int matrix_index = local_index + load * block_size; + + if (matrix_index < matrix_count) { + matrix_component += g_batch_matrices[(matrix_offset + matrix_index) * GMM_COMPONENT_COUNT + index]; + } + } + matrix_component += __SHFL_DOWN(matrix_component, 16); + matrix_component += __SHFL_DOWN(matrix_component, 8); + matrix_component += __SHFL_DOWN(matrix_component, 4); + matrix_component += __SHFL_DOWN(matrix_component, 2); + matrix_component += __SHFL_DOWN(matrix_component, 1); + if (lane_index == 0) { + s_matrix_component[warp_index] = matrix_component; + } + + __syncthreads(); + + if (warp_index == 0) { + matrix_component = s_matrix_component[lane_index]; + if (warp_count >= 32) { + matrix_component += __SHFL_DOWN(matrix_component, 16); + } + if (warp_count >= 16) { + matrix_component += __SHFL_DOWN(matrix_component, 8); + } + if (warp_count >= 8) { + matrix_component += __SHFL_DOWN(matrix_component, 4); + } + if (warp_count >= 4) { + matrix_component += __SHFL_DOWN(matrix_component, 2); + } + if (warp_count >= 2) { + matrix_component += __SHFL_DOWN(matrix_component, 1); + } + if (lane_index == 0) { + float constant = i == 0 ? 0.0f : s_gmm[i] * s_gmm[j]; + + if (i != 0 && i == j) { + constant -= EPSILON; + } + + s_gmm[index] = norm_factor * matrix_component - constant; + + if (index == 0 && matrix_component > 0) { + norm_factor = 1.0f / matrix_component; + } + } + } + + __syncthreads(); + } + } + + float* matrix = s_gmm + (CHANNEL_COUNT + 1); + float* det_ptr = s_gmm + MATRIX_COMPONENT_COUNT; + + if (local_index == 0) { + float square_mat[CHANNEL_COUNT][CHANNEL_COUNT]; + float cholesky_mat[CHANNEL_COUNT][CHANNEL_COUNT]; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + for (int j = 0; j < CHANNEL_COUNT; j++) { + square_mat[i][j] = 0.0f; + cholesky_mat[i][j] = 0.0f; + } + } + + to_square(matrix, square_mat); + cholesky(square_mat, cholesky_mat); + + *det_ptr = chol_det(cholesky_mat); + + if (invert_matrix) { + chol_inv(cholesky_mat, square_mat); + to_triangle(square_mat, matrix); + } + } + + if (local_index < GMM_COMPONENT_COUNT) { + g_batch_gmm[gmm_index * GMM_COMPONENT_COUNT + local_index] = s_gmm[local_index]; + } +} + +struct GMMSplit_t { + int idx; + float threshold; + float eigenvector[CHANNEL_COUNT]; +}; + +// 1 Block, 32xMIXTURE_COUNT +__global__ void GMMFindSplit(GMMSplit_t* gmmSplit, int gmmK, float* gmm) { + int batch_index = blockIdx.z; + + float* g_batch_gmm = gmm + batch_index * GMM_COUNT * GMM_COMPONENT_COUNT; + GMMSplit_t* g_batch_gmmSplit = gmmSplit + batch_index * MIXTURE_COUNT; + + int gmm_idx = threadIdx.x * MIXTURE_COUNT + threadIdx.y; + + float eigenvalue = 0; + float eigenvector[CHANNEL_COUNT]; + + if (threadIdx.x < gmmK) { + float* matrix = g_batch_gmm + gmm_idx * GMM_COMPONENT_COUNT + (CHANNEL_COUNT + 1); + largest_eigenpair(matrix, eigenvector, &eigenvalue); + } + + float max_value = eigenvalue; + max_value = max(max_value, __SHFL_XOR(max_value, 16)); + max_value = max(max_value, __SHFL_XOR(max_value, 8)); + max_value = max(max_value, __SHFL_XOR(max_value, 4)); + max_value = max(max_value, __SHFL_XOR(max_value, 2)); + max_value = max(max_value, __SHFL_XOR(max_value, 1)); + if (max_value == eigenvalue) { + GMMSplit_t split; + + float* average_feature = gmm + gmm_idx * GMM_COMPONENT_COUNT + 1; + + split.idx = threadIdx.x; + split.threshold = scalar_prod(average_feature, eigenvector); + + for (int i = 0; i < CHANNEL_COUNT; i++) { + split.eigenvector[i] = eigenvector[i]; + } + + g_batch_gmmSplit[threadIdx.y] = split; + } +} + +#define DO_SPLIT_DEGENERACY 4 + +__global__ void GMMDoSplit(const GMMSplit_t* gmmSplit, int k, const float* image, int* alpha, int element_count) { + __shared__ GMMSplit_t s_gmmSplit[MIXTURE_COUNT]; + + int batch_index = blockIdx.z; + + const GMMSplit_t* g_batch_gmmSplit = gmmSplit + batch_index * MIXTURE_COUNT; + const float* g_batch_image = image + batch_index * element_count * CHANNEL_COUNT; + int* g_batch_alpha = alpha + batch_index * element_count; + + int* s_linear = (int*)s_gmmSplit; + int* g_linear = (int*)g_batch_gmmSplit; + + if (threadIdx.x < MIXTURE_COUNT * sizeof(GMMSplit_t)) { + s_linear[threadIdx.x] = g_linear[threadIdx.x]; + } + + __syncthreads(); + + int index = threadIdx.x + blockIdx.x * BLOCK_SIZE * DO_SPLIT_DEGENERACY; + + for (int i = 0; i < DO_SPLIT_DEGENERACY; i++) { + index += BLOCK_SIZE; + + if (index < element_count) { + int my_alpha = g_batch_alpha[index]; + + if (my_alpha != -1) { + int select = my_alpha & 15; + int gmm_idx = my_alpha >> 4; + + if (gmm_idx == s_gmmSplit[select].idx) { + // in the split cluster now + float feature[CHANNEL_COUNT]; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + feature[i] = g_batch_image[index + i * element_count]; + } + + float value = scalar_prod(s_gmmSplit[select].eigenvector, feature); + + if (value > s_gmmSplit[select].threshold) { + // assign pixel to new cluster + g_batch_alpha[index] = k + select; + } + } + } + } + } +} + +// Single block, 32xMIXTURE_COUNT +__global__ void GMMcommonTerm(float* g_gmm) { + int batch_index = blockIdx.z; + + float* g_batch_gmm = g_gmm + batch_index * GMM_COUNT * GMM_COMPONENT_COUNT; + + int gmm_index = (threadIdx.x * MIXTURE_COUNT) + threadIdx.y; + + float gmm_n = threadIdx.x < MIXTURE_SIZE ? g_batch_gmm[gmm_index * GMM_COMPONENT_COUNT] : 0.0f; + + float sum = gmm_n; + sum += __SHFL_XOR(sum, 1); + sum += __SHFL_XOR(sum, 2); + sum += __SHFL_XOR(sum, 4); + sum += __SHFL_XOR(sum, 8); + sum += __SHFL_XOR(sum, 16); + + if (threadIdx.x < MIXTURE_SIZE) { + float det = g_batch_gmm[gmm_index * GMM_COMPONENT_COUNT + MATRIX_COMPONENT_COUNT] + EPSILON; + float commonTerm = det > 0.0f ? gmm_n / (sqrtf(det) * sum) : gmm_n / sum; + + g_batch_gmm[gmm_index * GMM_COMPONENT_COUNT + MATRIX_COMPONENT_COUNT] = commonTerm; + } +} + +__device__ float GMMTerm(float* feature, const float* gmm) { + const float* average_feature = gmm + 1; + const float* matrix = gmm + CHANNEL_COUNT + 1; + + float diff[CHANNEL_COUNT]; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + diff[i] = feature[i] - average_feature[i]; + } + + float value = 0.0f; + + for (int index = 0, i = 0; i < CHANNEL_COUNT; i++) { + for (int j = i; j < CHANNEL_COUNT; j++, index++) { + float term = diff[i] * diff[j] * matrix[index]; + + value += i == j ? term : 2 * term; + } + } + + return gmm[MATRIX_COMPONENT_COUNT] * expf(-0.5 * value); +} + +__global__ void GMMDataTermKernel(const float* image, const float* gmm, float* output, int element_count) { + int batch_index = blockIdx.z; + + const float* g_batch_image = image + batch_index * element_count * CHANNEL_COUNT; + const float* g_batch_gmm = gmm + batch_index * GMM_COUNT * GMM_COMPONENT_COUNT; + float* g_batch_output = output + batch_index * element_count * MIXTURE_COUNT; + + int index = blockIdx.x * blockDim.x + threadIdx.x; + + if (index >= element_count) + return; + + float feature[CHANNEL_COUNT]; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + feature[i] = g_batch_image[index + i * element_count]; + } + + float weights[MIXTURE_COUNT]; + float weight_total = 0.0f; + + for (int i = 0; i < MIXTURE_COUNT; i++) { + float mixture_weight = 0.0f; + + for (int j = 0; j < MIXTURE_SIZE; j++) { + mixture_weight += GMMTerm(feature, &g_batch_gmm[(MIXTURE_COUNT * j + i) * GMM_COMPONENT_COUNT]); + } + + weights[i] = mixture_weight; + weight_total += mixture_weight; + } + + for (int i = 0; i < MIXTURE_COUNT; i++) { + // protecting against pixels with 0 in all mixtures + float final_weight = weight_total > 0.0f ? weights[i] / weight_total : 0.0f; + g_batch_output[index + i * element_count] = final_weight; + } +} + +#define THREADS 512 +#define WARPS 16 +#define BLOCK (WARPS << 5) +#define LOAD 4 + +void GMMInitialize( + const float* image, + int* alpha, + float* gmm, + float* scratch_mem, + unsigned int batch_count, + unsigned int element_count) { + unsigned int block_count = TILE(element_count, BLOCK * LOAD); + + float* block_gmm_scratch = scratch_mem; + GMMSplit_t* gmm_split_scratch = (GMMSplit_t*)scratch_mem; + + int gmm_N = MIXTURE_COUNT * MIXTURE_SIZE; + + for (unsigned int k = MIXTURE_COUNT; k < gmm_N; k += MIXTURE_COUNT) { + for (unsigned int i = 0; i < k; ++i) { + CovarianceReductionKernel + <<>>(i, image, alpha, block_gmm_scratch, element_count); + } + + CovarianceFinalizationKernel<<>>(block_gmm_scratch, gmm, block_count); + + GMMFindSplit<<>>( + gmm_split_scratch, k / MIXTURE_COUNT, gmm); + GMMDoSplit<<>>( + gmm_split_scratch, (k / MIXTURE_COUNT) << 4, image, alpha, element_count); + } +} + +void GMMUpdate( + const float* image, + int* alpha, + float* gmm, + float* scratch_mem, + unsigned int batch_count, + unsigned int element_count) { + unsigned int block_count = TILE(element_count, BLOCK * LOAD); + + float* block_gmm_scratch = scratch_mem; + + unsigned int gmm_N = MIXTURE_COUNT * MIXTURE_SIZE; + + for (unsigned int i = 0; i < gmm_N; ++i) { + CovarianceReductionKernel + <<>>(i, image, alpha, block_gmm_scratch, element_count); + } + + CovarianceFinalizationKernel + <<>>(block_gmm_scratch, gmm, block_count); + + GMMcommonTerm<<>>(gmm); +} + +void GMMDataTerm( + const float* image, + const float* gmm, + float* output, + unsigned int batch_count, + unsigned int element_count) { + dim3 block(BLOCK_SIZE, 1); + dim3 grid(TILE(element_count, BLOCK_SIZE), 1, batch_count); + + GMMDataTermKernel<<>>(image, gmm, output, element_count); +} + +void learn_cuda( + const float* input, + const int* labels, + float* gmm, + float* scratch_memory, + unsigned int batch_count, + unsigned int element_count) { + int* alpha = (int*)scratch_memory; + float* scratch_mem = scratch_memory + batch_count * element_count; + + cudaMemcpyAsync(alpha, labels, batch_count * element_count * sizeof(int), cudaMemcpyDeviceToDevice); + + GMMInitialize(input, alpha, gmm, scratch_mem, batch_count, element_count); + GMMUpdate(input, alpha, gmm, scratch_mem, batch_count, element_count); +} + +void apply_cuda( + const float* gmm, + const float* input, + float* output, + unsigned int batch_count, + unsigned int element_count) { + GMMDataTerm(input, gmm, output, batch_count, element_count); +} diff --git a/source_code/SegMamba/monai/_extensions/gmm/gmm_cuda_linalg.cuh b/source_code/SegMamba/monai/_extensions/gmm/gmm_cuda_linalg.cuh new file mode 100644 index 0000000000000000000000000000000000000000..56c7c7ccdcd53b7bb5c24dcba660af35571caa76 --- /dev/null +++ b/source_code/SegMamba/monai/_extensions/gmm/gmm_cuda_linalg.cuh @@ -0,0 +1,144 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +__device__ void to_square(float in[SUB_MATRIX_COMPONENT_COUNT], float out[CHANNEL_COUNT][CHANNEL_COUNT]) { + for (int index = 0, i = 0; i < CHANNEL_COUNT; i++) { + for (int j = i; j < CHANNEL_COUNT; j++, index++) { + out[i][j] = in[index]; + out[j][i] = in[index]; + } + } +} + +__device__ void to_triangle(float in[CHANNEL_COUNT][CHANNEL_COUNT], float out[SUB_MATRIX_COMPONENT_COUNT]) { + for (int index = 0, i = 0; i < CHANNEL_COUNT; i++) { + for (int j = i; j < CHANNEL_COUNT; j++, index++) { + out[index] = in[j][i]; + } + } +} + +__device__ void cholesky(float in[CHANNEL_COUNT][CHANNEL_COUNT], float out[CHANNEL_COUNT][CHANNEL_COUNT]) { + for (int i = 0; i < CHANNEL_COUNT; i++) { + for (int j = 0; j < i + 1; j++) { + float sum = 0.0f; + + for (int k = 0; k < j; k++) { + sum += out[i][k] * out[j][k]; + } + + if (i == j) { + out[i][j] = sqrtf(in[i][i] - sum); + } else { + out[i][j] = (in[i][j] - sum) / out[j][j]; + } + } + } +} + +__device__ float chol_det(float in[CHANNEL_COUNT][CHANNEL_COUNT]) { + float det = 1.0f; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + det *= in[i][i]; + } + + return det * det; +} + +__device__ void chol_inv(float in[CHANNEL_COUNT][CHANNEL_COUNT], float out[CHANNEL_COUNT][CHANNEL_COUNT]) { + // Invert cholesky matrix + for (int i = 0; i < CHANNEL_COUNT; i++) { + in[i][i] = 1.0f / (in[i][i] + 0.0001f); + + for (int j = 0; j < i; j++) { + float sum = 0.0f; + + for (int k = j; k < i; k++) { + sum += in[i][k] * in[k][j]; + } + + in[i][j] = -in[i][i] * sum; + } + } + + // Dot with transpose of self + for (int i = 0; i < CHANNEL_COUNT; i++) { + for (int j = 0; j < CHANNEL_COUNT; j++) { + out[i][j] = 0.0f; + + for (int k = max(i, j); k < CHANNEL_COUNT; k++) { + out[i][j] += in[k][i] * in[k][j]; + } + } + } +} + +__device__ void normalize(float* v) { + float norm = 0.0f; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + norm += v[i] * v[i]; + } + + norm = 1.0f / sqrtf(norm); + + for (int i = 0; i < CHANNEL_COUNT; i++) { + v[i] *= norm; + } +} + +__device__ float scalar_prod(float* a, float* b) { + float product = 0.0f; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + product += a[i] * b[i]; + } + + return product; +} + +__device__ void largest_eigenpair(const float* M, float* evec, float* eval) { + float scratch[CHANNEL_COUNT]; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + scratch[i] = i + 1; + } + + for (int itr = 0; itr < 10; itr++) { + *eval = 0.0f; + + for (int i = 0; i < CHANNEL_COUNT; i++) { + int index = i; + + evec[i] = 0.0f; + + for (int j = 0; j < CHANNEL_COUNT; j++) { + evec[i] += M[index] * scratch[j]; + + if (j < i) { + index += CHANNEL_COUNT - (j + 1); + } else { + index += 1; + } + } + + *eval = max(*eval, evec[i]); + } + + for (int i = 0; i < CHANNEL_COUNT; i++) { + evec[i] /= *eval; + scratch[i] = evec[i]; + } + } +} diff --git a/source_code/SegMamba/monai/apps/auto3dseg/auto_runner.py b/source_code/SegMamba/monai/apps/auto3dseg/auto_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..05c961f999805ebbc61da1df007a725062a61522 --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/auto_runner.py @@ -0,0 +1,898 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +import shutil +import warnings +from copy import deepcopy +from time import sleep +from typing import Any, cast + +import torch + +from monai.apps.auto3dseg.bundle_gen import BundleGen +from monai.apps.auto3dseg.data_analyzer import DataAnalyzer +from monai.apps.auto3dseg.ensemble_builder import EnsembleRunner +from monai.apps.auto3dseg.hpo_gen import NNIGen +from monai.apps.auto3dseg.utils import export_bundle_algo_history, import_bundle_algo_history +from monai.apps.utils import get_logger +from monai.auto3dseg.utils import algo_to_pickle +from monai.bundle import ConfigParser +from monai.transforms import SaveImage +from monai.utils import AlgoKeys, has_option, look_up_option, optional_import +from monai.utils.misc import check_kwargs_exist_in_class_init, run_cmd + +logger = get_logger(module_name=__name__) + +nni, has_nni = optional_import("nni") + + +class AutoRunner: + """ + An interface for handling Auto3Dseg with minimal inputs and understanding of the internal states in Auto3Dseg. + The users can run the Auto3Dseg with default settings in one line of code. They can also customize the advanced + features Auto3Dseg in a few additional lines. Examples of customization include + + - change cross-validation folds + - change training/prediction parameters + - change ensemble methods + - automatic hyperparameter optimization. + + The output of the interface is a directory that contains + + - data statistics analysis report + - algorithm definition files (scripts, configs, pickle objects) and training results (checkpoints, accuracies) + - the predictions on the testing datasets from the final algorithm ensemble + - a copy of the input arguments in form of YAML + - cached intermediate results + + Args: + work_dir: working directory to save the intermediate and final results. + input: the configuration dictionary or the file path to the configuration in form of YAML. + The configuration should contain datalist, dataroot, modality, multigpu, and class_names info. + algos: optionally specify algorithms to use. If a dictionary, must be in the form + {"algname": dict(_target_="algname.scripts.algo.AlgnameAlgo", template_path="algname"), ...} + If a list or a string, defines a subset of names of the algorithms to use, e.g. 'segresnet' or + ['segresnet', 'dints'] out of the full set of algorithm templates provided by templates_path_or_url. + Defaults to None, to use all available algorithms. + analyze: on/off switch to run DataAnalyzer and generate a datastats report. Defaults to None, to automatically + decide based on cache, and run data analysis only if we have not completed this step yet. + algo_gen: on/off switch to run AlgoGen and generate templated BundleAlgos. Defaults to None, to automatically + decide based on cache, and run algorithm folders generation only if we have not completed this step yet. + train: on/off switch to run training and generate algorithm checkpoints. Defaults to None, to automatically + decide based on cache, and run training only if we have not completed this step yet. + hpo: use hyperparameter optimization (HPO) in the training phase. Users can provide a list of + hyper-parameter and a search will be performed to investigate the algorithm performances. + hpo_backend: a string that indicates the backend of the HPO. Currently, only NNI Grid-search mode + is supported + ensemble: on/off switch to run model ensemble and use the ensemble to predict outputs in testing + datasets. + not_use_cache: if the value is True, it will ignore all cached results in data analysis, + algorithm generation, or training, and start the pipeline from scratch. + templates_path_or_url: the folder with the algorithm templates or a url. If None provided, the default template + zip url will be downloaded and extracted into the work_dir. + allow_skip: a switch passed to BundleGen process which determines if some Algo in the default templates + can be skipped based on the analysis on the dataset from Auto3DSeg DataAnalyzer. + mlflow_tracking_uri: a tracking URI for MLflow server which could be local directory or address of the remote + tracking Server; MLflow runs will be recorded locally in algorithms' model folder if the value is None. + mlflow_experiment_name: the name of the experiment in MLflow server. + kwargs: image writing parameters for the ensemble inference. The kwargs format follows the SaveImage + transform. For more information, check https://docs.monai.io/en/stable/transforms.html#saveimage. + + + Examples: + - User can use the one-liner to start the Auto3Dseg workflow + + .. code-block:: bash + + python -m monai.apps.auto3dseg AutoRunner run --input \ + '{"modality": "ct", "datalist": "dl.json", "dataroot": "/dr", "multigpu": true, "class_names": ["A", "B"]}' + + - User can also save the input dictionary as a input YAML file and use the following one-liner + + .. code-block:: bash + + python -m monai.apps.auto3dseg AutoRunner run --input=./input.yaml + + - User can specify work_dir and data source config input and run AutoRunner: + + .. code-block:: python + + work_dir = "./work_dir" + input = "path/to/input_yaml" + runner = AutoRunner(work_dir=work_dir, input=input) + runner.run() + + - User can specify a subset of algorithms to use and run AutoRunner: + + .. code-block:: python + + work_dir = "./work_dir" + input = "path/to/input_yaml" + algos = ["segresnet", "dints"] + runner = AutoRunner(work_dir=work_dir, input=input, algos=algos) + runner.run() + + - User can specify a local folder with algorithms templates and run AutoRunner: + + .. code-block:: python + + work_dir = "./work_dir" + input = "path/to/input_yaml" + algos = "segresnet" + templates_path_or_url = "./local_path_to/algorithm_templates" + runner = AutoRunner(work_dir=work_dir, input=input, algos=algos, templates_path_or_url=templates_path_or_url) + runner.run() + + - User can specify training parameters by: + + .. code-block:: python + + input = "path/to/input_yaml" + runner = AutoRunner(input=input) + train_param = { + "num_epochs_per_validation": 1, + "num_images_per_batch": 2, + "num_epochs": 2, + } + runner.set_training_params(params=train_param) # 2 epochs + runner.run() + + - User can specify the fold number of cross validation + + .. code-block:: python + + input = "path/to/input_yaml" + runner = AutoRunner(input=input) + runner.set_num_fold(n_fold = 2) + runner.run() + + - User can specify the prediction parameters during algo ensemble inference: + + .. code-block:: python + + input = "path/to/input_yaml" + pred_params = { + 'files_slices': slice(0,2), + 'mode': "vote", + 'sigmoid': True, + } + runner = AutoRunner(input=input) + runner.set_prediction_params(params=pred_params) + runner.run() + + - User can define a grid search space and use the HPO during training. + + .. code-block:: python + + input = "path/to/input_yaml" + runner = AutoRunner(input=input, hpo=True) + runner.set_nni_search_space({"learning_rate": {"_type": "choice", "_value": [0.0001, 0.001, 0.01, 0.1]}}) + runner.run() + + Notes: + Expected results in the work_dir as below:: + + work_dir/ + ├── algorithm_templates # bundle algo templates (scripts/configs) + ├── cache.yaml # Autorunner will automatically cache results to save time + ├── datastats.yaml # datastats of the dataset + ├── dints_0 # network scripts/configs/checkpoints and pickle object of the algo + ├── ensemble_output # the prediction of testing datasets from the ensemble of the algos + ├── input.yaml # copy of the input data source configs + ├── segresnet_0 # network scripts/configs/checkpoints and pickle object of the algo + ├── segresnet2d_0 # network scripts/configs/checkpoints and pickle object of the algo + └── swinunetr_0 # network scripts/configs/checkpoints and pickle object of the algo + + """ + + analyze_params: dict | None + + def __init__( + self, + work_dir: str = "./work_dir", + input: dict[str, Any] | str | None = None, + algos: dict | list | str | None = None, + analyze: bool | None = None, + algo_gen: bool | None = None, + train: bool | None = None, + hpo: bool = False, + hpo_backend: str = "nni", + ensemble: bool = True, + not_use_cache: bool = False, + templates_path_or_url: str | None = None, + allow_skip: bool = True, + mlflow_tracking_uri: str | None = None, + mlflow_experiment_name: str | None = None, + **kwargs: Any, + ): + if input is None and os.path.isfile(os.path.join(os.path.abspath(work_dir), "input.yaml")): + input = os.path.join(os.path.abspath(work_dir), "input.yaml") + logger.info(f"Input config is not provided, using the default {input}") + + self.data_src_cfg = dict() + if isinstance(input, dict): + self.data_src_cfg = input + elif isinstance(input, str) and os.path.isfile(input): + self.data_src_cfg = ConfigParser.load_config_file(input) + logger.info(f"Loading input config {input}") + else: + raise ValueError(f"{input} is not a valid file or dict") + + if "work_dir" in self.data_src_cfg: # override from config + work_dir = self.data_src_cfg["work_dir"] + self.work_dir = os.path.abspath(work_dir) + + logger.info(f"AutoRunner using work directory {self.work_dir}") + os.makedirs(self.work_dir, exist_ok=True) + self.data_src_cfg_name = os.path.join(self.work_dir, "input.yaml") + + self.algos = algos + self.templates_path_or_url = templates_path_or_url + self.allow_skip = allow_skip + + # cache.yaml + self.not_use_cache = not_use_cache + self.cache_filename = os.path.join(self.work_dir, "cache.yaml") + self.cache = self.read_cache() + self.export_cache() + + # determine if we need to analyze, algo_gen or train from cache, unless manually provided + self.analyze = not self.cache["analyze"] if analyze is None else analyze + self.algo_gen = not self.cache["algo_gen"] if algo_gen is None else algo_gen + self.train = train + self.ensemble = ensemble # last step, no need to check + self.hpo = hpo and has_nni + self.hpo_backend = hpo_backend + self.mlflow_tracking_uri = mlflow_tracking_uri + self.mlflow_experiment_name = mlflow_experiment_name + self.kwargs = deepcopy(kwargs) + + # parse input config for AutoRunner param overrides + for param in [ + "analyze", + "algo_gen", + "train", + "hpo", + "ensemble", + "not_use_cache", + "allow_skip", + ]: # override from config + if param in self.data_src_cfg and isinstance(self.data_src_cfg[param], bool): + setattr(self, param, self.data_src_cfg[param]) # e.g. self.analyze = self.data_src_cfg["analyze"] + + for param in [ + "algos", + "hpo_backend", + "templates_path_or_url", + "mlflow_tracking_uri", + "mlflow_experiment_name", + ]: # override from config + if param in self.data_src_cfg: + setattr(self, param, self.data_src_cfg[param]) # e.g. self.algos = self.data_src_cfg["algos"] + + missing_keys = {"dataroot", "datalist", "modality"}.difference(self.data_src_cfg.keys()) + if len(missing_keys) > 0: + raise ValueError(f"Config keys are missing {missing_keys}") + + if not os.path.exists(self.data_src_cfg["datalist"]): + raise ValueError(f"Datalist file is not found {self.data_src_cfg['datalist']}") + + # copy datalist to work_dir + datalist_filename = os.path.join(self.work_dir, os.path.basename(self.data_src_cfg["datalist"])) + if datalist_filename != self.data_src_cfg["datalist"]: + try: + shutil.copyfile(self.data_src_cfg["datalist"], datalist_filename) + logger.info(f"Datalist was copied to work_dir: {datalist_filename}") + except shutil.SameFileError: + pass + + # inspect and update folds + self.max_fold = self.inspect_datalist_folds(datalist_filename=datalist_filename) + if "num_fold" in self.data_src_cfg: + num_fold = int(self.data_src_cfg["num_fold"]) # override from config + logger.info(f"Setting num_fold {num_fold} based on the input config.") + else: + num_fold = self.max_fold + logger.info(f"Setting num_fold {num_fold} based on the input datalist {datalist_filename}.") + + self.data_src_cfg["datalist"] = datalist_filename # update path to a version in work_dir and save user input + ConfigParser.export_config_file( + config=self.data_src_cfg, filepath=self.data_src_cfg_name, fmt="yaml", sort_keys=False + ) + + self.dataroot = self.data_src_cfg["dataroot"] + self.datastats_filename = os.path.join(self.work_dir, "datastats.yaml") + self.datalist_filename = datalist_filename + + self.set_training_params() + self.set_device_info() + self.set_prediction_params() + self.set_analyze_params() + self.set_ensemble_method() + self.set_num_fold(num_fold=num_fold) + + self.gpu_customization = False + self.gpu_customization_specs: dict[str, Any] = {} + + # hpo + if self.hpo_backend.lower() != "nni": + raise NotImplementedError("HPOGen backend only supports NNI") + self.hpo = self.hpo and has_nni + self.set_hpo_params() + self.search_space: dict[str, dict[str, Any]] = {} + self.hpo_tasks = 0 + + if "sigmoid" not in self.kwargs and "sigmoid" in self.data_src_cfg: + self.kwargs["sigmoid"] = self.data_src_cfg["sigmoid"] + + def read_cache(self): + """ + Check if the intermediate result is cached after each step in the current working directory + + Returns: + a dict of cache results. If not_use_cache is set to True, or there is no cache file in the + working directory, the result will be ``empty_cache`` in which all ``has_cache`` keys are + set to False. + """ + + empty_cache = {"analyze": False, "datastats": None, "algo_gen": False, "train": False} + + if self.not_use_cache or not os.path.isfile(self.cache_filename): + return empty_cache + + cache = ConfigParser.load_config_file(self.cache_filename) + + for k, v in empty_cache.items(): + cache.setdefault(k, v) + + if cache["analyze"]: + if not (isinstance(cache["datastats"], str) and os.path.isfile(cache["datastats"])): + cache["analyze"] = False + cache["datastats"] = None + + if cache["algo_gen"]: + history = import_bundle_algo_history(self.work_dir, only_trained=False) + if len(history) == 0: # no saved algo_objects + cache["algo_gen"] = False + + if cache["train"]: + trained_history = import_bundle_algo_history(self.work_dir, only_trained=True) + if len(trained_history) == 0: + cache["train"] = False + + return cache + + def export_cache(self, **kwargs): + """ + Save the cache state as ``cache.yaml`` in the working directory + """ + self.cache.update(kwargs) + ConfigParser.export_config_file( + self.cache, self.cache_filename, fmt="yaml", default_flow_style=None, sort_keys=False + ) + + def inspect_datalist_folds(self, datalist_filename: str) -> int: + """ + Returns number of folds in the datalist file, and assigns fold numbers if not provided. + + Args: + datalist_filename: path to the datalist file. + + Notes: + If the fold key is not provided, it auto generates 5 folds assignments in the training key list. + If validation key list is available, then it assumes a single fold validation. + """ + + datalist = ConfigParser.load_config_file(datalist_filename) + if "training" not in datalist: + raise ValueError("Datalist files has no training key:" + str(datalist_filename)) + + fold_list = [int(d["fold"]) for d in datalist["training"] if "fold" in d] + + if len(fold_list) > 0: + num_fold = max(fold_list) + 1 + logger.info(f"Found num_fold {num_fold} based on the input datalist {datalist_filename}.") + # check if every fold is present + if len(set(fold_list)) != num_fold: + raise ValueError(f"Fold numbers are not continuous from 0 to {num_fold - 1}") + elif "validation" in datalist and len(datalist["validation"]) > 0: + logger.info("No fold numbers provided, attempting to use a single fold based on the validation key") + # update the datalist file + for d in datalist["training"]: + d["fold"] = 1 + for d in datalist["validation"]: + d["fold"] = 0 + + val_labels = {d["label"]: d for d in datalist["validation"] if "label" in d} + logger.info( + f"Found {len(val_labels)} items in the validation key, saving updated datalist to", datalist_filename + ) + + # check for duplicates + for d in datalist["training"]: + if d["label"] in val_labels: + d["fold"] = 0 + del val_labels[d["label"]] + + datalist["training"] = datalist["training"] + list(val_labels.values()) + + ConfigParser.export_config_file(datalist, datalist_filename, fmt="json", indent=4) + num_fold = 1 + + else: + num_fold = 5 + + warnings.warn( + f"Datalist has no folds specified {datalist_filename}..." + f"Generating {num_fold} folds randomly." + f"Please consider presaving fold numbers beforehand for repeated experiments." + ) + + from sklearn.model_selection import KFold + + kf = KFold(n_splits=num_fold, shuffle=True, random_state=0) + for i, (_, valid_idx) in enumerate(kf.split(datalist["training"])): + for vi in valid_idx: + datalist["training"][vi]["fold"] = i + + ConfigParser.export_config_file(datalist, datalist_filename, fmt="json", indent=4) + + return num_fold + + def set_gpu_customization( + self, gpu_customization: bool = False, gpu_customization_specs: dict[str, Any] | None = None + ) -> AutoRunner: + """ + Set options for GPU-based parameter customization/optimization. + + Args: + gpu_customization: the switch to determine automatically customize/optimize bundle script/config + parameters for each bundleAlgo based on gpus. Custom parameters are obtained through dummy + training to simulate the actual model training process and hyperparameter optimization (HPO) + experiments. + gpu_customization_specs (optional): the dictionary to enable users overwrite the HPO settings. user can + overwrite part of variables as follows or all of them. The structure is as follows. + + .. code-block:: python + + gpu_customization_specs = { + 'ALGO': { + 'num_trials': 6, + 'range_num_images_per_batch': [1, 20], + 'range_num_sw_batch_size': [1, 20] + } + } + + ALGO: the name of algorithm. It could be one of algorithm names (e.g., 'dints') or 'universal' which + would apply changes to all algorithms. Possible options are + + - {``"universal"``, ``"dints"``, ``"segresnet"``, ``"segresnet2d"``, ``"swinunetr"``}. + + num_trials: the number of HPO trials/experiments to run. + range_num_images_per_batch: the range of number of images per mini-batch. + range_num_sw_batch_size: the range of batch size in sliding-window inferer. + """ + self.gpu_customization = gpu_customization + if gpu_customization_specs is not None: + self.gpu_customization_specs = gpu_customization_specs + + return self + + def set_num_fold(self, num_fold: int = 5) -> AutoRunner: + """ + Set the number of cross validation folds for all algos. + + Args: + num_fold: a positive integer to define the number of folds. + """ + + if num_fold <= 0: + raise ValueError(f"num_fold is expected to be an integer greater than zero. Now it gets {num_fold}") + if num_fold > self.max_fold + 1: + # Auto3DSeg allows no validation set, so the maximum fold number is max_fold + 1 + raise ValueError( + f"num_fold is greater than the maximum fold number {self.max_fold} in {self.datalist_filename}." + ) + self.num_fold = num_fold + + return self + + def set_training_params(self, params: dict[str, Any] | None = None) -> AutoRunner: + """ + Set the training params for all algos. + + Args: + params: a dict that defines the overriding key-value pairs during training. The overriding method + is defined by the algo class. + + Examples: + For BundleAlgo objects, the training parameter to shorten the training time to a few epochs can be + {"num_epochs": 2, "num_epochs_per_validation": 1} + + """ + self.train_params = deepcopy(params) if params is not None else {} + if "CUDA_VISIBLE_DEVICES" in self.train_params: + warnings.warn( + "CUDA_VISIBLE_DEVICES is deprecated from 'set_training_params'. Use 'set_device_info' instead.", + DeprecationWarning, + ) + + return self + + def set_device_info( + self, + cuda_visible_devices: list[int] | str | None = None, + num_nodes: int | None = None, + mn_start_method: str | None = None, + cmd_prefix: str | None = None, + ) -> AutoRunner: + """ + Set the device related info + + Args: + cuda_visible_devices: define GPU ids for data analyzer, training, and ensembling. + List of GPU ids [0,1,2,3] or a string "0,1,2,3". + Default using env "CUDA_VISIBLE_DEVICES" or all devices available. + num_nodes: number of nodes for training and ensembling. + Default using env "NUM_NODES" or 1 if "NUM_NODES" is unset. + mn_start_method: multi-node start method. Autorunner will use the method to start multi-node processes. + Default using env "MN_START_METHOD" or 'bcprun' if "MN_START_METHOD" is unset. + cmd_prefix: command line prefix for subprocess running in BundleAlgo and EnsembleRunner. + Default using env "CMD_PREFIX" or None, examples are: + + - single GPU/CPU or multinode bcprun: "python " or "/opt/conda/bin/python3.8 ", + - single node multi-GPU running "torchrun --nnodes=1 --nproc_per_node=2 " + + If user define this prefix, please make sure --nproc_per_node matches cuda_visible_device or + os.env['CUDA_VISIBLE_DEVICES']. Also always set --nnodes=1. Set num_nodes for multi-node. + """ + self.device_setting: dict[str, Any] = {} + if cuda_visible_devices is None: + cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES") + if cuda_visible_devices is None: # still None after reading the environ + self.device_setting["CUDA_VISIBLE_DEVICES"] = ",".join([str(x) for x in range(torch.cuda.device_count())]) + self.device_setting["n_devices"] = torch.cuda.device_count() + elif isinstance(cuda_visible_devices, str): + self.device_setting["CUDA_VISIBLE_DEVICES"] = cuda_visible_devices + self.device_setting["n_devices"] = len(cuda_visible_devices.split(",")) + elif isinstance(cuda_visible_devices, (list, tuple)): + self.device_setting["CUDA_VISIBLE_DEVICES"] = ",".join([str(x) for x in cuda_visible_devices]) + self.device_setting["n_devices"] = len(cuda_visible_devices) + else: + logger.warn(f"Wrong format of cuda_visible_devices {cuda_visible_devices}, devices not set") + + if num_nodes is None: + num_nodes = int(os.environ.get("NUM_NODES", 1)) + self.device_setting["NUM_NODES"] = num_nodes + + if mn_start_method is None: + mn_start_method = os.environ.get("MN_START_METHOD", "bcprun") + self.device_setting["MN_START_METHOD"] = mn_start_method + + if cmd_prefix is None: + cmd_prefix = os.environ.get("CMD_PREFIX", "") + self.device_setting["CMD_PREFIX"] = cmd_prefix + + if cmd_prefix is not None: + logger.info(f"Using user defined command running prefix {cmd_prefix}, will override other settings") + + return self + + def set_ensemble_method(self, ensemble_method_name: str = "AlgoEnsembleBestByFold", **kwargs: Any) -> AutoRunner: + """ + Set the bundle ensemble method name and parameters for save image transform parameters. + + Args: + ensemble_method_name: the name of the ensemble method. Only two methods are supported "AlgoEnsembleBestN" + and "AlgoEnsembleBestByFold". + kwargs: the keyword arguments used to define the ensemble method. Currently only ``n_best`` for + ``AlgoEnsembleBestN`` is supported. + """ + self.ensemble_method_name = look_up_option( + ensemble_method_name, supported=["AlgoEnsembleBestN", "AlgoEnsembleBestByFold"] + ) + self.kwargs.update(kwargs) + + return self + + def set_image_save_transform(self, **kwargs: Any) -> AutoRunner: + """ + Set the ensemble output transform. + + Args: + kwargs: image writing parameters for the ensemble inference. The kwargs format follows SaveImage + transform. For more information, check https://docs.monai.io/en/stable/transforms.html#saveimage. + + """ + + are_all_args_present, extra_args = check_kwargs_exist_in_class_init(SaveImage, kwargs) + if are_all_args_present: + self.kwargs.update(kwargs) + else: + raise ValueError( + f"{extra_args} are not supported in monai.transforms.SaveImage," + "Check https://docs.monai.io/en/stable/transforms.html#saveimage for more information." + ) + + return self + + def set_prediction_params(self, params: dict[str, Any] | None = None) -> AutoRunner: + """ + Set the prediction params for all algos. + + Args: + params: a dict that defines the overriding key-value pairs during prediction. The overriding method + is defined by the algo class. + + Examples: + + For BundleAlgo objects, this set of param will specify the algo ensemble to only inference the first + two files in the testing datalist {"file_slices": slice(0, 2)} + + """ + self.pred_params = deepcopy(params) if params is not None else {} + + return self + + def set_analyze_params(self, params: dict[str, Any] | None = None) -> AutoRunner: + """ + Set the data analysis extra params. + + Args: + params: a dict that defines the overriding key-value pairs during training. The overriding method + is defined by the algo class. + + """ + if params is None: + self.analyze_params = {"do_ccp": False, "device": "cuda"} + else: + self.analyze_params = deepcopy(params) + + return self + + def set_hpo_params(self, params: dict[str, Any] | None = None) -> AutoRunner: + """ + Set parameters for the HPO module and the algos before the training. It will attempt to (1) override bundle + templates with the key-value pairs in ``params`` (2) change the config of the HPO module (e.g. NNI) if the + key is found to be one of: + + - "trialCodeDirectory" + - "trialGpuNumber" + - "trialConcurrency" + - "maxTrialNumber" + - "maxExperimentDuration" + - "tuner" + - "trainingService" + + and (3) enable the dry-run mode if the user would generate the NNI configs without starting the NNI service. + + Args: + params: a dict that defines the overriding key-value pairs during instantiation of the algo. For + BundleAlgo, it will override the template config filling. + + Notes: + Users can set ``nni_dry_run`` to ``True`` in the ``params`` to enable the dry-run mode for the NNI backend. + + """ + self.hpo_params = self.train_params if params is None else params + + return self + + def set_nni_search_space(self, search_space: dict[str, Any]) -> AutoRunner: + """ + Set the search space for NNI parameter search. + + Args: + search_space: hyper parameter search space in the form of dict. For more information, please check + NNI documentation: https://nni.readthedocs.io/en/v2.2/Tutorial/SearchSpaceSpec.html . + """ + value_combinations = 1 + for k, v in search_space.items(): + if "_value" not in v: + raise ValueError(f"{search_space} key {k} value {v} has not _value") + value_combinations *= len(v["_value"]) + + self.search_space = search_space + self.hpo_tasks = value_combinations + + return self + + def _train_algo_in_sequence(self, history: list[dict[str, Any]]) -> None: + """ + Train the Algos in a sequential scheme. The order of training is randomized. + + Args: + history: the history of generated Algos. It is a list of dicts. Each element has the task name + (e.g. "dints_0" for dints network in fold 0) as the key and the algo object as the value. + After the training, the algo object with the ``best_metric`` will be saved as a pickle file. + + Note: + The final results of the model training will be written to all the generated algorithm's output + folders under the working directory. The results include the model checkpoints, a + progress.yaml, accuracies in CSV and a pickle file of the Algo object. + """ + for algo_dict in history: + algo = algo_dict[AlgoKeys.ALGO] + if has_option(algo.train, "device_setting"): + algo.train(self.train_params, self.device_setting) + else: + algo.train(self.train_params) + acc = algo.get_score() + + algo_meta_data = {str(AlgoKeys.SCORE): acc} + algo_to_pickle(algo, template_path=algo.template_path, **algo_meta_data) + + def _train_algo_in_nni(self, history: list[dict[str, Any]]) -> None: + """ + Train the Algos using HPO. + + Args: + history: the history of generated Algos. It is a list of dicts. Each element has the task name + (e.g. "dints_0" for dints network in fold 0) as the key and the algo object as the value. + After the training, the algo object with the ``best_metric`` will be saved as a pickle file. + + Note: + The final results of the model training will not be written to all the previously generated + algorithm's output folders. Instead, HPO will generate a new algo during the searching, and + the new algo will be saved under the working directory with a different format of the name. + For example, if the searching space has "learning_rate", the result of HPO will be written to + a folder name with original task name and the param (e.g. "dints_0_learning_rate_0.001"). + The results include the model checkpoints, a progress.yaml, accuracies in CSV and a pickle + file of the Algo object. + + """ + default_nni_config = { + "trialCodeDirectory": ".", + "trialGpuNumber": torch.cuda.device_count(), + "trialConcurrency": 1, + "maxTrialNumber": 10, + "maxExperimentDuration": "1h", + "tuner": {"name": "GridSearch"}, + "trainingService": {"platform": "local", "useActiveGpu": True}, + } + + last_total_tasks = len(import_bundle_algo_history(self.work_dir, only_trained=True)) + mode_dry_run = self.hpo_params.pop("nni_dry_run", False) + for algo_dict in history: + name = algo_dict[AlgoKeys.ID] + algo = algo_dict[AlgoKeys.ALGO] + nni_gen = NNIGen(algo=algo, params=self.hpo_params) + obj_filename = nni_gen.get_obj_filename() + nni_config = deepcopy(default_nni_config) + # override the default nni config with the same key in hpo_params + for key in self.hpo_params: + if key in nni_config: + nni_config[key] = self.hpo_params[key] + nni_config.update({"experimentName": name}) + nni_config.update({"search_space": self.search_space}) + trial_cmd = "python -m monai.apps.auto3dseg NNIGen run_algo " + obj_filename + " " + self.work_dir + nni_config.update({"trialCommand": trial_cmd}) + nni_config_filename = os.path.abspath(os.path.join(self.work_dir, f"{name}_nni_config.yaml")) + ConfigParser.export_config_file(nni_config, nni_config_filename, fmt="yaml", default_flow_style=None) + + max_trial = min(self.hpo_tasks, cast(int, default_nni_config["maxTrialNumber"])) + cmd = "nnictl create --config " + nni_config_filename + " --port 8088" + + if mode_dry_run: + logger.info(f"AutoRunner HPO is in dry-run mode. Please manually launch: {cmd}") + continue + + run_cmd(cmd.split(), check=True) + + n_trainings = len(import_bundle_algo_history(self.work_dir, only_trained=True)) + while n_trainings - last_total_tasks < max_trial: + sleep(1) + n_trainings = len(import_bundle_algo_history(self.work_dir, only_trained=True)) + + cmd = "nnictl stop --all" + run_cmd(cmd.split(), check=True) + logger.info(f"NNI completes HPO on {name}") + last_total_tasks = n_trainings + + def run(self): + """ + Run the AutoRunner pipeline + """ + # step 1: data analysis + if self.analyze and self.analyze_params is not None: + logger.info("Running data analysis...") + da = DataAnalyzer( + self.datalist_filename, self.dataroot, output_path=self.datastats_filename, **self.analyze_params + ) + da.get_all_case_stats() + + da = None # type: ignore + torch.cuda.empty_cache() + + self.export_cache(analyze=True, datastats=self.datastats_filename) + else: + logger.info("Skipping data analysis...") + + # step 2: algorithm generation + if self.algo_gen: + if not os.path.isfile(self.datastats_filename): + raise ValueError( + f"Could not find the datastats file {self.datastats_filename}. " + "Possibly the required data analysis step was not completed." + ) + + bundle_generator = BundleGen( + algos=self.algos, + algo_path=self.work_dir, + templates_path_or_url=self.templates_path_or_url, + data_stats_filename=self.datastats_filename, + data_src_cfg_name=self.data_src_cfg_name, + mlflow_tracking_uri=self.mlflow_tracking_uri, + mlflow_experiment_name=self.mlflow_experiment_name, + ) + + if self.gpu_customization: + bundle_generator.generate( + self.work_dir, + num_fold=self.num_fold, + gpu_customization=self.gpu_customization, + gpu_customization_specs=self.gpu_customization_specs, + allow_skip=self.allow_skip, + ) + else: + bundle_generator.generate(self.work_dir, num_fold=self.num_fold, allow_skip=self.allow_skip) + history = bundle_generator.get_history() + export_bundle_algo_history(history) + self.export_cache(algo_gen=True) + else: + logger.info("Skipping algorithm generation...") + + # step 3: algo training + auto_train_choice = self.train is None + if self.train or (auto_train_choice and not self.cache["train"]): + history = import_bundle_algo_history(self.work_dir, only_trained=False) + + if len(history) == 0: + raise ValueError( + f"Could not find training scripts in {self.work_dir}. " + "Possibly the required algorithms generation step was not completed." + ) + + if auto_train_choice: + skip_algos = [h[AlgoKeys.ID] for h in history if h[AlgoKeys.IS_TRAINED]] + if skip_algos: + logger.info( + f"Skipping already trained algos {skip_algos}." + "Set option train=True to always retrain all algos." + ) + history = [h for h in history if not h[AlgoKeys.IS_TRAINED]] + + if len(history) > 0: + if not self.hpo: + self._train_algo_in_sequence(history) + else: + self._train_algo_in_nni(history) + + self.export_cache(train=True) + else: + logger.info("Skipping algorithm training...") + + # step 4: model ensemble and write the prediction to disks. + if self.ensemble: + ensemble_runner = EnsembleRunner( + data_src_cfg_name=self.data_src_cfg_name, + work_dir=self.work_dir, + num_fold=self.num_fold, + ensemble_method_name=self.ensemble_method_name, + mgpu=int(self.device_setting["n_devices"]) > 1, + **self.kwargs, # for set_image_save_transform + **self.pred_params, + ) # for inference + ensemble_runner.run(self.device_setting) + logger.info("Auto3Dseg pipeline is completed successfully.") diff --git a/source_code/SegMamba/monai/apps/auto3dseg/bundle_gen.py b/source_code/SegMamba/monai/apps/auto3dseg/bundle_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..8a54d18be7e2a4d192ef9d6a34ed56ee4fc9472b --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/bundle_gen.py @@ -0,0 +1,665 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import importlib +import os +import re +import shutil +import subprocess +import sys +import time +import warnings +from copy import deepcopy +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Any +from urllib.parse import urlparse + +import torch + +from monai.apps import download_and_extract +from monai.apps.utils import get_logger +from monai.auto3dseg.algo_gen import Algo, AlgoGen +from monai.auto3dseg.utils import ( + _prepare_cmd_bcprun, + _prepare_cmd_default, + _prepare_cmd_torchrun, + _run_cmd_bcprun, + _run_cmd_torchrun, + algo_to_pickle, +) +from monai.bundle.config_parser import ConfigParser +from monai.config import PathLike +from monai.utils import ensure_tuple, look_up_option, run_cmd +from monai.utils.enums import AlgoKeys +from monai.utils.misc import MONAIEnvVars + +logger = get_logger(module_name=__name__) +ALGO_HASH = MONAIEnvVars.algo_hash() + +__all__ = ["BundleAlgo", "BundleGen"] + + +class BundleAlgo(Algo): + """ + An algorithm represented by a set of bundle configurations and scripts. + + ``BundleAlgo.cfg`` is a ``monai.bundle.ConfigParser`` instance. + + .. code-block:: python + + from monai.apps.auto3dseg import BundleAlgo + + data_stats_yaml = "../datastats.yaml" + algo = BundleAlgo(template_path="../algorithm_templates") + algo.set_data_stats(data_stats_yaml) + # algo.set_data_src("../data_src.json") + algo.export_to_disk(".", algo_name="segresnet2d_1") + + This class creates MONAI bundles from a directory of 'bundle template'. Different from the regular MONAI bundle + format, the bundle template may contain placeholders that must be filled using ``fill_template_config`` during + ``export_to_disk``. Then created bundle keeps the same file structure as the template. + + """ + + def __init__(self, template_path: PathLike): + """ + Create an Algo instance based on the predefined Algo template. + + Args: + template_path: path to a folder that contains the algorithm templates. + Please check https://github.com/Project-MONAI/research-contributions/tree/main/auto3dseg/algorithm_templates + + """ + + self.template_path = template_path + self.data_stats_files = "" + self.data_list_file = "" + self.mlflow_tracking_uri: str | None = None + self.mlflow_experiment_name: str | None = None + self.output_path = "" + self.name = "" + self.best_metric = None + # track records when filling template config: {"": {"": value, ...}, ...} + self.fill_records: dict = {} + # device_setting set default value and sanity check, in case device_setting not from autorunner + self.device_setting: dict[str, int | str] = { + "CUDA_VISIBLE_DEVICES": ",".join([str(x) for x in range(torch.cuda.device_count())]), + "n_devices": int(torch.cuda.device_count()), + "NUM_NODES": int(os.environ.get("NUM_NODES", 1)), + "MN_START_METHOD": os.environ.get("MN_START_METHOD", "bcprun"), + "CMD_PREFIX": os.environ.get("CMD_PREFIX", ""), + } + + def pre_check_skip_algo(self, skip_bundlegen: bool = False, skip_info: str = "") -> tuple[bool, str]: + """ + Analyse the data analysis report and check if the algorithm needs to be skipped. + This function is overriden within algo. + Args: + skip_bundlegen: skip generating bundles for this algo if true. + skip_info: info to print when skipped. + """ + return skip_bundlegen, skip_info + + def set_data_stats(self, data_stats_files: str) -> None: + """ + Set the data analysis report (generated by DataAnalyzer). + + Args: + data_stats_files: path to the datastats yaml file + """ + self.data_stats_files = data_stats_files + + def set_data_source(self, data_src_cfg: str) -> None: + """ + Set the data source configuration file + + Args: + data_src_cfg: path to a configuration file (yaml) that contains datalist, dataroot, and other params. + The config will be in a form of {"modality": "ct", "datalist": "path_to_json_datalist", "dataroot": + "path_dir_data"} + """ + self.data_list_file = data_src_cfg + + def set_mlflow_tracking_uri(self, mlflow_tracking_uri: str | None) -> None: + """ + Set the tracking URI for MLflow server + + Args: + mlflow_tracking_uri: a tracking URI for MLflow server which could be local directory or address of + the remote tracking Server; MLflow runs will be recorded locally in algorithms' model folder if + the value is None. + """ + self.mlflow_tracking_uri = mlflow_tracking_uri + + def set_mlflow_experiment_name(self, mlflow_experiment_name: str | None) -> None: + """ + Set the experiment name for MLflow server + + Args: + mlflow_experiment_name: a string to specify the experiment name for MLflow server. + """ + self.mlflow_experiment_name = mlflow_experiment_name + + def fill_template_config(self, data_stats_filename: str, algo_path: str, **kwargs: Any) -> dict: + """ + The configuration files defined when constructing this Algo instance might not have a complete training + and validation pipelines. Some configuration components and hyperparameters of the pipelines depend on the + training data and other factors. This API is provided to allow the creation of fully functioning config files. + Return the records of filling template config: {"": {"": value, ...}, ...}. + + Args: + data_stats_filename: filename of the data stats report (generated by DataAnalyzer) + + Notes: + Template filling is optional. The user can construct a set of pre-filled configs without replacing values + by using the data analysis results. It is also intended to be re-implemented in subclasses of BundleAlgo + if the user wants their own way of auto-configured template filling. + """ + return {} + + def export_to_disk(self, output_path: str, algo_name: str, **kwargs: Any) -> None: + """ + Fill the configuration templates, write the bundle (configs + scripts) to folder `output_path/algo_name`. + + Args: + output_path: Path to export the 'scripts' and 'configs' directories. + algo_name: the identifier of the algorithm (usually contains the name and extra info like fold ID). + kwargs: other parameters, including: "copy_dirs=True/False" means whether to copy the template as output + instead of inplace operation, "fill_template=True/False" means whether to fill the placeholders + in the template. other parameters are for `fill_template_config` function. + + """ + if kwargs.pop("copy_dirs", True): + self.output_path = os.path.join(output_path, algo_name) + os.makedirs(self.output_path, exist_ok=True) + if os.path.isdir(self.output_path): + shutil.rmtree(self.output_path) + # copy algorithm_templates/ to the working directory output_path + shutil.copytree(os.path.join(str(self.template_path), self.name), self.output_path) + else: + self.output_path = str(self.template_path) + if kwargs.pop("fill_template", True): + self.fill_records = self.fill_template_config(self.data_stats_files, self.output_path, **kwargs) + logger.info(f"Generated:{self.output_path}") + + def _create_cmd(self, train_params: None | dict = None) -> tuple[str, str]: + """ + Create the command to execute training. + + """ + if train_params is None: + train_params = {} + params = deepcopy(train_params) + + train_py = os.path.join(self.output_path, "scripts", "train.py") + config_dir = os.path.join(self.output_path, "configs") + + config_files = [] + if os.path.isdir(config_dir): + for file in sorted(os.listdir(config_dir)): + if file.endswith("yaml") or file.endswith("json"): + # Python Fire may be confused by single-quoted WindowsPath + config_files.append(Path(os.path.join(config_dir, file)).as_posix()) + + if int(self.device_setting["NUM_NODES"]) > 1: + # multi-node command + # only bcprun is supported for now + try: + look_up_option(self.device_setting["MN_START_METHOD"], ["bcprun"]) + except ValueError as err: + raise NotImplementedError( + f"{self.device_setting['MN_START_METHOD']} is not supported yet." + "Try modify BundleAlgo._create_cmd for your cluster." + ) from err + + return ( + _prepare_cmd_bcprun( + f"{train_py} run", + cmd_prefix=f"{self.device_setting['CMD_PREFIX']}", + config_file=config_files, + **params, + ), + "", + ) + elif int(self.device_setting["n_devices"]) > 1: + return _prepare_cmd_torchrun(f"{train_py} run", config_file=config_files, **params), "" + else: + return ( + _prepare_cmd_default( + f"{train_py} run", + cmd_prefix=f"{self.device_setting['CMD_PREFIX']}", + config_file=config_files, + **params, + ), + "", + ) + + def _run_cmd(self, cmd: str, devices_info: str = "") -> subprocess.CompletedProcess: + """ + Execute the training command with target devices information. + + """ + if devices_info: + warnings.warn(f"input devices_info {devices_info} is deprecated and ignored.") + + ps_environ = os.environ.copy() + ps_environ["CUDA_VISIBLE_DEVICES"] = str(self.device_setting["CUDA_VISIBLE_DEVICES"]) + + # delete pattern "VAR=VALUE" at the beginning of the string, with optional leading/trailing whitespaces + cmd = re.sub(r"^\s*\w+=.*?\s+", "", cmd) + + if int(self.device_setting["NUM_NODES"]) > 1: + try: + look_up_option(self.device_setting["MN_START_METHOD"], ["bcprun"]) + except ValueError as err: + raise NotImplementedError( + f"{self.device_setting['MN_START_METHOD']} is not supported yet." + "Try modify BundleAlgo._run_cmd for your cluster." + ) from err + + return _run_cmd_bcprun(cmd, n=self.device_setting["NUM_NODES"], p=self.device_setting["n_devices"]) + elif int(self.device_setting["n_devices"]) > 1: + return _run_cmd_torchrun( + cmd, nnodes=1, nproc_per_node=self.device_setting["n_devices"], env=ps_environ, check=True + ) + else: + return run_cmd(cmd.split(), run_cmd_verbose=True, env=ps_environ, check=True) + + def train( + self, train_params: None | dict = None, device_setting: None | dict = None + ) -> subprocess.CompletedProcess: + """ + Load the run function in the training script of each model. Training parameter is predefined by the + algo_config.yaml file, which is pre-filled by the fill_template_config function in the same instance. + + Args: + train_params: training parameters + device_setting: device related settings, should follow the device_setting in auto_runner.set_device_info. + 'CUDA_VISIBLE_DEVICES' should be a string e.g. '0,1,2,3' + """ + if device_setting is not None: + self.device_setting.update(device_setting) + self.device_setting["n_devices"] = len(str(self.device_setting["CUDA_VISIBLE_DEVICES"]).split(",")) + + if train_params is not None and "CUDA_VISIBLE_DEVICES" in train_params: + warnings.warn("CUDA_VISIBLE_DEVICES is deprecated from train_params!") + train_params.pop("CUDA_VISIBLE_DEVICES") + + cmd, _unused_return = self._create_cmd(train_params) + return self._run_cmd(cmd) + + def get_score(self, *args, **kwargs): + """ + Returns validation scores of the model trained by the current Algo. + """ + config_yaml = os.path.join(self.output_path, "configs", "hyper_parameters.yaml") + parser = ConfigParser() + parser.read_config(config_yaml) + ckpt_path = parser.get_parsed_content("ckpt_path", default=self.output_path) + + dict_file = ConfigParser.load_config_file(os.path.join(ckpt_path, "progress.yaml")) + # dict_file: a list of scores saved in the form of dict in progress.yaml + return dict_file[-1]["best_avg_dice_score"] # the last one is the best one + + def get_inferer(self, *args, **kwargs): + """ + Load the InferClass from the infer.py. The InferClass should be defined in the template under the path of + `"scripts/infer.py"`. It is required to define the "InferClass" (name is fixed) with two functions at least + (``__init__`` and ``infer``). The init class has an override kwargs that can be used to override parameters in + the run-time optionally. + + Examples: + + .. code-block:: python + + class InferClass + def __init__(self, config_file: Optional[Union[str, Sequence[str]]] = None, **override): + # read configs from config_file (sequence) + # set up transforms + # set up model + # set up other hyper parameters + return + + @torch.no_grad() + def infer(self, image_file): + # infer the model and save the results to output + return output + + """ + infer_py = os.path.join(self.output_path, "scripts", "infer.py") + if not os.path.isfile(infer_py): + raise ValueError(f"{infer_py} is not found, please check the path.") + + config_dir = os.path.join(self.output_path, "configs") + configs_path = [os.path.join(config_dir, f) for f in os.listdir(config_dir)] + + spec = importlib.util.spec_from_file_location("InferClass", infer_py) + infer_class = importlib.util.module_from_spec(spec) # type: ignore + sys.modules["InferClass"] = infer_class + spec.loader.exec_module(infer_class) # type: ignore + return infer_class.InferClass(configs_path, *args, **kwargs) + + def predict(self, predict_files: list, predict_params: dict | None = None) -> list: + """ + Use the trained model to predict the outputs with a given input image. + + Args: + predict_files: a list of paths to files to run inference on ["path_to_image_1", "path_to_image_2"] + predict_params: a dict to override the parameters in the bundle config (including the files to predict). + + """ + params = {} if predict_params is None else deepcopy(predict_params) + inferer = self.get_inferer(**params) + return [inferer.infer(f) for f in ensure_tuple(predict_files)] + + def get_output_path(self): + """Returns the algo output paths to find the algo scripts and configs.""" + return self.output_path + + +# path to download the algo_templates +default_algo_zip = ( + f"https://github.com/Project-MONAI/research-contributions/releases/download/algo_templates/{ALGO_HASH}.tar.gz" +) + +# default algorithms +default_algos = { + "segresnet2d": dict(_target_="segresnet2d.scripts.algo.Segresnet2dAlgo"), + "dints": dict(_target_="dints.scripts.algo.DintsAlgo"), + "swinunetr": dict(_target_="swinunetr.scripts.algo.SwinunetrAlgo"), + "segresnet": dict(_target_="segresnet.scripts.algo.SegresnetAlgo"), +} + + +def _download_algos_url(url: str, at_path: str) -> dict[str, dict[str, str]]: + """ + Downloads the algorithm templates release archive, and extracts it into a parent directory of the at_path folder. + Returns a dictionary of the algorithm templates. + """ + at_path = os.path.abspath(at_path) + zip_download_dir = TemporaryDirectory() + algo_compressed_file = os.path.join(zip_download_dir.name, "algo_templates.tar.gz") + + download_attempts = 3 + for i in range(download_attempts): + try: + download_and_extract(url=url, filepath=algo_compressed_file, output_dir=os.path.dirname(at_path)) + except Exception as e: + msg = f"Download and extract of {url} failed, attempt {i+1}/{download_attempts}." + if i < download_attempts - 1: + warnings.warn(msg) + time.sleep(i) + else: + zip_download_dir.cleanup() + raise ValueError(msg) from e + else: + break + + zip_download_dir.cleanup() + + algos_all = deepcopy(default_algos) + for name in algos_all: + algos_all[name]["template_path"] = at_path + + return algos_all + + +def _copy_algos_folder(folder, at_path): + """ + Copies the algorithm templates folder to at_path. + Returns a dictionary of algorithm templates. + """ + folder = os.path.abspath(folder) + at_path = os.path.abspath(at_path) + + if folder != at_path: + if os.path.exists(at_path): + shutil.rmtree(at_path) + shutil.copytree(folder, at_path) + + algos_all = {} + for name in os.listdir(at_path): + if os.path.exists(os.path.join(folder, name, "scripts", "algo.py")): + algos_all[name] = dict(_target_=f"{name}.scripts.algo.{name.capitalize()}Algo", template_path=at_path) + logger.info(f"Copying template: {name} -- {algos_all[name]}") + if not algos_all: + raise ValueError(f"Unable to find any algos in {folder}") + + return algos_all + + +class BundleGen(AlgoGen): + """ + This class generates a set of bundles according to the cross-validation folds, each of them can run independently. + + Args: + algo_path: the directory path to save the algorithm templates. Default is the current working dir. + algos: If dictionary, it outlines the algorithm to use. If a list or a string, defines a subset of names of + the algorithms to use, e.g. ('segresnet', 'dints') out of the full set of algorithm templates provided + by templates_path_or_url. Defaults to None - to use all available algorithms. + templates_path_or_url: the folder with the algorithm templates or a url. If None provided, the default template + zip url will be downloaded and extracted into the algo_path. The current default options are released at: + https://github.com/Project-MONAI/research-contributions/tree/main/auto3dseg. + data_stats_filename: the path to the data stats file (generated by DataAnalyzer). + data_src_cfg_name: the path to the data source config YAML file. The config will be in a form of + {"modality": "ct", "datalist": "path_to_json_datalist", "dataroot": "path_dir_data"}. + mlflow_tracking_uri: a tracking URI for MLflow server which could be local directory or address of + the remote tracking Server; MLflow runs will be recorded locally in algorithms' model folder if + the value is None. + mlfow_experiment_name: a string to specify the experiment name for MLflow server. + .. code-block:: bash + + python -m monai.apps.auto3dseg BundleGen generate --data_stats_filename="../algorithms/datastats.yaml" + """ + + def __init__( + self, + algo_path: str = ".", + algos: dict | list | str | None = None, + templates_path_or_url: str | None = None, + data_stats_filename: str | None = None, + data_src_cfg_name: str | None = None, + mlflow_tracking_uri: str | None = None, + mlflow_experiment_name: str | None = None, + ): + if algos is None or isinstance(algos, (list, tuple, str)): + if templates_path_or_url is None: + templates_path_or_url = default_algo_zip + + at_path = os.path.join(os.path.abspath(algo_path), "algorithm_templates") + + if os.path.isdir(templates_path_or_url): + # if a local folder, copy if necessary + logger.info(f"BundleGen from directory {templates_path_or_url}") + algos_all = _copy_algos_folder(folder=templates_path_or_url, at_path=at_path) + elif urlparse(templates_path_or_url).scheme in ("http", "https"): + # if url, trigger the download and extract process + logger.info(f"BundleGen from {templates_path_or_url}") + algos_all = _download_algos_url(url=templates_path_or_url, at_path=at_path) + else: + raise ValueError(f"{self.__class__} received invalid templates_path_or_url: {templates_path_or_url}") + + if algos is not None: + algos = {k: v for k, v in algos_all.items() if k in ensure_tuple(algos)} # keep only provided + if len(algos) == 0: + raise ValueError(f"Unable to find provided algos in {algos_all}") + else: + algos = algos_all + + self.algos: Any = [] + if isinstance(algos, dict): + for algo_name, algo_params in sorted(algos.items()): + template_path = algo_params.get("template_path", ".") + if len(template_path) > 0 and template_path not in sys.path: + sys.path.append(template_path) + + try: + onealgo = ConfigParser(algo_params).get_parsed_content() + onealgo.name = algo_name + self.algos.append(onealgo) + except RuntimeError as e: + msg = """Please make sure the folder structure of an Algo Template follows + [algo_name] + ├── configs + │ ├── hyper_parameters.yaml # automatically generated yaml from a set of ``template_configs`` + └── scripts + ├── test.py + ├── __init__.py + └── validate.py + """ + raise RuntimeError(msg) from e + else: + raise ValueError("Unexpected error algos is not a dict") + + self.data_stats_filename = data_stats_filename + self.data_src_cfg_name = data_src_cfg_name + self.mlflow_tracking_uri = mlflow_tracking_uri + self.mlflow_experiment_name = mlflow_experiment_name + self.history: list[dict] = [] + + def set_data_stats(self, data_stats_filename: str) -> None: + """ + Set the data stats filename + + Args: + data_stats_filename: filename of datastats + """ + self.data_stats_filename = data_stats_filename + + def get_data_stats(self): + """Get the filename of the data stats""" + return self.data_stats_filename + + def set_data_src(self, data_src_cfg_name): + """ + Set the data source filename + + Args: + data_src_cfg_name: filename of data_source file + """ + self.data_src_cfg_name = data_src_cfg_name + + def get_data_src(self): + """Get the data source filename""" + return self.data_src_cfg_name + + def set_mlflow_tracking_uri(self, mlflow_tracking_uri): + """ + Set the tracking URI for MLflow server + + Args: + mlflow_tracking_uri: a tracking URI for MLflow server which could be local directory or address of + the remote tracking Server; MLflow runs will be recorded locally in algorithms' model folder if + the value is None. + """ + self.mlflow_tracking_uri = mlflow_tracking_uri + + def set_mlflow_experiment_name(self, mlflow_experiment_name): + """ + Set the experiment name for MLflow server + + Args: + mlflow_experiment_name: a string to specify the experiment name for MLflow server. + """ + self.mlflow_experiment_name = mlflow_experiment_name + + def get_mlflow_tracking_uri(self): + """Get the tracking URI for MLflow server""" + return self.mlflow_tracking_uri + + def get_mlflow_experiment_name(self): + """Get the experiment name for MLflow server""" + return self.mlflow_experiment_name + + def get_history(self) -> list: + """Get the history of the bundleAlgo object with their names/identifiers""" + return self.history + + def generate( + self, + output_folder: str = ".", + num_fold: int = 5, + gpu_customization: bool = False, + gpu_customization_specs: dict[str, Any] | None = None, + allow_skip: bool = True, + ) -> None: + """ + Generate the bundle scripts/configs for each bundleAlgo + + Args: + output_folder: the output folder to save each algorithm. + num_fold: the number of cross validation fold. + gpu_customization: the switch to determine automatically customize/optimize bundle script/config + parameters for each bundleAlgo based on gpus. Custom parameters are obtained through dummy + training to simulate the actual model training process and hyperparameter optimization (HPO) + experiments. + gpu_customization_specs: the dictionary to enable users overwrite the HPO settings. user can + overwrite part of variables as follows or all of them. The structure is as follows. + allow_skip: a switch to determine if some Algo in the default templates can be skipped based on the + analysis on the dataset from Auto3DSeg DataAnalyzer. + + .. code-block:: python + + gpu_customization_specs = { + 'ALGO': { + 'num_trials': 6, + 'range_num_images_per_batch': [1, 20], + 'range_num_sw_batch_size': [1, 20] + } + } + + ALGO: the name of algorithm. It could be one of algorithm names (e.g., 'dints') or 'universal' which + would apply changes to all algorithms. Possible options are + + - {``"universal"``, ``"dints"``, ``"segresnet"``, ``"segresnet2d"``, ``"swinunetr"``}. + + num_trials: the number of HPO trials/experiments to run. + range_num_images_per_batch: the range of number of images per mini-batch. + range_num_sw_batch_size: the range of batch size in sliding-window inferer. + """ + fold_idx = list(range(num_fold)) + for algo in self.algos: + for f_id in ensure_tuple(fold_idx): + data_stats = self.get_data_stats() + data_src_cfg = self.get_data_src() + mlflow_tracking_uri = self.get_mlflow_tracking_uri() + mlflow_experiment_name = self.get_mlflow_experiment_name() + gen_algo = deepcopy(algo) + gen_algo.set_data_stats(data_stats) + gen_algo.set_data_source(data_src_cfg) + gen_algo.set_mlflow_tracking_uri(mlflow_tracking_uri) + gen_algo.set_mlflow_experiment_name(mlflow_experiment_name) + name = f"{gen_algo.name}_{f_id}" + + if allow_skip: + skip_bundlegen, skip_info = gen_algo.pre_check_skip_algo() + if skip_bundlegen: + logger.info(f"{name} is skipped! {skip_info}") + continue + + if gpu_customization: + gen_algo.export_to_disk( + output_folder, + name, + fold=f_id, + gpu_customization=True, + gpu_customization_specs=gpu_customization_specs, + ) + else: + gen_algo.export_to_disk(output_folder, name, fold=f_id) + + algo_to_pickle(gen_algo, template_path=algo.template_path) + self.history.append( + {AlgoKeys.ID: name, AlgoKeys.ALGO: gen_algo} + ) # track the previous, may create a persistent history diff --git a/source_code/SegMamba/monai/apps/auto3dseg/data_analyzer.py b/source_code/SegMamba/monai/apps/auto3dseg/data_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..15e56abfea4c7e37148402e378368afae24f948a --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/data_analyzer.py @@ -0,0 +1,386 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from os import path +from typing import Any, cast + +import numpy as np +import torch +from torch.multiprocessing import get_context + +from monai.apps.auto3dseg.transforms import EnsureSameShaped +from monai.apps.utils import get_logger +from monai.auto3dseg import SegSummarizer +from monai.auto3dseg.utils import datafold_read +from monai.bundle import config_parser +from monai.bundle.config_parser import ConfigParser +from monai.data import DataLoader, Dataset, partition_dataset +from monai.data.utils import no_collation +from monai.transforms import Compose, EnsureTyped, LoadImaged, Orientationd +from monai.utils import ImageMetaKey, StrEnum, min_version, optional_import +from monai.utils.enums import DataStatsKeys, ImageStatsKeys + + +def strenum_representer(dumper, data): + return dumper.represent_scalar("tag:yaml.org,2002:str", data.value) + + +if optional_import("yaml")[1]: + config_parser.yaml.SafeDumper.add_multi_representer(StrEnum, strenum_representer) + +tqdm, has_tqdm = optional_import("tqdm", "4.47.0", min_version, "tqdm") +logger = get_logger(module_name=__name__) + +__all__ = ["DataAnalyzer"] + + +class DataAnalyzer: + """ + The DataAnalyzer automatically analyzes given medical image dataset and reports the statistics. + The module expects file paths to the image data and utilizes the LoadImaged transform to read the + files, which supports nii, nii.gz, png, jpg, bmp, npz, npy, and dcm formats. Currently, only + segmentation task is supported, so the user needs to provide paths to the image and label files + (if have). Also, label data format is preferred to be (1,H,W,D), with the label index in the + first dimension. If it is in onehot format, it will be converted to the preferred format. + + Args: + datalist: a Python dictionary storing group, fold, and other information of the medical + image dataset, or a string to the JSON file storing the dictionary. + dataroot: user's local directory containing the datasets. + output_path: path to save the analysis result. + average: whether to average the statistical value across different image modalities. + do_ccp: apply the connected component algorithm to process the labels/images + device: a string specifying hardware (CUDA/CPU) utilized for the operations. + worker: number of workers to use for loading datasets in each GPU/CPU sub-process. + image_key: a string that user specify for the image. The DataAnalyzer will look it up in the + datalist to locate the image files of the dataset. + label_key: a string that user specify for the label. The DataAnalyzer will look it up in the + datalist to locate the label files of the dataset. If label_key is NoneType or "None", + the DataAnalyzer will skip looking for labels and all label-related operations. + hist_bins: bins to compute histogram for each image channel. + hist_range: ranges to compute histogram for each image channel. + fmt: format used to save the analysis results. Currently support ``"json"`` and ``"yaml"``, defaults to "yaml". + histogram_only: whether to only compute histograms. Defaults to False. + extra_params: other optional arguments. Currently supported arguments are : + 'allowed_shape_difference' (default 5) can be used to change the default tolerance of + the allowed shape differences between the image and label items. In case of shape mismatch below + the tolerance, the label image will be resized to match the image using nearest interpolation. + + + Examples: + .. code-block:: python + + from monai.apps.auto3dseg.data_analyzer import DataAnalyzer + + datalist = { + "testing": [{"image": "image_003.nii.gz"}], + "training": [ + {"fold": 0, "image": "image_001.nii.gz", "label": "label_001.nii.gz"}, + {"fold": 0, "image": "image_002.nii.gz", "label": "label_002.nii.gz"}, + {"fold": 1, "image": "image_001.nii.gz", "label": "label_001.nii.gz"}, + {"fold": 1, "image": "image_004.nii.gz", "label": "label_004.nii.gz"}, + ], + } + + dataroot = '/datasets' # the directory where you have the image files (nii.gz) + DataAnalyzer(datalist, dataroot) + + Notes: + The module can also be called from the command line interface (CLI). + + For example: + + .. code-block:: bash + + python -m monai.apps.auto3dseg \\ + DataAnalyzer \\ + get_all_case_stats \\ + --datalist="my_datalist.json" \\ + --dataroot="my_dataroot_dir" + + """ + + def __init__( + self, + datalist: str | dict, + dataroot: str = "", + output_path: str = "./datastats.yaml", + average: bool = True, + do_ccp: bool = False, + device: str | torch.device = "cuda", + worker: int = 4, + image_key: str = "image", + label_key: str | None = "label", + hist_bins: list | int | None = 0, + hist_range: list | None = None, + fmt: str = "yaml", + histogram_only: bool = False, + **extra_params: Any, + ): + if path.isfile(output_path): + warnings.warn(f"File {output_path} already exists and will be overwritten.") + logger.debug(f"{output_path} will be overwritten by a new datastat.") + + self.datalist = datalist + self.dataroot = dataroot + self.output_path = output_path + self.average = average + self.do_ccp = do_ccp + self.device = torch.device(device) + self.worker = worker + self.image_key = image_key + self.label_key = None if label_key == "None" else label_key + self.hist_bins = hist_bins + self.hist_range: list = [-500, 500] if hist_range is None else hist_range + self.fmt = fmt + self.histogram_only = histogram_only + self.extra_params = extra_params + + @staticmethod + def _check_data_uniformity(keys: list[str], result: dict) -> bool: + """ + Check data uniformity since DataAnalyzer provides no support to multi-modal images with different + affine matrices/spacings due to monai transforms. + + Args: + keys: a list of string-type keys under image_stats dictionary. + + Returns: + False if one of the selected key values is not constant across the dataset images. + + """ + + if DataStatsKeys.SUMMARY not in result or DataStatsKeys.IMAGE_STATS not in result[DataStatsKeys.SUMMARY]: + return True + constant_props = [result[DataStatsKeys.SUMMARY][DataStatsKeys.IMAGE_STATS][key] for key in keys] + for prop in constant_props: + if "stdev" in prop and np.any(prop["stdev"]): + logger.debug(f"summary image_stats {prop} has non-zero stdev {prop['stdev']}.") + return False + + return True + + def get_all_case_stats(self, key="training", transform_list=None): + """ + Get all case stats. Caller of the DataAnalyser class. The function initiates multiple GPU or CPU processes of the internal + _get_all_case_stats functions, which iterates datalist and call SegSummarizer to generate stats for each case. + After all case stats are generated, SegSummarizer is called to combine results. + + Args: + key: dataset key + transform_list: option list of transforms before SegSummarizer + + Returns: + A data statistics dictionary containing + "stats_summary" (summary statistics of the entire datasets). Within stats_summary + there are "image_stats" (summarizing info of shape, channel, spacing, and etc + using operations_summary), "image_foreground_stats" (info of the intensity for the + non-zero labeled voxels), and "label_stats" (info of the labels, pixel percentage, + image_intensity, and each individual label in a list) + "stats_by_cases" (List type value. Each element of the list is statistics of + an image-label info. Within each element, there are: "image" (value is the + path to an image), "label" (value is the path to the corresponding label), "image_stats" + (summarizing info of shape, channel, spacing, and etc using operations), + "image_foreground_stats" (similar to the previous one but one foreground image), and + "label_stats" (stats of the individual labels ) + + Notes: + Since the backend of the statistics computation are torch/numpy, nan/inf value + may be generated and carried over in the computation. In such cases, the output + dictionary will include .nan/.inf in the statistics. + + """ + result: dict[DataStatsKeys, Any] = {DataStatsKeys.SUMMARY: {}, DataStatsKeys.BY_CASE: []} + result_bycase: dict[DataStatsKeys, Any] = {DataStatsKeys.SUMMARY: {}, DataStatsKeys.BY_CASE: []} + if self.device.type == "cpu": + nprocs = 1 + logger.info("Using CPU for data analyzing!") + else: + nprocs = torch.cuda.device_count() + logger.info(f"Found {nprocs} GPUs for data analyzing!") + if nprocs > 1: + tmp_ctx: Any = get_context("forkserver") + with tmp_ctx.Manager() as manager: + manager_list = manager.list() + processes = [] + for rank in range(nprocs): + p = tmp_ctx.Process( + target=self._get_all_case_stats, args=(rank, nprocs, manager_list, key, transform_list) + ) + processes.append(p) + for p in processes: + p.start() + for p in processes: + p.join() + # merge DataStatsKeys.BY_CASE + for _ in manager_list: + result_bycase[DataStatsKeys.BY_CASE].extend(_[DataStatsKeys.BY_CASE]) + else: + result_bycase = self._get_all_case_stats(0, 1, None, key, transform_list) + + summarizer = SegSummarizer( + self.image_key, + self.label_key, + average=self.average, + do_ccp=self.do_ccp, + hist_bins=self.hist_bins, + hist_range=self.hist_range, + histogram_only=self.histogram_only, + ) + n_cases = len(result_bycase[DataStatsKeys.BY_CASE]) + result[DataStatsKeys.SUMMARY] = summarizer.summarize(cast(list, result_bycase[DataStatsKeys.BY_CASE])) + result[DataStatsKeys.SUMMARY]["n_cases"] = n_cases + result_bycase[DataStatsKeys.SUMMARY] = result[DataStatsKeys.SUMMARY] + if not self._check_data_uniformity([ImageStatsKeys.SPACING], result): + logger.info("Data spacing is not completely uniform. MONAI transforms may provide unexpected result") + if self.output_path: + logger.info(f"Writing data stats to {self.output_path}.") + ConfigParser.export_config_file( + result, self.output_path, fmt=self.fmt, default_flow_style=None, sort_keys=False + ) + by_case_path = self.output_path.replace(f".{self.fmt}", f"_by_case.{self.fmt}") + if by_case_path == self.output_path: # self.output_path not ended with self.fmt? + by_case_path += f".by_case.{self.fmt}" + logger.info(f"Writing by-case data stats to {by_case_path}, this may take a while.") + ConfigParser.export_config_file( + result_bycase, by_case_path, fmt=self.fmt, default_flow_style=None, sort_keys=False + ) + # release memory + if self.device.type == "cuda": + # release unreferenced tensors to mitigate OOM + # limitation: https://github.com/pytorch/pytorch/issues/12873#issuecomment-482916237 + torch.cuda.empty_cache() + result[DataStatsKeys.BY_CASE] = result_bycase[DataStatsKeys.BY_CASE] + return result + + def _get_all_case_stats( + self, + rank: int = 0, + world_size: int = 1, + manager_list: list | None = None, + key: str = "training", + transform_list: list | None = None, + ) -> Any: + """ + Get all case stats from a partitioned datalist. The function can only be called internally by get_all_case_stats. + Args: + rank: GPU process rank, 0 for CPU process + world_size: total number of GPUs, 1 for CPU process + manager_list: multiprocessing manager list object, if using multi-GPU. + key: dataset key + transform_list: option list of transforms before SegSummarizer + """ + summarizer = SegSummarizer( + self.image_key, + self.label_key, + average=self.average, + do_ccp=self.do_ccp, + hist_bins=self.hist_bins, + hist_range=self.hist_range, + histogram_only=self.histogram_only, + ) + keys = list(filter(None, [self.image_key, self.label_key])) + if transform_list is None: + transform_list = [ + LoadImaged(keys=keys, ensure_channel_first=True, image_only=True), + EnsureTyped(keys=keys, data_type="tensor", dtype=torch.float), + Orientationd(keys=keys, axcodes="RAS"), + ] + if self.label_key is not None: + allowed_shape_difference = self.extra_params.pop("allowed_shape_difference", 5) + transform_list.append( + EnsureSameShaped( + keys=self.label_key, + source_key=self.image_key, + allowed_shape_difference=allowed_shape_difference, + ) + ) + + transform = Compose(transform_list) + files, _ = datafold_read(datalist=self.datalist, basedir=self.dataroot, fold=-1, key=key) + if world_size <= len(files): + files = partition_dataset(data=files, num_partitions=world_size)[rank] + else: + files = partition_dataset(data=files, num_partitions=len(files))[rank] if rank < len(files) else [] + dataset = Dataset(data=files, transform=transform) + dataloader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=self.worker, + collate_fn=no_collation, + pin_memory=self.device.type == "cuda", + ) + result_bycase: dict[DataStatsKeys, Any] = {DataStatsKeys.SUMMARY: {}, DataStatsKeys.BY_CASE: []} + device = self.device if self.device.type == "cpu" else torch.device("cuda", rank) + if device.type == "cuda" and not (torch.cuda.is_available() and torch.cuda.device_count() > 0): + logger.info(f"device={device} but CUDA device is not available, using CPU instead.") + device = torch.device("cpu") + if not has_tqdm: + warnings.warn("tqdm is not installed. not displaying the caching progress.") + + for batch_data in tqdm(dataloader) if (has_tqdm and rank == 0) else dataloader: + batch_data = batch_data[0] + try: + batch_data[self.image_key] = batch_data[self.image_key].to(device) + _label_argmax = False + if self.label_key is not None: + label = batch_data[self.label_key] + label = torch.argmax(label, dim=0) if label.shape[0] > 1 else label[0] + _label_argmax = True # track if label is argmaxed + batch_data[self.label_key] = label.to(device) + d = summarizer(batch_data) + except BaseException as err: + if "image_meta_dict" in batch_data.keys(): + filename = batch_data["image_meta_dict"][ImageMetaKey.FILENAME_OR_OBJ] + else: + filename = batch_data[self.image_key].meta[ImageMetaKey.FILENAME_OR_OBJ] + logger.info(f"Unable to process data {filename} on {device}. {err}") + if self.device.type == "cuda": + logger.info("DataAnalyzer `device` set to GPU execution hit an exception. Falling back to `cpu`.") + try: + batch_data[self.image_key] = batch_data[self.image_key].to("cpu") + if self.label_key is not None: + label = batch_data[self.label_key] + if not _label_argmax: + label = torch.argmax(label, dim=0) if label.shape[0] > 1 else label[0] + batch_data[self.label_key] = label.to("cpu") + d = summarizer(batch_data) + except BaseException as err: + logger.info(f"Unable to process data {filename} on {device}. {err}") + continue + else: + continue + + stats_by_cases = { + DataStatsKeys.BY_CASE_IMAGE_PATH: d[DataStatsKeys.BY_CASE_IMAGE_PATH], + DataStatsKeys.BY_CASE_LABEL_PATH: d[DataStatsKeys.BY_CASE_LABEL_PATH], + } + if not self.histogram_only: + stats_by_cases[DataStatsKeys.IMAGE_STATS] = d[DataStatsKeys.IMAGE_STATS] + if self.hist_bins != 0: + stats_by_cases[DataStatsKeys.IMAGE_HISTOGRAM] = d[DataStatsKeys.IMAGE_HISTOGRAM] + + if self.label_key is not None: + stats_by_cases.update( + { + DataStatsKeys.FG_IMAGE_STATS: d[DataStatsKeys.FG_IMAGE_STATS], + DataStatsKeys.LABEL_STATS: d[DataStatsKeys.LABEL_STATS], + } + ) + result_bycase[DataStatsKeys.BY_CASE].append(stats_by_cases) + if manager_list is None: + return result_bycase + else: + manager_list.append(result_bycase) diff --git a/source_code/SegMamba/monai/apps/auto3dseg/ensemble_builder.py b/source_code/SegMamba/monai/apps/auto3dseg/ensemble_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..b2bea806deace6b0b1d8ae6dc14e20de752cb2fe --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/ensemble_builder.py @@ -0,0 +1,660 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +from abc import ABC, abstractmethod +from collections.abc import Mapping, Sequence +from copy import deepcopy +from typing import Any, cast +from warnings import warn + +import numpy as np +import torch +import torch.distributed as dist + +from monai.apps.auto3dseg.bundle_gen import BundleAlgo +from monai.apps.auto3dseg.utils import get_name_from_algo_id, import_bundle_algo_history +from monai.apps.utils import get_logger +from monai.auto3dseg import concat_val_to_np +from monai.auto3dseg.utils import ( + _prepare_cmd_bcprun, + _prepare_cmd_torchrun, + _run_cmd_bcprun, + _run_cmd_torchrun, + datafold_read, +) +from monai.bundle import ConfigParser +from monai.data import partition_dataset +from monai.transforms import MeanEnsemble, SaveImage, VoteEnsemble +from monai.utils import RankFilter +from monai.utils.enums import AlgoKeys +from monai.utils.misc import check_kwargs_exist_in_class_init, prob2class +from monai.utils.module import look_up_option, optional_import + +tqdm, has_tqdm = optional_import("tqdm", name="tqdm") + +logger = get_logger(module_name=__name__) + + +class AlgoEnsemble(ABC): + """ + The base class of Ensemble methods + """ + + def __init__(self): + self.algos = [] + self.mode = "mean" + self.infer_files = [] + self.algo_ensemble = [] + + def set_algos(self, infer_algos): + """ + Register model in the ensemble + """ + self.algos = deepcopy(infer_algos) + + def get_algo(self, identifier): + """ + Get a model by identifier. + + Args: + identifier: the name of the bundleAlgo + """ + for algo in self.algos: + if identifier == algo[AlgoKeys.ID]: + return algo + + def get_algo_ensemble(self): + """ + Get the algo ensemble after ranking or a empty list if ranking was not started. + + Returns: + A list of Algo + """ + return self.algo_ensemble + + def set_infer_files(self, dataroot: str, data_list_or_path: str | list, data_key: str = "testing") -> None: + """ + Set the files to perform model inference. + + Args: + dataroot: the path of the files + data_list_or_path: the data source file path + """ + + self.infer_files = [] + + if isinstance(data_list_or_path, list): + self.infer_files = data_list_or_path + elif isinstance(data_list_or_path, str): + datalist = ConfigParser.load_config_file(data_list_or_path) + if data_key in datalist: + self.infer_files, _ = datafold_read(datalist=datalist, basedir=dataroot, fold=-1, key=data_key) + elif not hasattr(self, "rank") or self.rank == 0: + logger.info(f"Datalist file has no testing key - {data_key}. No data for inference is specified") + + else: + raise ValueError("Unsupported parameter type") + + def ensemble_pred(self, preds, sigmoid=False): + """ + ensemble the results using either "mean" or "vote" method + + Args: + preds: a list of probability prediction in Tensor-Like format. + sigmoid: use the sigmoid function to threshold probability one-hot map, + otherwise argmax is used. Defaults to False + + Returns: + a tensor which is the ensembled prediction. + """ + + if any(not p.is_cuda for p in preds): + preds = [p.cpu() for p in preds] # ensure CPU if at least one is on CPU + + if self.mode == "mean": + prob = MeanEnsemble()(preds) + return prob2class(cast(torch.Tensor, prob), dim=0, keepdim=True, sigmoid=sigmoid) + elif self.mode == "vote": + classes = [prob2class(p, dim=0, keepdim=True, sigmoid=sigmoid) for p in preds] + if sigmoid: + return VoteEnsemble()(classes) # do not specify num_classes for one-hot encoding + else: + return VoteEnsemble(num_classes=preds[0].shape[0])(classes) + + def _apply_algo_specific_param(self, algo_spec_param: dict, param: dict, algo_name: str) -> dict: + """ + Apply the model-specific params to the prediction params based on the name of the Algo. + + Args: + algo_spec_param: a dict that has structure of {"": ""}. + param: the prediction params to override. + algo_name: name of the Algo + + Returns: + param after being updated with the model-specific param + """ + _param_to_override = deepcopy(algo_spec_param) + _param = deepcopy(param) + for k, v in _param_to_override.items(): + if k.lower() == algo_name.lower(): + _param.update(v) + return _param + + def __call__(self, pred_param: dict | None = None) -> list: + """ + Use the ensembled model to predict result. + + Args: + pred_param: prediction parameter dictionary. The key has two groups: the first one will be consumed + in this function, and the second group will be passed to the `InferClass` to override the + parameters of the class functions. + The first group contains: + + - ``"infer_files"``: file paths to the images to read in a list. + - ``"files_slices"``: a value type of `slice`. The files_slices will slice the ``"infer_files"`` and + only make prediction on the infer_files[file_slices]. + - ``"mode"``: ensemble mode. Currently "mean" and "vote" (majority voting) schemes are supported. + - ``"image_save_func"``: a dictionary used to instantiate the ``SaveImage`` transform. When specified, + the ensemble prediction will save the prediction files, instead of keeping the files in the memory. + Example: `{"_target_": "SaveImage", "output_dir": "./"}` + - ``"sigmoid"``: use the sigmoid function (e.g. x > 0.5) to convert the prediction probability map + to the label class prediction, otherwise argmax(x) is used. + - ``"algo_spec_params"``: a dictionary to add pred_params that are specific to a model. + The dict has a format of {"": ""}. + + The parameters in the second group is defined in the ``config`` of each Algo templates. Please check: + https://github.com/Project-MONAI/research-contributions/tree/main/auto3dseg/algorithm_templates + + Returns: + A list of tensors or file paths, depending on whether ``"image_save_func"`` is set. + """ + param = {} if pred_param is None else deepcopy(pred_param) + files = self.infer_files + + if "infer_files" in param: + files = param.pop("infer_files") + + if "files_slices" in param: + slices = param.pop("files_slices") + files = files[slices] + + if "mode" in param: + mode = param.pop("mode") + self.mode = look_up_option(mode, supported=["mean", "vote"]) + + sigmoid = param.pop("sigmoid", False) + + if "image_save_func" in param: + img_saver = ConfigParser(param["image_save_func"]).get_parsed_content() + + algo_spec_params = param.pop("algo_spec_params", {}) + + outputs = [] + for _, file in ( + enumerate(tqdm(files, desc="Ensembling (rank 0)...")) + if has_tqdm and pred_param and pred_param.get("rank", 0) == 0 + else enumerate(files) + ): + preds = [] + for algo in self.algo_ensemble: + infer_algo_name = get_name_from_algo_id(algo[AlgoKeys.ID]) + infer_instance = algo[AlgoKeys.ALGO] + _param = self._apply_algo_specific_param(algo_spec_params, param, infer_algo_name) + pred = infer_instance.predict(predict_files=[file], predict_params=_param) + preds.append(pred[0]) + if "image_save_func" in param: + try: + ensemble_preds = self.ensemble_pred(preds, sigmoid=sigmoid) + except BaseException: + ensemble_preds = self.ensemble_pred([_.to("cpu") for _ in preds], sigmoid=sigmoid) + res = img_saver(ensemble_preds) + # res is the path to the saved results + if hasattr(res, "meta") and "saved_to" in res.meta.keys(): + res = res.meta["saved_to"] + else: + warn("Image save path not returned.") + res = None + else: + warn("Prediction returned in list instead of disk, provide image_save_func to avoid out of memory.") + res = self.ensemble_pred(preds, sigmoid=sigmoid) + outputs.append(res) + return outputs + + @abstractmethod + def collect_algos(self, *args, **kwargs): + raise NotImplementedError + + +class AlgoEnsembleBestN(AlgoEnsemble): + """ + Ensemble method that select N model out of all using the models' best_metric scores + + Args: + n_best: number of models to pick for ensemble (N). + """ + + def __init__(self, n_best: int = 5): + super().__init__() + self.n_best = n_best + + def sort_score(self): + """ + Sort the best_metrics + """ + scores = concat_val_to_np(self.algos, [AlgoKeys.SCORE]) + return np.argsort(scores).tolist() + + def collect_algos(self, n_best: int = -1) -> None: + """ + Rank the algos by finding the top N (n_best) validation scores. + """ + + if n_best <= 0: + n_best = self.n_best + + ranks = self.sort_score() + if len(ranks) < n_best: + warn(f"Found {len(ranks)} available algos (pre-defined n_best={n_best}). All {len(ranks)} will be used.") + n_best = len(ranks) + + # get the ranks for which the indices are lower than N-n_best + indices = [r for (i, r) in enumerate(ranks) if i < (len(ranks) - n_best)] + + # remove the found indices + indices = sorted(indices, reverse=True) + + self.algo_ensemble = deepcopy(self.algos) + for idx in indices: + if idx < len(self.algo_ensemble): + self.algo_ensemble.pop(idx) + + +class AlgoEnsembleBestByFold(AlgoEnsemble): + """ + Ensemble method that select the best models that are the tops in each fold. + + Args: + n_fold: number of cross-validation folds used in training + """ + + def __init__(self, n_fold: int = 5): + super().__init__() + self.n_fold = n_fold + + def collect_algos(self) -> None: + """ + Rank the algos by finding the best model in each cross-validation fold + """ + + self.algo_ensemble = [] + for f_idx in range(self.n_fold): + best_score = -1.0 + best_model: BundleAlgo | None = None + for algo in self.algos: + # algorithm folder: {net}_{fold_index}_{other} + identifier = algo[AlgoKeys.ID].split("_")[1] + try: + algo_id = int(identifier) + except ValueError as err: + raise ValueError(f"model identifier {identifier} is not number.") from err + if algo_id == f_idx and algo[AlgoKeys.SCORE] > best_score: + best_model = algo + best_score = algo[AlgoKeys.SCORE] + self.algo_ensemble.append(best_model) + + +class AlgoEnsembleBuilder: + """ + Build ensemble workflow from configs and arguments. + + Args: + history: a collection of trained bundleAlgo algorithms. + data_src_cfg_name: filename of the data source. + + Examples: + + .. code-block:: python + + builder = AlgoEnsembleBuilder(history, data_src_cfg) + builder.set_ensemble_method(BundleAlgoEnsembleBestN(3)) + ensemble = builder.get_ensemble() + + """ + + def __init__(self, history: Sequence[dict[str, Any]], data_src_cfg_name: str | None = None): + self.infer_algos: list[dict[AlgoKeys, Any]] = [] + self.ensemble: AlgoEnsemble + self.data_src_cfg = ConfigParser(globals=False) + + if data_src_cfg_name is not None and os.path.exists(str(data_src_cfg_name)): + self.data_src_cfg.read_config(data_src_cfg_name) + + for algo_dict in history: + # load inference_config_paths + + name = algo_dict[AlgoKeys.ID] + gen_algo = algo_dict[AlgoKeys.ALGO] + + best_metric = gen_algo.get_score() + algo_path = gen_algo.output_path + infer_path = os.path.join(algo_path, "scripts", "infer.py") + + if not os.path.isdir(algo_path): + warn(f"{gen_algo.output_path} is not a directory. Please check the path.") + + if not os.path.isfile(infer_path): + warn(f"{infer_path} is not found. Please check the path.") + + self.add_inferer(name, gen_algo, best_metric) + + def add_inferer(self, identifier: str, gen_algo: BundleAlgo, best_metric: float | None = None) -> None: + """ + Add model inferer to the builder. + + Args: + identifier: name of the bundleAlgo. + gen_algo: a trained BundleAlgo model object. + best_metric: the best metric in validation of the trained model. + """ + + if best_metric is None: + raise ValueError("Feature to re-validate is to be implemented") + + algo = {AlgoKeys.ID: identifier, AlgoKeys.ALGO: gen_algo, AlgoKeys.SCORE: best_metric} + self.infer_algos.append(algo) + + def set_ensemble_method(self, ensemble: AlgoEnsemble, *args: Any, **kwargs: Any) -> None: + """ + Set the ensemble method. + + Args: + ensemble: the AlgoEnsemble to build. + """ + + ensemble.set_algos(self.infer_algos) + ensemble.collect_algos(*args, **kwargs) + ensemble.set_infer_files(self.data_src_cfg["dataroot"], self.data_src_cfg["datalist"]) + + self.ensemble = ensemble + + def get_ensemble(self): + """Get the ensemble""" + + return self.ensemble + + +class EnsembleRunner: + """ + The Runner for ensembler. It ensembles predictions and saves them to the disk with a support of using multi-GPU. + + Args: + data_src_cfg_name: filename of the data source. + work_dir: working directory to save the intermediate and final results. Default is `./work_dir`. + num_fold: number of fold. Default is 5. + ensemble_method_name: method to ensemble predictions from different model. Default is AlgoEnsembleBestByFold. + Supported methods: ["AlgoEnsembleBestN", "AlgoEnsembleBestByFold"]. + mgpu: if using multi-gpu. Default is True. + kwargs: additional image writing, ensembling parameters and prediction parameters for the ensemble inference. + - for image saving, please check the supported parameters in SaveImage transform. + - for prediction parameters, please check the supported parameters in the ``AlgoEnsemble`` callables. + - for ensemble parameters, please check the documentation of the selected AlgoEnsemble callable. + + Example: + + .. code-block:: python + + ensemble_runner = EnsembleRunner(data_src_cfg_name, + work_dir, + ensemble_method_name, + mgpu=device_setting['n_devices']>1, + **kwargs, + **pred_params) + ensemble_runner.run(device_setting) + + """ + + def __init__( + self, + data_src_cfg_name: str, + work_dir: str = "./work_dir", + num_fold: int = 5, + ensemble_method_name: str = "AlgoEnsembleBestByFold", + mgpu: bool = True, + **kwargs: Any, + ) -> None: + self.data_src_cfg_name = data_src_cfg_name + self.work_dir = work_dir + self.num_fold = num_fold + self.ensemble_method_name = ensemble_method_name + self.mgpu = mgpu + self.kwargs = deepcopy(kwargs) + self.rank = 0 + self.world_size = 1 + self.device_setting: dict[str, int | str] = { + "CUDA_VISIBLE_DEVICES": ",".join([str(x) for x in range(torch.cuda.device_count())]), + "n_devices": torch.cuda.device_count(), + "NUM_NODES": int(os.environ.get("NUM_NODES", 1)), + "MN_START_METHOD": os.environ.get("MN_START_METHOD", "bcprun"), + "CMD_PREFIX": os.environ.get("CMD_PREFIX", ""), + } + + def set_ensemble_method(self, ensemble_method_name: str = "AlgoEnsembleBestByFold", **kwargs: Any) -> None: + """ + Set the bundle ensemble method + + Args: + ensemble_method_name: the name of the ensemble method. Only two methods are supported "AlgoEnsembleBestN" + and "AlgoEnsembleBestByFold". + kwargs: the keyword arguments used to define the ensemble method. Currently only ``n_best`` for + ``AlgoEnsembleBestN`` is supported. + + """ + self.ensemble_method_name = look_up_option( + ensemble_method_name, supported=["AlgoEnsembleBestN", "AlgoEnsembleBestByFold"] + ) + if self.ensemble_method_name == "AlgoEnsembleBestN": + n_best = kwargs.pop("n_best", 2) + self.ensemble_method = AlgoEnsembleBestN(n_best=n_best) + elif self.ensemble_method_name == "AlgoEnsembleBestByFold": + self.ensemble_method = AlgoEnsembleBestByFold(n_fold=self.num_fold) # type: ignore + else: + raise NotImplementedError(f"Ensemble method {self.ensemble_method_name} is not implemented.") + + def _pop_kwargs_to_get_image_save_transform(self, **kwargs): + """ + Pop the kwargs used to define ImageSave class for the ensemble output. + + Args: + kwargs: image writing parameters for the ensemble inference. The kwargs format follows SaveImage + transform. For more information, check https://docs.monai.io/en/stable/transforms.html#saveimage . + + Returns: + save_image: a dictionary that can be used to instantiate a SaveImage class in ConfigParser. + """ + + output_dir = kwargs.pop("output_dir", None) + + if output_dir is None: + output_dir = os.path.join(self.work_dir, "ensemble_output") + logger.info(f"The output_dir is not specified. {output_dir} will be used to save ensemble predictions.") + + if not os.path.isdir(output_dir): + os.makedirs(output_dir, exist_ok=True) + logger.info(f"Directory {output_dir} is created to save ensemble predictions") + + input_yaml = ConfigParser.load_config_file(self.data_src_cfg_name) + data_root_dir = input_yaml.get("dataroot", "") + + save_image = { + "_target_": "SaveImage", + "output_dir": output_dir, + "output_postfix": kwargs.pop("output_postfix", "ensemble"), + "output_dtype": kwargs.pop("output_dtype", "$np.uint8"), + "resample": kwargs.pop("resample", False), + "print_log": False, + "savepath_in_metadict": True, + "data_root_dir": kwargs.pop("data_root_dir", data_root_dir), + "separate_folder": kwargs.pop("separate_folder", False), + } + + are_all_args_save_image, extra_args = check_kwargs_exist_in_class_init(SaveImage, kwargs) + if are_all_args_save_image: + save_image.update(kwargs) + else: + # kwargs has extra values for other purposes, for example, pred_params + for args in list(kwargs): + if args not in extra_args: + save_image.update({args: kwargs.pop(args)}) + + return save_image + + def set_image_save_transform(self, **kwargs: Any) -> None: + """ + Set the ensemble output transform. + + Args: + kwargs: image writing parameters for the ensemble inference. The kwargs format follows SaveImage + transform. For more information, check https://docs.monai.io/en/stable/transforms.html#saveimage . + + """ + are_all_args_present, extra_args = check_kwargs_exist_in_class_init(SaveImage, kwargs) + if are_all_args_present: + self.kwargs.update(kwargs) + else: + raise ValueError( + f"{extra_args} are not supported in monai.transforms.SaveImage," + "Check https://docs.monai.io/en/stable/transforms.html#saveimage for more information." + ) + + def set_num_fold(self, num_fold: int = 5) -> None: + """ + Set the number of cross validation folds for all algos. + + Args: + num_fold: a positive integer to define the number of folds. + """ + + if num_fold <= 0: + raise ValueError(f"num_fold is expected to be an integer greater than zero. Now it gets {num_fold}") + self.num_fold = num_fold + + def ensemble(self): + if self.mgpu: # torch.cuda.device_count() is not used because env is not set by autorunner + # init multiprocessing and update infer_files + dist.init_process_group(backend="nccl", init_method="env://") + self.world_size = dist.get_world_size() + self.rank = dist.get_rank() + logger.addFilter(RankFilter()) + # set params after init_process_group to know the rank + self.set_num_fold(num_fold=self.num_fold) + self.set_ensemble_method(self.ensemble_method_name, **self.kwargs) + # self.kwargs needs to pop out args for set_image_save_transform + save_image = self._pop_kwargs_to_get_image_save_transform(**self.kwargs) + + history = import_bundle_algo_history(self.work_dir, only_trained=False) + history_untrained = [h for h in history if not h[AlgoKeys.IS_TRAINED]] + if history_untrained: + logger.warning( + f"Ensembling step will skip {[h[AlgoKeys.ID] for h in history_untrained]} untrained algos." + "Generally it means these algos did not complete training." + ) + history = [h for h in history if h[AlgoKeys.IS_TRAINED]] + if len(history) == 0: + raise ValueError( + f"Could not find the trained results in {self.work_dir}. " + "Possibly the required training step was not completed." + ) + + builder = AlgoEnsembleBuilder(history, self.data_src_cfg_name) + builder.set_ensemble_method(self.ensemble_method) + self.ensembler = builder.get_ensemble() + infer_files = self.ensembler.infer_files + if len(infer_files) < self.world_size: + if len(infer_files) == 0: + logger.info("No testing files for inference is provided. Ensembler ending.") + return + infer_files = [infer_files[self.rank]] if self.rank < len(infer_files) else [] + else: + infer_files = partition_dataset( + data=infer_files, shuffle=False, num_partitions=self.world_size, even_divisible=False + )[self.rank] + + # TO DO: Add some function in ensembler for infer_files update? + self.ensembler.infer_files = infer_files + # add rank to pred_params + self.kwargs["rank"] = self.rank + self.kwargs["image_save_func"] = save_image + logger.info("Auto3Dseg picked the following networks to ensemble:") + for algo in self.ensembler.get_algo_ensemble(): + logger.info(algo[AlgoKeys.ID]) + output_dir = save_image["output_dir"] + logger.info(f"Auto3Dseg ensemble prediction outputs will be saved in {output_dir}.") + self.ensembler(pred_param=self.kwargs) + + if self.mgpu: + dist.destroy_process_group() + + def run(self, device_setting: dict | None = None) -> None: + """ + Load the run function in the training script of each model. Training parameter is predefined by the + algo_config.yaml file, which is pre-filled by the fill_template_config function in the same instance. + + Args: + device_setting: device related settings, should follow the device_setting in auto_runner.set_device_info. + 'CUDA_VISIBLE_DEVICES' should be a string e.g. '0,1,2,3' + """ + # device_setting set default value and sanity check, in case device_setting not from autorunner + if device_setting is not None: + self.device_setting.update(device_setting) + self.device_setting["n_devices"] = len(str(self.device_setting["CUDA_VISIBLE_DEVICES"]).split(",")) + self._create_cmd() + + def _create_cmd(self) -> None: + if int(self.device_setting["NUM_NODES"]) <= 1 and int(self.device_setting["n_devices"]) <= 1: + # if single GPU + logger.info("Ensembling using single GPU!") + self.ensemble() + return + + # define base cmd for subprocess + base_cmd = f"monai.apps.auto3dseg EnsembleRunner ensemble \ + --data_src_cfg_name {self.data_src_cfg_name} \ + --work_dir {self.work_dir} \ + --num_fold {self.num_fold} \ + --ensemble_method_name {self.ensemble_method_name} \ + --mgpu True" + + if self.kwargs and isinstance(self.kwargs, Mapping): + for k, v in self.kwargs.items(): + base_cmd += f" --{k}={v}" + # define env for subprocess + ps_environ = os.environ.copy() + ps_environ["CUDA_VISIBLE_DEVICES"] = str(self.device_setting["CUDA_VISIBLE_DEVICES"]) + if int(self.device_setting["NUM_NODES"]) > 1: + if self.device_setting["MN_START_METHOD"] != "bcprun": + raise NotImplementedError( + f"{self.device_setting['MN_START_METHOD']} is not supported yet. " + "Try modify EnsembleRunner._create_cmd for your cluster." + ) + logger.info(f"Ensembling on {self.device_setting['NUM_NODES']} nodes!") + cmd = _prepare_cmd_bcprun("-m " + base_cmd, cmd_prefix=f"{self.device_setting['CMD_PREFIX']}") + _run_cmd_bcprun(cmd, n=self.device_setting["NUM_NODES"], p=self.device_setting["n_devices"]) + + else: + logger.info(f"Ensembling using {self.device_setting['n_devices']} GPU!") + cmd = _prepare_cmd_torchrun("-m " + base_cmd) + _run_cmd_torchrun( + cmd, nnodes=1, nproc_per_node=self.device_setting["n_devices"], env=ps_environ, check=True + ) + return diff --git a/source_code/SegMamba/monai/apps/auto3dseg/hpo_gen.py b/source_code/SegMamba/monai/apps/auto3dseg/hpo_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..b755b99feb6e01b2df9fc405a9b34eb48756f13b --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/hpo_gen.py @@ -0,0 +1,401 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +from abc import abstractmethod +from copy import deepcopy +from typing import Any, cast +from warnings import warn + +from monai.apps.auto3dseg.bundle_gen import BundleAlgo +from monai.apps.utils import get_logger +from monai.auto3dseg import Algo, AlgoGen, algo_from_pickle, algo_to_pickle +from monai.bundle.config_parser import ConfigParser +from monai.config import PathLike +from monai.utils import optional_import +from monai.utils.enums import AlgoKeys + +nni, has_nni = optional_import("nni") +optuna, has_optuna = optional_import("optuna") +logger = get_logger(module_name=__name__) + +__all__ = ["HPOGen", "NNIGen", "OptunaGen"] + + +class HPOGen(AlgoGen): + """ + The base class for hyperparameter optimization (HPO) interfaces to generate algos in the Auto3Dseg pipeline. + The auto-generated algos are saved at their ``output_path`` on the disk. The files in the ``output_path`` + may contain scripts that define the algo, configuration files, and pickle files that save the internal states + of the algo before/after the training. Compared to the BundleGen class, HPOGen generates Algo on-the-fly, so + training and algo generation may be executed alternatively and take a long time to finish the generation process. + + """ + + @abstractmethod + def get_hyperparameters(self): + """Get the hyperparameter from HPO.""" + raise NotImplementedError + + @abstractmethod + def update_params(self, *args, **kwargs): + """Update Algo parameters according to the hyperparameters to be evaluated.""" + raise NotImplementedError + + @abstractmethod + def set_score(self): + """Report the evaluated results to HPO.""" + raise NotImplementedError + + @abstractmethod + def run_algo(self, *args, **kwargs): + """Interface for launch the training given the fetched hyperparameters.""" + raise NotImplementedError + + +class NNIGen(HPOGen): + """ + Generate algorithms for the NNI to automate hyperparameter tuning. The module has two major interfaces: + ``__init__`` which prints out how to set up the NNI, and a trialCommand function ``run_algo`` for the NNI library to + start the trial of the algo. More about trialCommand function can be found in ``trail code`` section in NNI webpage + https://nni.readthedocs.io/en/latest/tutorials/hpo_quickstart_pytorch/main.html . + + Args: + algo: an Algo object (e.g. BundleAlgo) with defined methods: ``get_output_path`` and train + and supports saving to and loading from pickle files via ``algo_from_pickle`` and ``algo_to_pickle``. + params: a set of parameter to override the algo if override is supported by Algo subclass. + + Examples:: + + The experiment will keep generating new folders to save the model checkpoints, scripts, and configs if available. + ├── algorithm_templates + │ └── unet + ├── unet_0 + │ ├── algo_object.pkl + │ ├── configs + │ └── scripts + ├── unet_0_learning_rate_0.01 + │ ├── algo_object.pkl + │ ├── configs + │ ├── model_fold0 + │ └── scripts + └── unet_0_learning_rate_0.1 + ├── algo_object.pkl + ├── configs + ├── model_fold0 + └── scripts + + .. code-block:: python + # Bundle Algorithms are already generated by BundleGen in work_dir + import_bundle_algo_history(work_dir, only_trained=False) + algo_dict = self.history[0] # pick the first algorithm + algo_name = algo_dict[AlgoKeys.ID] + onealgo = algo_dict[AlgoKeys.ALGO] + nni_gen = NNIGen(algo=onealgo) + nni_gen.print_bundle_algo_instruction() + + Notes: + The NNIGen will prepare the algorithms in a folder and suggest a command to replace trialCommand in the experiment + config. However, NNIGen will not trigger NNI. User needs to write their NNI experiment configs, and then run the + NNI command manually. + """ + + def __init__(self, algo: Algo | None = None, params: dict | None = None): + self.algo: Algo + self.hint = "" + self.obj_filename = "" + + if algo is not None: + if isinstance(algo, BundleAlgo): + if params is None: + self.algo = algo + else: + self.algo = deepcopy(algo) + name = os.path.basename(algo.get_output_path()) + "_override" + output_folder = os.path.dirname(algo.get_output_path()) + + params.update({"fill_with_datastats": False}) # just copy, not using datastats to fill + self.algo.export_to_disk(output_folder, name, **params) + else: + self.algo = algo + + self.obj_filename = algo_to_pickle(self.algo, template_path=self.algo.template_path) + + def get_obj_filename(self): + """Return the filename of the dumped pickle algo object.""" + return self.obj_filename + + def print_bundle_algo_instruction(self): + """ + Print how to write the trial commands for Bundle Algo. + """ + hint = "python -m monai.apps.auto3dseg NNIGen run_algo " + logger.info("=" * 140) + logger.info("If NNI will run in your local env: ") + logger.info("1. Add the following line to the trialCommand in your NNI config: ") + logger.info(f"{hint} {self.obj_filename} {{result_dir}}") + logger.info("-" * 140) + logger.info("If NNI will run in a remote env: ") + logger.info( + f"1. Copy the algorithm_templates folder {cast(BundleAlgo, self.algo).template_path} " + f"to remote {{remote_algorithm_templates_dir}}" + ) + logger.info(f"2. Copy the older {self.algo.get_output_path()} to the remote machine {{remote_algo_dir}}") + logger.info("Then add the following line to the trialCommand in your NNI config: ") + logger.info(f"{hint} {{remote_algo_dir}} {{result_dir}} {{remote_algorithm_templates_dir}}") + logger.info("=" * 140) + + def get_hyperparameters(self): + """ + Get parameter for next round of training from NNI server. + """ + if has_nni: + return nni.get_next_parameter() + warn("NNI is not detected. The code will continue to run without NNI.") + return {} + + def update_params(self, params: dict) -> None: + """ + Translate the parameter from monai bundle to meet NNI requirements. + + Args: + params: a dict of parameters. + """ + self.params = params + + def get_task_id(self): + """ + Get the identifier of the current experiment. In the format of listing the searching parameter name and values + connected by underscore in the file name. + """ + return "".join(f"_{k}_{v}" for k, v in self.params.items()) or "_None" + + def generate(self, output_folder: str = ".") -> None: + """ + Generate the record for each Algo. If it is a BundleAlgo, it will generate the config files. + + Args: + output_folder: the directory nni will save the results to. + """ + task_id = self.get_task_id() + task_prefix = os.path.basename(self.algo.get_output_path()) + write_path = os.path.join(output_folder, task_prefix + task_id) + self.obj_filename = os.path.join(write_path, "algo_object.pkl") + + if isinstance(self.algo, BundleAlgo): + self.algo.export_to_disk( + output_folder, task_prefix + task_id, bundle_root=write_path, fill_with_datastats=False + ) + else: + ConfigParser.export_config_file(self.params, write_path) + logger.info(write_path) + + def set_score(self, acc): + """ + Report the acc to NNI server. + """ + if has_nni: + nni.report_final_result(acc) + else: + warn("NNI is not detected. The code will continue to run without NNI.") + + def run_algo(self, obj_filename: str, output_folder: str = ".", template_path: PathLike | None = None) -> None: + """ + The python interface for NNI to run. + + Args: + obj_filename: the pickle-exported Algo object. + output_folder: the root path of the algorithms templates. + template_path: the algorithm_template. It must contain algo.py in the follow path: + ``{algorithm_templates_dir}/{network}/scripts/algo.py`` + """ + if not os.path.isfile(obj_filename): + raise ValueError(f"{obj_filename} is not found") + + self.algo, algo_meta_data = algo_from_pickle(obj_filename, template_path=template_path) + + # step 1 sample hyperparams + params = self.get_hyperparameters() + # step 2 set the update params for the algo to run in the next trial + self.update_params(params) + # step 3 generate the folder to save checkpoints and train + self.generate(output_folder) + self.algo.train(self.params) + # step 4 report validation acc to controller + acc = self.algo.get_score() + algo_meta_data = {str(AlgoKeys.SCORE): acc} + + algo_to_pickle(self.algo, template_path=self.algo.template_path, **algo_meta_data) + self.set_score(acc) + + +class OptunaGen(HPOGen): + """ + Generate algorithms for the Optuna to automate hyperparameter tuning. Please refer to NNI and Optuna + (https://optuna.readthedocs.io/en/stable/) for more information. Optuna has different running scheme + compared to NNI. The hyperparameter samples come from a trial object (trial.suggest...) created by Optuna, + so OptunaGen needs to accept this trial object as input. Meanwhile, Optuna calls OptunaGen, + thus OptunaGen.__call__() should return the accuracy. Use functools.partial to wrap OptunaGen + for addition input arguments. + + Args: + algo: an Algo object (e.g. BundleAlgo). The object must at least define two methods: get_output_path and train + and supports saving to and loading from pickle files via ``algo_from_pickle`` and ``algo_to_pickle``. + params: a set of parameter to override the algo if override is supported by Algo subclass. + + Examples:: + + The experiment will keep generating new folders to save the model checkpoints, scripts, and configs if available. + ├── algorithm_templates + │ └── unet + ├── unet_0 + │ ├── algo_object.pkl + │ ├── configs + │ └── scripts + ├── unet_0_learning_rate_0.01 + │ ├── algo_object.pkl + │ ├── configs + │ ├── model_fold0 + │ └── scripts + └── unet_0_learning_rate_0.1 + ├── algo_object.pkl + ├── configs + ├── model_fold0 + └── scripts + + Notes: + Different from NNI and NNIGen, OptunaGen and Optuna can be ran within the Python process. + + """ + + def __init__(self, algo: Algo | None = None, params: dict | None = None) -> None: + self.algo: Algo + self.obj_filename = "" + + if algo is not None: + if isinstance(algo, BundleAlgo): + if params is None: + self.algo = algo + else: + self.algo = deepcopy(algo) + name = os.path.basename(algo.get_output_path()) + "_override" + output_folder = os.path.dirname(algo.get_output_path()) + + params.update({"fill_with_datastats": False}) # just copy, not using datastats to fill + self.algo.export_to_disk(output_folder, name, **params) + else: + self.algo = algo + + self.obj_filename = algo_to_pickle(self.algo, template_path=self.algo.template_path) + + def get_obj_filename(self): + """Return the dumped pickle object of algo.""" + return self.obj_filename + + def get_hyperparameters(self): + """ + Get parameter for next round of training from optuna trial object. + This function requires user rewrite during usage for different search space. + """ + if has_optuna: + logger.info("Please rewrite this code by creating a child class") + return {"learning_rate": self.trial.suggest_float("learning_rate", 0.0001, 0.1)} + else: + warn("Optuna is not detected. The code will continue to run without Optuna.") + return {} + + def set_score(self, acc): + """Set the accuracy score""" + self.acc = acc + + def set_trial(self, trial): + """Set the Optuna trial""" + self.trial = trial + + def __call__( + self, trial: Any, obj_filename: str, output_folder: str = ".", template_path: PathLike | None = None + ) -> Any: + """ + Callable that Optuna will use to optimize the hyper-parameters + + Args: + obj_filename: the pickle-exported Algo object. + output_folder: the root path of the algorithms templates. + template_path: the algorithm_template. It must contain algo.py in the follow path: + ``{algorithm_templates_dir}/{network}/scripts/algo.py`` + """ + self.set_trial(trial) + self.run_algo(obj_filename, output_folder, template_path) + return self.acc + + def update_params(self, params: dict) -> None: + """ + Translate the parameter from monai bundle. + + Args: + params: a dict of parameters. + """ + self.params = params + + def get_task_id(self): + """ + Get the identifier of the current experiment. In the format of listing the searching parameter name and values + connected by underscore in the file name. + """ + return "".join(f"_{k}_{v}" for k, v in self.params.items()) or "_None" + + def generate(self, output_folder: str = ".") -> None: + """ + Generate the record for each Algo. If it is a BundleAlgo, it will generate the config files. + + Args: + output_folder: the directory nni will save the results to. + """ + task_id = self.get_task_id() + task_prefix = os.path.basename(self.algo.get_output_path()) + write_path = os.path.join(output_folder, task_prefix + task_id) + self.obj_filename = os.path.join(write_path, "algo_object.pkl") + + if isinstance(self.algo, BundleAlgo): + self.algo.export_to_disk(output_folder, task_prefix + task_id, fill_with_datastats=False) + else: + ConfigParser.export_config_file(self.params, write_path) + logger.info(write_path) + + def run_algo(self, obj_filename: str, output_folder: str = ".", template_path: PathLike | None = None) -> None: + """ + The python interface for NNI to run. + + Args: + obj_filename: the pickle-exported Algo object. + output_folder: the root path of the algorithms templates. + template_path: the algorithm_template. It must contain algo.py in the follow path: + ``{algorithm_templates_dir}/{network}/scripts/algo.py`` + """ + if not os.path.isfile(obj_filename): + raise ValueError(f"{obj_filename} is not found") + + self.algo, algo_meta_data = algo_from_pickle(obj_filename, template_path=template_path) + + # step 1 sample hyperparams + params = self.get_hyperparameters() + # step 2 set the update params for the algo to run in the next trial + self.update_params(params) + # step 3 generate the folder to save checkpoints and train + self.generate(output_folder) + self.algo.train(self.params) + # step 4 report validation acc to controller + acc = self.algo.get_score() + algo_meta_data = {str(AlgoKeys.SCORE): acc} + algo_to_pickle(self.algo, template_path=self.algo.template_path, **algo_meta_data) + self.set_score(acc) diff --git a/source_code/SegMamba/monai/apps/deepedit/__init__.py b/source_code/SegMamba/monai/apps/deepedit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e97f8940782e96a77c1c08483fc41da9a48ae22 --- /dev/null +++ b/source_code/SegMamba/monai/apps/deepedit/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/source_code/SegMamba/monai/apps/deepedit/interaction.py b/source_code/SegMamba/monai/apps/deepedit/interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..07302575c6afa7c0a9f846373746d16a0245fb03 --- /dev/null +++ b/source_code/SegMamba/monai/apps/deepedit/interaction.py @@ -0,0 +1,100 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Callable, Sequence + +import numpy as np +import torch + +from monai.data import decollate_batch, list_data_collate +from monai.engines import SupervisedEvaluator, SupervisedTrainer +from monai.engines.utils import IterationEvents +from monai.transforms import Compose +from monai.utils.enums import CommonKeys + + +class Interaction: + """ + Ignite process_function used to introduce interactions (simulation of clicks) for DeepEdit Training/Evaluation. + + More details about this can be found at: + + Diaz-Pinto et al., MONAI Label: A framework for AI-assisted Interactive + Labeling of 3D Medical Images. (2022) https://arxiv.org/abs/2203.12362 + + Args: + deepgrow_probability: probability of simulating clicks in an iteration + transforms: execute additional transformation during every iteration (before train). + Typically, several Tensor based transforms composed by `Compose`. + train: True for training mode or False for evaluation mode + click_probability_key: key to click/interaction probability + label_names: Dict of label names + max_interactions: maximum number of interactions per iteration + """ + + def __init__( + self, + deepgrow_probability: float, + transforms: Sequence[Callable] | Callable, + train: bool, + label_names: None | dict[str, int] = None, + click_probability_key: str = "probability", + max_interactions: int = 1, + ) -> None: + self.deepgrow_probability = deepgrow_probability + self.transforms = Compose(transforms) if not isinstance(transforms, Compose) else transforms + self.train = train + self.label_names = label_names + self.click_probability_key = click_probability_key + self.max_interactions = max_interactions + + def __call__(self, engine: SupervisedTrainer | SupervisedEvaluator, batchdata: dict[str, torch.Tensor]) -> dict: + if batchdata is None: + raise ValueError("Must provide batch data for current iteration.") + + if np.random.choice([True, False], p=[self.deepgrow_probability, 1 - self.deepgrow_probability]): + for j in range(self.max_interactions): + inputs, _ = engine.prepare_batch(batchdata) + inputs = inputs.to(engine.state.device) + + engine.fire_event(IterationEvents.INNER_ITERATION_STARTED) + engine.network.eval() + + with torch.no_grad(): + if engine.amp: + with torch.cuda.amp.autocast(): + predictions = engine.inferer(inputs, engine.network) + else: + predictions = engine.inferer(inputs, engine.network) + batchdata.update({CommonKeys.PRED: predictions}) + + # decollate/collate batchdata to execute click transforms + batchdata_list = decollate_batch(batchdata, detach=True) + for i in range(len(batchdata_list)): + batchdata_list[i][self.click_probability_key] = ( + (1.0 - ((1.0 / self.max_interactions) * j)) if self.train else 1.0 + ) + batchdata_list[i] = self.transforms(batchdata_list[i]) + + batchdata = list_data_collate(batchdata_list) + engine.fire_event(IterationEvents.INNER_ITERATION_COMPLETED) + else: + # zero out input guidance channels + batchdata_list = decollate_batch(batchdata, detach=True) + for i in range(1, len(batchdata_list[0][CommonKeys.IMAGE])): + batchdata_list[0][CommonKeys.IMAGE][i] *= 0 + batchdata = list_data_collate(batchdata_list) + + # first item in batch only + engine.state.batch = batchdata + return engine._iteration(engine, batchdata) # type: ignore[arg-type] diff --git a/source_code/SegMamba/monai/apps/deepedit/transforms.py b/source_code/SegMamba/monai/apps/deepedit/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..6d0825f54ab38183b33fbf5036ec0e5dbc3b10db --- /dev/null +++ b/source_code/SegMamba/monai/apps/deepedit/transforms.py @@ -0,0 +1,915 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import json +import logging +import random +import warnings +from collections.abc import Hashable, Mapping, Sequence, Sized + +import numpy as np +import torch + +from monai.config import KeysCollection +from monai.data import MetaTensor +from monai.networks.layers import GaussianFilter +from monai.transforms.transform import MapTransform, Randomizable, Transform +from monai.utils import min_version, optional_import + +measure, _ = optional_import("skimage.measure", "0.14.2", min_version) + +logger = logging.getLogger(__name__) + +distance_transform_cdt, _ = optional_import("scipy.ndimage.morphology", name="distance_transform_cdt") + + +class DiscardAddGuidanced(MapTransform): + + def __init__( + self, + keys: KeysCollection, + number_intensity_ch: int = 1, + probability: float = 1.0, + label_names: Sized | None = None, + allow_missing_keys: bool = False, + ): + """ + Discard positive and negative points according to discard probability + + Args: + keys: The ``keys`` parameter will be used to get and set the actual data item to transform + number_intensity_ch: number of intensity channels + probability: probability of discarding clicks + """ + super().__init__(keys, allow_missing_keys) + + self.number_intensity_ch = number_intensity_ch + self.discard_probability = probability + self.label_names = label_names or [] + + def _apply(self, image): + if self.discard_probability >= 1.0 or np.random.choice( + [True, False], p=[self.discard_probability, 1 - self.discard_probability] + ): + signal = np.zeros( + (len(self.label_names), image.shape[-3], image.shape[-2], image.shape[-1]), dtype=np.float32 + ) + if image.shape[0] == self.number_intensity_ch + len(self.label_names): + image[self.number_intensity_ch :, ...] = signal + else: + image = np.concatenate([image, signal], axis=0) + return image + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "image": + tmp_image = self._apply(d[key]) + if isinstance(d[key], MetaTensor): + d[key].array = tmp_image + else: + d[key] = tmp_image + else: + print("This transform only applies to the image") + return d + + +class NormalizeLabelsInDatasetd(MapTransform): + + def __init__( + self, keys: KeysCollection, label_names: dict[str, int] | None = None, allow_missing_keys: bool = False + ): + """ + Normalize label values according to label names dictionary + + Args: + keys: The ``keys`` parameter will be used to get and set the actual data item to transform + label_names: all label names + """ + super().__init__(keys, allow_missing_keys) + + self.label_names = label_names or {} + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + # Dictionary containing new label numbers + new_label_names = {} + label = np.zeros(d[key].shape) + # Making sure the range values and number of labels are the same + for idx, (key_label, val_label) in enumerate(self.label_names.items(), start=1): + if key_label != "background": + new_label_names[key_label] = idx + label[d[key] == val_label] = idx + if key_label == "background": + new_label_names["background"] = 0 + + d["label_names"] = new_label_names + if isinstance(d[key], MetaTensor): + d[key].array = label + else: + d[key] = label + return d + + +class SingleLabelSelectiond(MapTransform): + + def __init__( + self, keys: KeysCollection, label_names: Sequence[str] | None = None, allow_missing_keys: bool = False + ): + """ + Selects one label at a time to train the DeepEdit + + Args: + keys: The ``keys`` parameter will be used to get and set the actual data item to transform + label_names: all label names + """ + super().__init__(keys, allow_missing_keys) + + self.label_names: Sequence[str] = label_names or [] + self.all_label_values = { + "spleen": 1, + "right kidney": 2, + "left kidney": 3, + "gallbladder": 4, + "esophagus": 5, + "liver": 6, + "stomach": 7, + "aorta": 8, + "inferior vena cava": 9, + "portal_vein": 10, + "splenic_vein": 11, + "pancreas": 12, + "right adrenal gland": 13, + "left adrenal gland": 14, + } + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "label": + # Taking one label at a time + t_label = np.random.choice(self.label_names) + d["current_label"] = t_label + d[key][d[key] != self.all_label_values[t_label]] = 0.0 + # Convert label to index values following label_names argument + max_label_val = self.label_names.index(t_label) + 1 + d[key][d[key] > 0] = max_label_val + print(f"Using label {t_label} with number: {d[key].max()}") + else: + warnings.warn("This transform only applies to the label") + return d + + +class AddGuidanceSignalDeepEditd(MapTransform): + """ + Add Guidance signal for input image. Multilabel DeepEdit + + Based on the "guidance" points, apply Gaussian to them and add them as new channel for input image. + + Args: + guidance: key to store guidance. + sigma: standard deviation for Gaussian kernel. + number_intensity_ch: channel index. + """ + + def __init__( + self, + keys: KeysCollection, + guidance: str = "guidance", + sigma: int = 3, + number_intensity_ch: int = 1, + allow_missing_keys: bool = False, + ): + super().__init__(keys, allow_missing_keys) + self.guidance = guidance + self.sigma = sigma + self.number_intensity_ch = number_intensity_ch + + def _get_signal(self, image, guidance): + dimensions = 3 if len(image.shape) > 3 else 2 + guidance = guidance.tolist() if isinstance(guidance, np.ndarray) else guidance + guidance = json.loads(guidance) if isinstance(guidance, str) else guidance + + # In inference the user may not provide clicks for some channels/labels + if len(guidance): + if dimensions == 3: + # Assume channel is first and depth is last CHWD + signal = np.zeros((1, image.shape[-3], image.shape[-2], image.shape[-1]), dtype=np.float32) + else: + signal = np.zeros((1, image.shape[-2], image.shape[-1]), dtype=np.float32) + + sshape = signal.shape + for point in guidance: # TO DO: make the guidance a list only - it is currently a list of list + if np.any(np.asarray(point) < 0): + continue + + if dimensions == 3: + # Making sure points fall inside the image dimension + p1 = max(0, min(int(point[-3]), sshape[-3] - 1)) + p2 = max(0, min(int(point[-2]), sshape[-2] - 1)) + p3 = max(0, min(int(point[-1]), sshape[-1] - 1)) + signal[:, p1, p2, p3] = 1.0 + else: + p1 = max(0, min(int(point[-2]), sshape[-2] - 1)) + p2 = max(0, min(int(point[-1]), sshape[-1] - 1)) + signal[:, p1, p2] = 1.0 + + # Apply a Gaussian filter to the signal + if np.max(signal[0]) > 0: + signal_tensor = torch.tensor(signal[0]) + pt_gaussian = GaussianFilter(len(signal_tensor.shape), sigma=self.sigma) + signal_tensor = pt_gaussian(signal_tensor.unsqueeze(0).unsqueeze(0)) + signal_tensor = signal_tensor.squeeze(0).squeeze(0) + signal[0] = signal_tensor.detach().cpu().numpy() + signal[0] = (signal[0] - np.min(signal[0])) / (np.max(signal[0]) - np.min(signal[0])) + return signal + else: + if dimensions == 3: + signal = np.zeros((1, image.shape[-3], image.shape[-2], image.shape[-1]), dtype=np.float32) + else: + signal = np.zeros((1, image.shape[-2], image.shape[-1]), dtype=np.float32) + return signal + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "image": + image = d[key] + tmp_image = image[0 : 0 + self.number_intensity_ch, ...] + guidance = d[self.guidance] + for key_label in guidance.keys(): + # Getting signal based on guidance + signal = self._get_signal(image, guidance[key_label]) + tmp_image = np.concatenate([tmp_image, signal], axis=0) + if isinstance(d[key], MetaTensor): + d[key].array = tmp_image + else: + d[key] = tmp_image + return d + else: + print("This transform only applies to image key") + return d + + +class FindAllValidSlicesDeepEditd(MapTransform): + """ + Find/List all valid slices in the labels. + Label is assumed to be a 4D Volume with shape CHWD, where C=1. + + Args: + sids: key to store slices indices having valid label map. + """ + + def __init__(self, keys: KeysCollection, sids: Hashable = "sids", allow_missing_keys: bool = False): + super().__init__(keys, allow_missing_keys) + self.sids = sids + + def _apply(self, label, d): + sids = {} + for key_label in d["label_names"].keys(): + l_ids = [] + for sid in range(label.shape[-1]): # Assume channel is first and depth is last CHWD + if d["label_names"][key_label] in label[0][..., sid]: + l_ids.append(sid) + sids[key_label] = l_ids + return sids + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "label": + label = d[key] + if label.shape[0] != 1: + raise ValueError("Only supports single channel labels!") + + if len(label.shape) != 4: # only for 3D + raise ValueError("Only supports label with shape CHWD!") + + sids = self._apply(label, d) + if sids is not None and len(sids.keys()): + d[self.sids] = sids + return d + else: + print("This transform only applies to label key") + return d + + +class AddInitialSeedPointDeepEditd(Randomizable, MapTransform): + """ + Add random guidance as initial seed point for a given label. + + Note that the label is of size (C, D, H, W) or (C, H, W) + + The guidance is of size (2, N, # of dims) where N is number of guidance added. + # of dims = 4 when C, D, H, W; # of dims = 3 when (C, H, W) + + Args: + guidance: key to store guidance. + sids: key that represents lists of valid slice indices for the given label. + sid: key that represents the slice to add initial seed point. If not present, random sid will be chosen. + connected_regions: maximum connected regions to use for adding initial points. + """ + + def __init__( + self, + keys: KeysCollection, + guidance: str = "guidance", + sids: str = "sids", + sid: str = "sid", + connected_regions: int = 5, + allow_missing_keys: bool = False, + ): + super().__init__(keys, allow_missing_keys) + self.sids_key = sids + self.sid_key = sid + self.sid: dict[str, int] = dict() + self.guidance = guidance + self.connected_regions = connected_regions + + def _apply(self, label, sid, key_label): + dimensions = 3 if len(label.shape) > 3 else 2 + self.default_guidance = [-1] * (dimensions + 1) + + dims = dimensions + if sid is not None and dimensions == 3: + dims = 2 + label = label[0][..., sid][np.newaxis] # Assume channel is first and depth is last CHWD + + # THERE MAY BE MULTIPLE BLOBS FOR SINGLE LABEL IN THE SELECTED SLICE + label = (label > 0.5).astype(np.float32) + # measure.label: Label connected regions of an integer array - Two pixels are connected + # when they are neighbors and have the same value + blobs_labels = measure.label(label.astype(int), background=0) if dims == 2 else label + if np.max(blobs_labels) <= 0: + raise AssertionError(f"SLICES NOT FOUND FOR LABEL: {key_label}") + + pos_guidance = [] + for ridx in range(1, 2 if dims == 3 else self.connected_regions + 1): + if dims == 2: + label = (blobs_labels == ridx).astype(np.float32) + if np.sum(label) == 0: + pos_guidance.append(self.default_guidance) + continue + + # The distance transform provides a metric or measure of the separation of points in the image. + # This function calculates the distance between each pixel that is set to off (0) and + # the nearest nonzero pixel for binary images - http://matlab.izmiran.ru/help/toolbox/images/morph14.html + distance = distance_transform_cdt(label).flatten() + probability = np.exp(distance) - 1.0 + + idx = np.where(label.flatten() > 0)[0] + seed = self.R.choice(idx, size=1, p=probability[idx] / np.sum(probability[idx])) + dst = distance[seed] + + g = np.asarray(np.unravel_index(seed, label.shape)).transpose().tolist()[0] + g[0] = dst[0] # for debug + if dimensions == 2 or dims == 3: + pos_guidance.append(g) + else: + # Clicks are created using this convention Channel Height Width Depth (CHWD) + pos_guidance.append([g[0], g[-2], g[-1], sid]) # Assume channel is first and depth is last CHWD + + return np.asarray([pos_guidance]) + + def _randomize(self, d, key_label): + sids = d.get(self.sids_key).get(key_label) if d.get(self.sids_key) is not None else None + sid = d.get(self.sid_key).get(key_label) if d.get(self.sid_key) is not None else None + if sids is not None and sids: + if sid is None or sid not in sids: + sid = self.R.choice(sids, replace=False) + else: + logger.info(f"Not slice IDs for label: {key_label}") + sid = None + self.sid[key_label] = sid + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "label": + label_guidances = {} + for key_label in d["sids"].keys(): + # Randomize: Select a random slice + self._randomize(d, key_label) + # Generate guidance base on selected slice + tmp_label = np.copy(d[key]) + # Taking one label to create the guidance + if key_label != "background": + tmp_label[tmp_label != float(d["label_names"][key_label])] = 0 + else: + tmp_label[tmp_label != float(d["label_names"][key_label])] = 1 + tmp_label = 1 - tmp_label + label_guidances[key_label] = json.dumps( + self._apply(tmp_label, self.sid.get(key_label), key_label).astype(int).tolist() + ) + d[self.guidance] = label_guidances + return d + else: + print("This transform only applies to label key") + return d + + +class FindDiscrepancyRegionsDeepEditd(MapTransform): + """ + Find discrepancy between prediction and actual during click interactions during training. + + Args: + pred: key to prediction source. + discrepancy: key to store discrepancies found between label and prediction. + """ + + def __init__( + self, + keys: KeysCollection, + pred: str = "pred", + discrepancy: str = "discrepancy", + allow_missing_keys: bool = False, + ): + super().__init__(keys, allow_missing_keys) + self.pred = pred + self.discrepancy = discrepancy + + @staticmethod + def disparity(label, pred): + disparity = label - pred + # Negative ONES mean predicted label is not part of the ground truth + # Positive ONES mean predicted label missed that region of the ground truth + pos_disparity = (disparity > 0).astype(np.float32) + neg_disparity = (disparity < 0).astype(np.float32) + return [pos_disparity, neg_disparity] + + def _apply(self, label, pred): + return self.disparity(label, pred) + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "label": + all_discrepancies = {} + for _, (key_label, val_label) in enumerate(d["label_names"].items()): + if key_label != "background": + # Taking single label + label = np.copy(d[key]) + label[label != val_label] = 0 + # Label should be represented in 1 + label = (label > 0.5).astype(np.float32) + # Taking single prediction + pred = np.copy(d[self.pred]) + pred[pred != val_label] = 0 + # Prediction should be represented in one + pred = (pred > 0.5).astype(np.float32) + else: + # Taking single label + label = np.copy(d[key]) + label[label != val_label] = 1 + label = 1 - label + # Label should be represented in 1 + label = (label > 0.5).astype(np.float32) + # Taking single prediction + pred = np.copy(d[self.pred]) + pred[pred != val_label] = 1 + pred = 1 - pred + # Prediction should be represented in one + pred = (pred > 0.5).astype(np.float32) + all_discrepancies[key_label] = self._apply(label, pred) + d[self.discrepancy] = all_discrepancies + return d + else: + print("This transform only applies to 'label' key") + return d + + +class AddRandomGuidanceDeepEditd(Randomizable, MapTransform): + """ + Add random guidance based on discrepancies that were found between label and prediction. + + Args: + guidance: key to guidance source, shape (2, N, # of dim) + discrepancy: key to discrepancy map between label and prediction shape (2, C, H, W, D) or (2, C, H, W) + probability: key to click/interaction probability, shape (1) + """ + + def __init__( + self, + keys: KeysCollection, + guidance: str = "guidance", + discrepancy: str = "discrepancy", + probability: str = "probability", + allow_missing_keys: bool = False, + ): + super().__init__(keys, allow_missing_keys) + self.guidance_key = guidance + self.discrepancy = discrepancy + self.probability = probability + self._will_interact = None + self.is_pos: bool | None = None + self.is_other: bool | None = None + self.default_guidance = None + self.guidance: dict[str, list[list[int]]] = {} + + def randomize(self, data=None): + probability = data[self.probability] + self._will_interact = self.R.choice([True, False], p=[probability, 1.0 - probability]) + + def find_guidance(self, discrepancy): + distance = distance_transform_cdt(discrepancy).flatten() + probability = np.exp(distance.flatten()) - 1.0 + idx = np.where(discrepancy.flatten() > 0)[0] + + if np.sum(discrepancy > 0) > 0: + seed = self.R.choice(idx, size=1, p=probability[idx] / np.sum(probability[idx])) + dst = distance[seed] + + g = np.asarray(np.unravel_index(seed, discrepancy.shape)).transpose().tolist()[0] + g[0] = dst[0] + return g + return None + + def add_guidance(self, guidance, discrepancy, label_names, labels): + # Positive clicks of the segment in the iteration + pos_discr = discrepancy[0] # idx 0 is positive discrepancy and idx 1 is negative discrepancy + + # Check the areas that belong to other segments + other_discrepancy_areas = {} + for _, (key_label, val_label) in enumerate(label_names.items()): + if key_label != "background": + tmp_label = np.copy(labels) + tmp_label[tmp_label != val_label] = 0 + tmp_label = (tmp_label > 0.5).astype(np.float32) + other_discrepancy_areas[key_label] = np.sum(discrepancy[1] * tmp_label) + else: + tmp_label = np.copy(labels) + tmp_label[tmp_label != val_label] = 1 + tmp_label = 1 - tmp_label + other_discrepancy_areas[key_label] = np.sum(discrepancy[1] * tmp_label) + + # Add guidance to the current key label + if np.sum(pos_discr) > 0: + guidance.append(self.find_guidance(pos_discr)) + self.is_pos = True + + # Add guidance to the other areas + for key_label in label_names.keys(): + # Areas that cover more than 50 voxels + if other_discrepancy_areas[key_label] > 50: + self.is_other = True + if key_label != "background": + tmp_label = np.copy(labels) + tmp_label[tmp_label != label_names[key_label]] = 0 + tmp_label = (tmp_label > 0.5).astype(np.float32) + self.guidance[key_label].append(self.find_guidance(discrepancy[1] * tmp_label)) + else: + tmp_label = np.copy(labels) + tmp_label[tmp_label != label_names[key_label]] = 1 + tmp_label = 1 - tmp_label + self.guidance[key_label].append(self.find_guidance(discrepancy[1] * tmp_label)) + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + guidance = d[self.guidance_key] + discrepancy = d[self.discrepancy] + self.randomize(data) + if self._will_interact: + # Convert all guidance to lists so new guidance can be easily appended + for key_label in d["label_names"].keys(): + tmp_gui = guidance[key_label] + tmp_gui = tmp_gui.tolist() if isinstance(tmp_gui, np.ndarray) else tmp_gui + tmp_gui = json.loads(tmp_gui) if isinstance(tmp_gui, str) else tmp_gui + self.guidance[key_label] = [j for j in tmp_gui if -1 not in j] + + # Add guidance according to discrepancy + for key_label in d["label_names"].keys(): + # Add guidance based on discrepancy + self.add_guidance(self.guidance[key_label], discrepancy[key_label], d["label_names"], d["label"]) + + # Checking the number of clicks + num_clicks = random.randint(1, 10) + counter = 0 + keep_guidance = [] + while True: + aux_label = random.choice(list(d["label_names"].keys())) + if aux_label in keep_guidance: + pass + else: + keep_guidance.append(aux_label) + counter = counter + len(self.guidance[aux_label]) + # If collected clicks is bigger than max clicks, discard the others + if counter >= num_clicks: + for key_label in d["label_names"].keys(): + if key_label not in keep_guidance: + self.guidance[key_label] = [] + logger.info(f"Number of simulated clicks: {counter}") + break + + # Breaking once all labels are covered + if len(keep_guidance) == len(d["label_names"].keys()): + logger.info(f"Number of simulated clicks: {counter}") + break + d[self.guidance_key] = self.guidance # Update the guidance + return d + + +class AddGuidanceFromPointsDeepEditd(Transform): + """ + Add guidance based on user clicks. ONLY WORKS FOR 3D + + We assume the input is loaded by LoadImaged and has the shape of (H, W, D) originally. + Clicks always specify the coordinates in (H, W, D) + + Args: + ref_image: key to reference image to fetch current and original image details. + guidance: output key to store guidance. + meta_keys: explicitly indicate the key of the metadata dictionary of `ref_image`. + for example, for data with key `image`, the metadata by default is in `image_meta_dict`. + the metadata is a dictionary object which contains: filename, original_shape, etc. + if None, will try to construct meta_keys by `{ref_image}_{meta_key_postfix}`. + meta_key_postfix: if meta_key is None, use `{ref_image}_{meta_key_postfix}` to fetch the metadata according + to the key data, default is `meta_dict`, the metadata is a dictionary object. + For example, to handle key `image`, read/write affine matrices from the + metadata `image_meta_dict` dictionary's `affine` field. + + """ + + def __init__( + self, + ref_image: str, + guidance: str = "guidance", + label_names: dict | None = None, + meta_keys: str | None = None, + meta_key_postfix: str = "meta_dict", + ): + self.ref_image = ref_image + self.guidance = guidance + self.label_names = label_names or {} + self.meta_keys = meta_keys + self.meta_key_postfix = meta_key_postfix + + @staticmethod + def _apply(clicks, factor): + if len(clicks): + guidance = np.multiply(clicks, factor).astype(int).tolist() + return guidance + else: + return [] + + def __call__(self, data): + d = dict(data) + meta_dict_key = self.meta_keys or f"{self.ref_image}_{self.meta_key_postfix}" + # extract affine matrix from metadata + if isinstance(d[self.ref_image], MetaTensor): + meta_dict = d[self.ref_image].meta + elif meta_dict_key in d: + meta_dict = d[meta_dict_key] + else: + raise ValueError( + f"{meta_dict_key} is not found. Please check whether it is the correct the image meta key." + ) + + if "spatial_shape" not in meta_dict: + raise RuntimeError('Missing "spatial_shape" in meta_dict!') + + # Assume channel is first and depth is last CHWD + original_shape = meta_dict["spatial_shape"] + current_shape = list(d[self.ref_image].shape)[1:] + + # in here we assume the depth dimension is in the last dimension of "original_shape" and "current_shape" + factor = np.array(current_shape) / original_shape + + # Creating guidance for all clicks + all_guidances = {} + for key_label in self.label_names.keys(): + clicks = d.get(key_label, []) + clicks = list(np.array(clicks).astype(int)) + all_guidances[key_label] = self._apply(clicks, factor) + d[self.guidance] = all_guidances + return d + + +class ResizeGuidanceMultipleLabelDeepEditd(Transform): + """ + Resize the guidance based on cropped vs resized image. + + """ + + def __init__(self, guidance: str, ref_image: str) -> None: + self.guidance = guidance + self.ref_image = ref_image + + def __call__(self, data): + d = dict(data) + # Assume channel is first and depth is last CHWD + current_shape = d[self.ref_image].shape[1:] + + meta_dict_key = "image_meta_dict" + # extract affine matrix from metadata + if isinstance(d[self.ref_image], MetaTensor): + meta_dict = d[self.ref_image].meta + elif meta_dict_key in d: + meta_dict = d[meta_dict_key] + else: + raise ValueError( + f"{meta_dict_key} is not found. Please check whether it is the correct the image meta key." + ) + + original_shape = meta_dict["spatial_shape"] + + factor = np.divide(current_shape, original_shape) + all_guidances = {} + for key_label in d[self.guidance].keys(): + guidance = ( + np.multiply(d[self.guidance][key_label], factor).astype(int).tolist() + if len(d[self.guidance][key_label]) + else [] + ) + all_guidances[key_label] = guidance + + d[self.guidance] = all_guidances + return d + + +class SplitPredsLabeld(MapTransform): + """ + Split preds and labels for individual evaluation + + """ + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "pred": + for idx, (key_label, _) in enumerate(d["label_names"].items()): + if key_label != "background": + d[f"pred_{key_label}"] = d[key][idx + 1, ...][None] + d[f"label_{key_label}"] = d["label"][idx + 1, ...][None] + elif key != "pred": + logger.info("This is only for pred key") + return d + + +class AddInitialSeedPointMissingLabelsd(Randomizable, MapTransform): + """ + Add random guidance as initial seed point for a given label. + Note that the label is of size (C, D, H, W) or (C, H, W) + The guidance is of size (2, N, # of dims) where N is number of guidance added. + # of dims = 4 when C, D, H, W; # of dims = 3 when (C, H, W) + Args: + guidance: key to store guidance. + sids: key that represents lists of valid slice indices for the given label. + sid: key that represents the slice to add initial seed point. If not present, random sid will be chosen. + connected_regions: maximum connected regions to use for adding initial points. + """ + + def __init__( + self, + keys: KeysCollection, + guidance: str = "guidance", + sids: str = "sids", + sid: str = "sid", + connected_regions: int = 5, + allow_missing_keys: bool = False, + ): + super().__init__(keys, allow_missing_keys) + self.sids_key = sids + self.sid_key = sid + self.sid: dict[str, int] = dict() + self.guidance = guidance + self.connected_regions = connected_regions + + def _apply(self, label, sid): + dimensions = 3 if len(label.shape) > 3 else 2 + self.default_guidance = [-1] * (dimensions + 1) + + dims = dimensions + if sid is not None and dimensions == 3: + dims = 2 + label = label[0][..., sid][np.newaxis] # Assume channel is first and depth is last CHWD + + # THERE MAY BE MULTIPLE BLOBS FOR SINGLE LABEL IN THE SELECTED SLICE + label = (label > 0.5).astype(np.float32) + # measure.label: Label connected regions of an integer array - Two pixels are connected + # when they are neighbors and have the same value + blobs_labels = measure.label(label.astype(int), background=0) if dims == 2 else label + + label_guidance = [] + # If there are is presence of that label in this slice + if np.max(blobs_labels) <= 0: + label_guidance.append(self.default_guidance) + else: + for ridx in range(1, 2 if dims == 3 else self.connected_regions + 1): + if dims == 2: + label = (blobs_labels == ridx).astype(np.float32) + if np.sum(label) == 0: + label_guidance.append(self.default_guidance) + continue + + # The distance transform provides a metric or measure of the separation of points in the image. + # This function calculates the distance between each pixel that is set to off (0) and + # the nearest nonzero pixel for binary images + # http://matlab.izmiran.ru/help/toolbox/images/morph14.html + distance = distance_transform_cdt(label).flatten() + probability = np.exp(distance) - 1.0 + + idx = np.where(label.flatten() > 0)[0] + seed = self.R.choice(idx, size=1, p=probability[idx] / np.sum(probability[idx])) + dst = distance[seed] + + g = np.asarray(np.unravel_index(seed, label.shape)).transpose().tolist()[0] + g[0] = dst[0] # for debug + if dimensions == 2 or dims == 3: + label_guidance.append(g) + else: + # Clicks are created using this convention Channel Height Width Depth (CHWD) + label_guidance.append([g[0], g[-2], g[-1], sid]) # Assume channel is first and depth is last CHWD + + return np.asarray(label_guidance) + + def _randomize(self, d, key_label): + sids = d.get(self.sids_key).get(key_label) if d.get(self.sids_key) is not None else None + sid = d.get(self.sid_key).get(key_label) if d.get(self.sid_key) is not None else None + if sids is not None and sids: + if sid is None or sid not in sids: + sid = self.R.choice(sids, replace=False) + else: + logger.info(f"Not slice IDs for label: {key_label}") + sid = None + self.sid[key_label] = sid + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "label": + label_guidances = {} + for key_label in d["sids"].keys(): + # Randomize: Select a random slice + self._randomize(d, key_label) + # Generate guidance base on selected slice + tmp_label = np.copy(d[key]) + # Taking one label to create the guidance + if key_label != "background": + tmp_label[tmp_label != float(d["label_names"][key_label])] = 0 + else: + tmp_label[tmp_label != float(d["label_names"][key_label])] = 1 + tmp_label = 1 - tmp_label + label_guidances[key_label] = json.dumps( + self._apply(tmp_label, self.sid.get(key_label)).astype(int).tolist() + ) + d[self.guidance] = label_guidances + return d + else: + print("This transform only applies to label key") + return d + + +class FindAllValidSlicesMissingLabelsd(MapTransform): + """ + Find/List all valid slices in the labels. + Label is assumed to be a 4D Volume with shape CHWD, where C=1. + Args: + sids: key to store slices indices having valid label map. + """ + + def __init__(self, keys: KeysCollection, sids: Hashable = "sids", allow_missing_keys: bool = False): + super().__init__(keys, allow_missing_keys) + self.sids = sids + + def _apply(self, label, d): + sids = {} + for key_label in d["label_names"].keys(): + l_ids = [] + for sid in range(label.shape[-1]): # Assume channel is first and depth is last CHWD + if d["label_names"][key_label] in label[0][..., sid]: + l_ids.append(sid) + # If there are not slices with the label + if l_ids == []: + l_ids = [-1] * 10 + sids[key_label] = l_ids + return sids + + def __call__(self, data: Mapping[Hashable, np.ndarray]) -> dict[Hashable, np.ndarray]: + d: dict = dict(data) + for key in self.key_iterator(d): + if key == "label": + label = d[key] + if label.shape[0] != 1: + raise ValueError("Only supports single channel labels!") + + if len(label.shape) != 4: # only for 3D + raise ValueError("Only supports label with shape CHWD!") + + sids = self._apply(label, d) + if sids is not None and len(sids.keys()): + d[self.sids] = sids + return d + else: + print("This transform only applies to label key") + return d diff --git a/source_code/SegMamba/monai/apps/deepgrow/__init__.py b/source_code/SegMamba/monai/apps/deepgrow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e97f8940782e96a77c1c08483fc41da9a48ae22 --- /dev/null +++ b/source_code/SegMamba/monai/apps/deepgrow/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/source_code/SegMamba/monai/apps/deepgrow/dataset.py b/source_code/SegMamba/monai/apps/deepgrow/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..802d86e0c72d9ac9c6ebfce0ed4270801290f8a5 --- /dev/null +++ b/source_code/SegMamba/monai/apps/deepgrow/dataset.py @@ -0,0 +1,271 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import logging +import os +from collections.abc import Sequence + +import numpy as np + +from monai.config import PathLike +from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, Orientationd, Spacingd, SqueezeDimd, Transform +from monai.utils import GridSampleMode + + +def create_dataset( + datalist: list[dict], + output_dir: str, + dimension: int, + pixdim: Sequence[float] | float, + image_key: str = "image", + label_key: str = "label", + base_dir: PathLike | None = None, + limit: int = 0, + relative_path: bool = False, + transforms: Transform | None = None, +) -> list[dict]: + """ + Utility to pre-process and create dataset list for Deepgrow training over on existing one. + The input data list is normally a list of images and labels (3D volume) that needs pre-processing + for Deepgrow training pipeline. + + Args: + datalist: A list of data dictionary. Each entry should at least contain 'image_key': . + For example, typical input data can be a list of dictionaries:: + + [{'image': , 'label':