diff --git a/source_code/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/.ninja_log b/source_code/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/.ninja_log new file mode 100644 index 0000000000000000000000000000000000000000..3eb9634e533c1082f780ea31d8de8a59563ecad2 --- /dev/null +++ b/source_code/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/.ninja_log @@ -0,0 +1,11 @@ +# ninja log v5 +0 19490 1769349310623049020 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan.o 36279c78d02f77a4 +1 39202 1769349330318255082 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_fp32.o 7d6547add5004b46 +1 39876 1769349330973261935 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_fp16.o 4bbc57405a8462fd +1 40297 1769349331412266528 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_bf16.o 4bcb4935fbabf375 +1 65588 1769349356697531076 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp32_real.o 7aa656e8f759244 +0 67915 1769349359001555182 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp16_real.o a9ff622fcbfad133 +0 70957 1769349362064587229 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_bf16_real.o 975c2cf7bf417ec8 +1 92869 1769349383962816340 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp32_complex.o 18c4e1712400dbd8 +0 94589 1769349385684834357 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp16_complex.o f494d02f2077ad75 +0 99933 1769349391029890280 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_bf16_complex.o f81edc21b8db261 diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/reverse_scan.cuh b/source_code/SegMamba/mamba/csrc/selective_scan/reverse_scan.cuh new file mode 100644 index 0000000000000000000000000000000000000000..d7e93174bb391d45271e6c77669a5e52d6c9cc78 --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/reverse_scan.cuh @@ -0,0 +1,401 @@ +/****************************************************************************** + * Copyright (c) 2023, Tri Dao. + ******************************************************************************/ + +#pragma once + +#include + +#include +#include +#include +// #include +#include "uninitialized_copy.cuh" + +/** + * Perform a reverse sequential reduction over \p LENGTH elements of the \p input array. The aggregate is returned. + */ +template < + int LENGTH, + typename T, + typename ReductionOp> +__device__ __forceinline__ T ThreadReverseReduce(const T (&input)[LENGTH], ReductionOp reduction_op) { + static_assert(LENGTH > 0); + T retval = input[LENGTH - 1]; + #pragma unroll + for (int i = LENGTH - 2; i >= 0; --i) { retval = reduction_op(retval, input[i]); } + return retval; +} + +/** + * Perform a sequential inclusive postfix reverse scan over the statically-sized \p input array, seeded with the specified \p postfix. The aggregate is returned. + */ +template < + int LENGTH, + typename T, + typename ScanOp> +__device__ __forceinline__ T ThreadReverseScanInclusive( + const T (&input)[LENGTH], + T (&output)[LENGTH], + ScanOp scan_op, + const T postfix) +{ + T inclusive = postfix; + #pragma unroll + for (int i = LENGTH - 1; i >= 0; --i) { + inclusive = scan_op(inclusive, input[i]); + output[i] = inclusive; + } +} + +/** + * Perform a sequential exclusive postfix reverse scan over the statically-sized \p input array, seeded with the specified \p postfix. The aggregate is returned. + */ +template < + int LENGTH, + typename T, + typename ScanOp> +__device__ __forceinline__ T ThreadReverseScanExclusive( + const T (&input)[LENGTH], + T (&output)[LENGTH], + ScanOp scan_op, + const T postfix) +{ + // Careful, output maybe be aliased to input + T exclusive = postfix; + T inclusive; + #pragma unroll + for (int i = LENGTH - 1; i >= 0; --i) { + inclusive = scan_op(exclusive, input[i]); + output[i] = exclusive; + exclusive = inclusive; + } + return inclusive; +} + + +/** + * \brief WarpReverseScan provides SHFL-based variants of parallel postfix scan of items partitioned across a CUDA thread warp. + * + * LOGICAL_WARP_THREADS must be a power-of-two + */ +template < + typename T, ///< Data type being scanned + int LOGICAL_WARP_THREADS ///< Number of threads per logical warp + > +struct WarpReverseScan { + //--------------------------------------------------------------------- + // Constants and type definitions + //--------------------------------------------------------------------- + + /// Whether the logical warp size and the PTX warp size coincide + static constexpr bool IS_ARCH_WARP = (LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0)); + /// The number of warp scan steps + static constexpr int STEPS = cub::Log2::VALUE; + static_assert(LOGICAL_WARP_THREADS == 1 << STEPS); + + + //--------------------------------------------------------------------- + // Thread fields + //--------------------------------------------------------------------- + + /// Lane index in logical warp + unsigned int lane_id; + + /// Logical warp index in 32-thread physical warp + unsigned int warp_id; + + /// 32-thread physical warp member mask of logical warp + unsigned int member_mask; + + //--------------------------------------------------------------------- + // Construction + //--------------------------------------------------------------------- + + /// Constructor + explicit __device__ __forceinline__ + WarpReverseScan() + : lane_id(cub::LaneId()) + , warp_id(IS_ARCH_WARP ? 0 : (lane_id / LOGICAL_WARP_THREADS)) + , member_mask(cub::WarpMask(warp_id)) + { + if (!IS_ARCH_WARP) { + lane_id = lane_id % LOGICAL_WARP_THREADS; + } + } + + + /// Broadcast + __device__ __forceinline__ T Broadcast( + T input, ///< [in] The value to broadcast + int src_lane) ///< [in] Which warp lane is to do the broadcasting + { + return cub::ShuffleIndex(input, src_lane, member_mask); + } + + + /// Inclusive scan + template + __device__ __forceinline__ void InclusiveReverseScan( + T input, ///< [in] Calling thread's input item. + T &inclusive_output, ///< [out] Calling thread's output item. May be aliased with \p input. + ScanOpT scan_op) ///< [in] Binary scan operator + { + inclusive_output = input; + #pragma unroll + for (int STEP = 0; STEP < STEPS; STEP++) { + int offset = 1 << STEP; + T temp = cub::ShuffleDown( + inclusive_output, offset, LOGICAL_WARP_THREADS - 1, member_mask + ); + // Perform scan op if from a valid peer + inclusive_output = static_cast(lane_id) >= LOGICAL_WARP_THREADS - offset + ? inclusive_output : scan_op(temp, inclusive_output); + } + } + + /// Exclusive scan + // Get exclusive from inclusive + template + __device__ __forceinline__ void ExclusiveReverseScan( + T input, ///< [in] Calling thread's input item. + T &exclusive_output, ///< [out] Calling thread's output item. May be aliased with \p input. + ScanOpT scan_op, ///< [in] Binary scan operator + T &warp_aggregate) ///< [out] Warp-wide aggregate reduction of input items. + { + T inclusive_output; + InclusiveReverseScan(input, inclusive_output, scan_op); + warp_aggregate = cub::ShuffleIndex(inclusive_output, 0, member_mask); + // initial value unknown + exclusive_output = cub::ShuffleDown( + inclusive_output, 1, LOGICAL_WARP_THREADS - 1, member_mask + ); + } + + /** + * \brief Computes both inclusive and exclusive reverse scans using the specified binary scan functor across the calling warp. Because no initial value is supplied, the \p exclusive_output computed for the last warp-lane is undefined. + */ + template + __device__ __forceinline__ void ReverseScan( + T input, ///< [in] Calling thread's input item. + T &inclusive_output, ///< [out] Calling thread's inclusive-scan output item. + T &exclusive_output, ///< [out] Calling thread's exclusive-scan output item. + ScanOpT scan_op) ///< [in] Binary scan operator + { + InclusiveReverseScan(input, inclusive_output, scan_op); + // initial value unknown + exclusive_output = cub::ShuffleDown( + inclusive_output, 1, LOGICAL_WARP_THREADS - 1, member_mask + ); + } + +}; + +/** + * \brief BlockReverseScan provides variants of raking-based parallel postfix scan across a CUDA thread block. + */ +template < + typename T, ///< Data type being scanned + int BLOCK_DIM_X, ///< The thread block length in threads along the X dimension + bool MEMOIZE=false ///< Whether or not to buffer outer raking scan partials to incur fewer shared memory reads at the expense of higher register pressure + > +struct BlockReverseScan { + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + /// Constants + /// The thread block size in threads + static constexpr int BLOCK_THREADS = BLOCK_DIM_X; + + /// Layout type for padded thread block raking grid + using BlockRakingLayout = cub::BlockRakingLayout; + // The number of reduction elements is not a multiple of the number of raking threads for now + static_assert(BlockRakingLayout::UNGUARDED); + + /// Number of raking threads + static constexpr int RAKING_THREADS = BlockRakingLayout::RAKING_THREADS; + /// Number of raking elements per warp synchronous raking thread + static constexpr int SEGMENT_LENGTH = BlockRakingLayout::SEGMENT_LENGTH; + /// Cooperative work can be entirely warp synchronous + static constexpr bool WARP_SYNCHRONOUS = (int(BLOCK_THREADS) == int(RAKING_THREADS)); + + /// WarpReverseScan utility type + using WarpReverseScan = WarpReverseScan; + + /// Shared memory storage layout type + struct _TempStorage { + typename BlockRakingLayout::TempStorage raking_grid; ///< Padded thread block raking grid + }; + + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : cub::Uninitialized<_TempStorage> {}; + + + //--------------------------------------------------------------------- + // Per-thread fields + //--------------------------------------------------------------------- + + // Thread fields + _TempStorage &temp_storage; + unsigned int linear_tid; + T cached_segment[SEGMENT_LENGTH]; + + + //--------------------------------------------------------------------- + // Utility methods + //--------------------------------------------------------------------- + + /// Performs upsweep raking reduction, returning the aggregate + template + __device__ __forceinline__ T Upsweep(ScanOp scan_op) { + T *smem_raking_ptr = BlockRakingLayout::RakingPtr(temp_storage.raking_grid, linear_tid); + // Read data into registers + #pragma unroll + for (int i = 0; i < SEGMENT_LENGTH; ++i) { cached_segment[i] = smem_raking_ptr[i]; } + T raking_partial = cached_segment[SEGMENT_LENGTH - 1]; + #pragma unroll + for (int i = SEGMENT_LENGTH - 2; i >= 0; --i) { + raking_partial = scan_op(raking_partial, cached_segment[i]); + } + return raking_partial; + } + + + /// Performs exclusive downsweep raking scan + template + __device__ __forceinline__ void ExclusiveDownsweep( + ScanOp scan_op, + T raking_partial) + { + T *smem_raking_ptr = BlockRakingLayout::RakingPtr(temp_storage.raking_grid, linear_tid); + // Read data back into registers + if (!MEMOIZE) { + #pragma unroll + for (int i = 0; i < SEGMENT_LENGTH; ++i) { cached_segment[i] = smem_raking_ptr[i]; } + } + ThreadReverseScanExclusive(cached_segment, cached_segment, scan_op, raking_partial); + // Write data back to smem + #pragma unroll + for (int i = 0; i < SEGMENT_LENGTH; ++i) { smem_raking_ptr[i] = cached_segment[i]; } + } + + + //--------------------------------------------------------------------- + // Constructors + //--------------------------------------------------------------------- + + /// Constructor + __device__ __forceinline__ BlockReverseScan( + TempStorage &temp_storage) + : + temp_storage(temp_storage.Alias()), + linear_tid(cub::RowMajorTid(BLOCK_DIM_X, 1, 1)) + {} + + + /// Computes an exclusive thread block-wide postfix scan using the specified binary \p scan_op functor. Each thread contributes one input element. the call-back functor \p block_postfix_callback_op is invoked by the first warp in the block, and the value returned by lane0 in that warp is used as the "seed" value that logically postfixes the thread block's scan inputs. Also provides every thread with the block-wide \p block_aggregate of all inputs. + template < + typename ScanOp, + typename BlockPostfixCallbackOp> + __device__ __forceinline__ void ExclusiveReverseScan( + T input, ///< [in] Calling thread's input item + T &exclusive_output, ///< [out] Calling thread's output item (may be aliased to \p input) + ScanOp scan_op, ///< [in] Binary scan operator + BlockPostfixCallbackOp &block_postfix_callback_op) ///< [in-out] [warp0 only] Call-back functor for specifying a thread block-wide postfix to be applied to all inputs. + { + if (WARP_SYNCHRONOUS) { + // Short-circuit directly to warp-synchronous scan + T block_aggregate; + WarpReverseScan warp_scan; + warp_scan.ExclusiveReverseScan(input, exclusive_output, scan_op, block_aggregate); + // Obtain warp-wide postfix in lane0, then broadcast to other lanes + T block_postfix = block_postfix_callback_op(block_aggregate); + block_postfix = warp_scan.Broadcast(block_postfix, 0); + exclusive_output = linear_tid == BLOCK_THREADS - 1 ? block_postfix : scan_op(block_postfix, exclusive_output); + } else { + // Place thread partial into shared memory raking grid + T *placement_ptr = BlockRakingLayout::PlacementPtr(temp_storage.raking_grid, linear_tid); + detail::uninitialized_copy(placement_ptr, input); + cub::CTA_SYNC(); + // Reduce parallelism down to just raking threads + if (linear_tid < RAKING_THREADS) { + WarpReverseScan warp_scan; + // Raking upsweep reduction across shared partials + T upsweep_partial = Upsweep(scan_op); + // Warp-synchronous scan + T exclusive_partial, block_aggregate; + warp_scan.ExclusiveReverseScan(upsweep_partial, exclusive_partial, scan_op, block_aggregate); + // Obtain block-wide postfix in lane0, then broadcast to other lanes + T block_postfix = block_postfix_callback_op(block_aggregate); + block_postfix = warp_scan.Broadcast(block_postfix, 0); + // Update postfix with warpscan exclusive partial + T downsweep_postfix = linear_tid == RAKING_THREADS - 1 + ? block_postfix : scan_op(block_postfix, exclusive_partial); + // Exclusive raking downsweep scan + ExclusiveDownsweep(scan_op, downsweep_postfix); + } + cub::CTA_SYNC(); + // Grab thread postfix from shared memory + exclusive_output = *placement_ptr; + + // // Compute warp scan in each warp. + // // The exclusive output from the last lane in each warp is invalid. + // T inclusive_output; + // WarpReverseScan warp_scan; + // warp_scan.ReverseScan(input, inclusive_output, exclusive_output, scan_op); + + // // Compute the warp-wide postfix and block-wide aggregate for each warp. Warp postfix for the last warp is invalid. + // T block_aggregate; + // T warp_postfix = ComputeWarpPostfix(scan_op, inclusive_output, block_aggregate); + + // // Apply warp postfix to our lane's partial + // if (warp_id != 0) { + // exclusive_output = scan_op(warp_postfix, exclusive_output); + // if (lane_id == 0) { exclusive_output = warp_postfix; } + // } + + // // Use the first warp to determine the thread block postfix, returning the result in lane0 + // if (warp_id == 0) { + // T block_postfix = block_postfix_callback_op(block_aggregate); + // if (lane_id == 0) { + // // Share the postfix with all threads + // detail::uninitialized_copy(&temp_storage.block_postfix, + // block_postfix); + + // exclusive_output = block_postfix; // The block postfix is the exclusive output for tid0 + // } + // } + + // cub::CTA_SYNC(); + + // // Incorporate thread block postfix into outputs + // T block_postfix = temp_storage.block_postfix; + // if (linear_tid > 0) { exclusive_output = scan_op(block_postfix, exclusive_output); } + } + } + + + /** + * \brief Computes an inclusive block-wide postfix scan using the specified binary \p scan_op functor. Each thread contributes an array of consecutive input elements. the call-back functor \p block_postfix_callback_op is invoked by the first warp in the block, and the value returned by lane0 in that warp is used as the "seed" value that logically postfixes the thread block's scan inputs. Also provides every thread with the block-wide \p block_aggregate of all inputs. + */ + template < + int ITEMS_PER_THREAD, + typename ScanOp, + typename BlockPostfixCallbackOp> + __device__ __forceinline__ void InclusiveReverseScan( + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + T (&output)[ITEMS_PER_THREAD], ///< [out] Calling thread's output items (may be aliased to \p input) + ScanOp scan_op, ///< [in] Binary scan functor + BlockPostfixCallbackOp &block_postfix_callback_op) ///< [in-out] [warp0 only] Call-back functor for specifying a block-wide postfix to be applied to the logical input sequence. + { + // Reduce consecutive thread items in registers + T thread_postfix = ThreadReverseReduce(input, scan_op); + // Exclusive thread block-scan + ExclusiveReverseScan(thread_postfix, thread_postfix, scan_op, block_postfix_callback_op); + // Inclusive scan in registers with postfix as seed + ThreadReverseScanInclusive(input, output, scan_op, thread_postfix); + } + +}; \ No newline at end of file diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan.h b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan.h new file mode 100644 index 0000000000000000000000000000000000000000..e2c7bcdbd5ddadc5975caa641ecb1dcd3b73dafd --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan.h @@ -0,0 +1,101 @@ +/****************************************************************************** + * Copyright (c) 2023, Tri Dao. + ******************************************************************************/ + +#pragma once + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +struct SSMScanParamsBase { + using index_t = uint32_t; + + int batch, seqlen, n_chunks; + index_t a_batch_stride; + index_t b_batch_stride; + index_t out_batch_stride; + + // Common data pointers. + void *__restrict__ a_ptr; + void *__restrict__ b_ptr; + void *__restrict__ out_ptr; + void *__restrict__ x_ptr; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +struct SSMParamsBase { + using index_t = uint32_t; + + int batch, dim, seqlen, dstate, n_groups, n_chunks; + int dim_ngroups_ratio; + bool is_variable_B; + bool is_variable_C; + + bool delta_softplus; + + index_t A_d_stride; + index_t A_dstate_stride; + index_t B_batch_stride; + index_t B_d_stride; + index_t B_dstate_stride; + index_t B_group_stride; + index_t C_batch_stride; + index_t C_d_stride; + index_t C_dstate_stride; + index_t C_group_stride; + index_t u_batch_stride; + index_t u_d_stride; + index_t delta_batch_stride; + index_t delta_d_stride; + index_t z_batch_stride; + index_t z_d_stride; + index_t out_batch_stride; + index_t out_d_stride; + index_t out_z_batch_stride; + index_t out_z_d_stride; + + // Common data pointers. + void *__restrict__ A_ptr; + void *__restrict__ B_ptr; + void *__restrict__ C_ptr; + void *__restrict__ D_ptr; + void *__restrict__ u_ptr; + void *__restrict__ delta_ptr; + void *__restrict__ delta_bias_ptr; + void *__restrict__ out_ptr; + void *__restrict__ x_ptr; + void *__restrict__ z_ptr; + void *__restrict__ out_z_ptr; +}; + +struct SSMParamsBwd: public SSMParamsBase { + index_t dout_batch_stride; + index_t dout_d_stride; + index_t dA_d_stride; + index_t dA_dstate_stride; + index_t dB_batch_stride; + index_t dB_group_stride; + index_t dB_d_stride; + index_t dB_dstate_stride; + index_t dC_batch_stride; + index_t dC_group_stride; + index_t dC_d_stride; + index_t dC_dstate_stride; + index_t du_batch_stride; + index_t du_d_stride; + index_t dz_batch_stride; + index_t dz_d_stride; + index_t ddelta_batch_stride; + index_t ddelta_d_stride; + + // Common data pointers. + void *__restrict__ dout_ptr; + void *__restrict__ dA_ptr; + void *__restrict__ dB_ptr; + void *__restrict__ dC_ptr; + void *__restrict__ dD_ptr; + void *__restrict__ du_ptr; + void *__restrict__ dz_ptr; + void *__restrict__ ddelta_ptr; + void *__restrict__ ddelta_bias_ptr; +}; diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_common.h b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_common.h new file mode 100644 index 0000000000000000000000000000000000000000..9140dcdf3b68ad2de95bcd3fd9543a9d320cef68 --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_common.h @@ -0,0 +1,221 @@ +/****************************************************************************** + * Copyright (c) 2023, Tri Dao. + ******************************************************************************/ + +#pragma once + +#include +#include +#include // For scalar_value_type + +#define MAX_DSTATE 256 + +using complex_t = c10::complex; + +inline __device__ float2 operator+(const float2 & a, const float2 & b){ + return {a.x + b.x, a.y + b.y}; +} + +inline __device__ float3 operator+(const float3 &a, const float3 &b) { + return {a.x + b.x, a.y + b.y, a.z + b.z}; +} + +inline __device__ float4 operator+(const float4 & a, const float4 & b){ + return {a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template struct BytesToType {}; + +template<> struct BytesToType<16> { + using Type = uint4; + static_assert(sizeof(Type) == 16); +}; + +template<> struct BytesToType<8> { + using Type = uint64_t; + static_assert(sizeof(Type) == 8); +}; + +template<> struct BytesToType<4> { + using Type = uint32_t; + static_assert(sizeof(Type) == 4); +}; + +template<> struct BytesToType<2> { + using Type = uint16_t; + static_assert(sizeof(Type) == 2); +}; + +template<> struct BytesToType<1> { + using Type = uint8_t; + static_assert(sizeof(Type) == 1); +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template +struct Converter{ + static inline __device__ void to_float(const scalar_t (&src)[N], float (&dst)[N]) { + #pragma unroll + for (int i = 0; i < N; ++i) { dst[i] = src[i]; } + } +}; + +template +struct Converter{ + static inline __device__ void to_float(const at::Half (&src)[N], float (&dst)[N]) { + static_assert(N % 2 == 0); + auto &src2 = reinterpret_cast(src); + auto &dst2 = reinterpret_cast(dst); + #pragma unroll + for (int i = 0; i < N / 2; ++i) { dst2[i] = __half22float2(src2[i]); } + } +}; + +#if __CUDA_ARCH__ >= 800 +template +struct Converter{ + static inline __device__ void to_float(const at::BFloat16 (&src)[N], float (&dst)[N]) { + static_assert(N % 2 == 0); + auto &src2 = reinterpret_cast(src); + auto &dst2 = reinterpret_cast(dst); + #pragma unroll + for (int i = 0; i < N / 2; ++i) { dst2[i] = __bfloat1622float2(src2[i]); } + } +}; +#endif + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +// From https://stackoverflow.com/questions/9860711/cucomplex-h-and-exp +// and https://forums.developer.nvidia.com/t/complex-number-exponential-function/24696 +__device__ __forceinline__ complex_t cexp2f(complex_t z) { + float t = exp2f(z.real_); + float c, s; + sincosf(z.imag_, &s, &c); + return complex_t(c * t, s * t); +} + +__device__ __forceinline__ complex_t cexpf(complex_t z) { + float t = expf(z.real_); + float c, s; + sincosf(z.imag_, &s, &c); + return complex_t(c * t, s * t); +} + +template struct SSMScanOp; + +template<> +struct SSMScanOp { + __device__ __forceinline__ float2 operator()(const float2 &ab0, const float2 &ab1) const { + return make_float2(ab1.x * ab0.x, ab1.x * ab0.y + ab1.y); + } +}; + +template<> +struct SSMScanOp { + __device__ __forceinline__ float4 operator()(const float4 &ab0, const float4 &ab1) const { + complex_t a0 = complex_t(ab0.x, ab0.y); + complex_t b0 = complex_t(ab0.z, ab0.w); + complex_t a1 = complex_t(ab1.x, ab1.y); + complex_t b1 = complex_t(ab1.z, ab1.w); + complex_t out_a = a1 * a0; + complex_t out_b = a1 * b0 + b1; + return make_float4(out_a.real_, out_a.imag_, out_b.real_, out_b.imag_); + } +}; + +// A stateful callback functor that maintains a running prefix to be applied +// during consecutive scan operations. +template struct SSMScanPrefixCallbackOp { + using scan_t = std::conditional_t, float2, float4>; + scan_t running_prefix; + // Constructor + __device__ SSMScanPrefixCallbackOp(scan_t running_prefix_) : running_prefix(running_prefix_) {} + // Callback operator to be entered by the first warp of threads in the block. + // Thread-0 is responsible for returning a value for seeding the block-wide scan. + __device__ scan_t operator()(scan_t block_aggregate) { + scan_t old_prefix = running_prefix; + running_prefix = SSMScanOp()(running_prefix, block_aggregate); + return old_prefix; + } +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template +inline __device__ void load_input(typename Ktraits::input_t *u, + typename Ktraits::input_t (&u_vals)[Ktraits::kNItems], + typename Ktraits::BlockLoadT::TempStorage &smem_load, + int seqlen) { + if constexpr (Ktraits::kIsEvenLen) { + auto& smem_load_vec = reinterpret_cast(smem_load); + using vec_t = typename Ktraits::vec_t; + Ktraits::BlockLoadVecT(smem_load_vec).Load( + reinterpret_cast(u), + reinterpret_cast(u_vals) + ); + } else { + Ktraits::BlockLoadT(smem_load).Load(u, u_vals, seqlen, 0.f); + } +} + +template +inline __device__ void load_weight(typename Ktraits::input_t *Bvar, + typename Ktraits::weight_t (&B_vals)[Ktraits::kNItems], + typename Ktraits::BlockLoadWeightT::TempStorage &smem_load_weight, + int seqlen) { + constexpr int kNItems = Ktraits::kNItems; + if constexpr (!Ktraits::kIsComplex) { + typename Ktraits::input_t B_vals_load[kNItems]; + if constexpr (Ktraits::kIsEvenLen) { + auto& smem_load_weight_vec = reinterpret_cast(smem_load_weight); + using vec_t = typename Ktraits::vec_t; + Ktraits::BlockLoadWeightVecT(smem_load_weight_vec).Load( + reinterpret_cast(Bvar), + reinterpret_cast(B_vals_load) + ); + } else { + Ktraits::BlockLoadWeightT(smem_load_weight).Load(Bvar, B_vals_load, seqlen, 0.f); + } + // #pragma unroll + // for (int i = 0; i < kNItems; ++i) { B_vals[i] = B_vals_load[i]; } + Converter::to_float(B_vals_load, B_vals); + } else { + typename Ktraits::input_t B_vals_load[kNItems * 2]; + if constexpr (Ktraits::kIsEvenLen) { + auto& smem_load_weight_vec = reinterpret_cast(smem_load_weight); + using vec_t = typename Ktraits::vec_t; + Ktraits::BlockLoadWeightVecT(smem_load_weight_vec).Load( + reinterpret_cast(Bvar), + reinterpret_cast(B_vals_load) + ); + } else { + Ktraits::BlockLoadWeightT(smem_load_weight).Load(Bvar, B_vals_load, seqlen, 0.f); + } + #pragma unroll + for (int i = 0; i < kNItems; ++i) { B_vals[i] = complex_t(B_vals_load[i * 2], B_vals_load[i * 2 + 1]); } + } +} + +template +inline __device__ void store_output(typename Ktraits::input_t *out, + const float (&out_vals)[Ktraits::kNItems], + typename Ktraits::BlockStoreT::TempStorage &smem_store, + int seqlen) { + typename Ktraits::input_t write_vals[Ktraits::kNItems]; + #pragma unroll + for (int i = 0; i < Ktraits::kNItems; ++i) { write_vals[i] = out_vals[i]; } + if constexpr (Ktraits::kIsEvenLen) { + auto& smem_store_vec = reinterpret_cast(smem_store); + using vec_t = typename Ktraits::vec_t; + Ktraits::BlockStoreVecT(smem_store_vec).Store( + reinterpret_cast(out), + reinterpret_cast(write_vals) + ); + } else { + Ktraits::BlockStoreT(smem_store).Store(out, write_vals, seqlen); + } +} diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp16.cu b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp16.cu new file mode 100644 index 0000000000000000000000000000000000000000..015e2a0eff633daf2693e43a2648008652a38c7c --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp16.cu @@ -0,0 +1,10 @@ +/****************************************************************************** + * Copyright (c) 2023, Tri Dao. + ******************************************************************************/ + +// Split into multiple files to compile in paralell + +#include "selective_scan_fwd_kernel.cuh" + +template void selective_scan_fwd_cuda(SSMParamsBase ¶ms, cudaStream_t stream); +template void selective_scan_fwd_cuda(SSMParamsBase ¶ms, cudaStream_t stream); \ No newline at end of file diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp32.cu b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp32.cu new file mode 100644 index 0000000000000000000000000000000000000000..c142fe0208ea784679122ba04997d3432b05efcc --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp32.cu @@ -0,0 +1,10 @@ +/****************************************************************************** + * Copyright (c) 2023, Tri Dao. + ******************************************************************************/ + +// Split into multiple files to compile in paralell + +#include "selective_scan_fwd_kernel.cuh" + +template void selective_scan_fwd_cuda(SSMParamsBase ¶ms, cudaStream_t stream); +template void selective_scan_fwd_cuda(SSMParamsBase ¶ms, cudaStream_t stream); \ No newline at end of file diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_kernel.cuh b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_kernel.cuh new file mode 100644 index 0000000000000000000000000000000000000000..440a209108bfe120c73d123bbf0b82ccf43a5638 --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_kernel.cuh @@ -0,0 +1,345 @@ +/****************************************************************************** + * Copyright (c) 2023, Tri Dao. + ******************************************************************************/ + +#pragma once + +#include +#include +#include // For C10_CUDA_CHECK and C10_CUDA_KERNEL_LAUNCH_CHECK + +#include +#include +#include + +#include "selective_scan.h" +#include "selective_scan_common.h" +#include "static_switch.h" + +template +struct Selective_Scan_fwd_kernel_traits { + static_assert(kNItems_ % 4 == 0); + using input_t = input_t_; + using weight_t = weight_t_; + static constexpr int kNThreads = kNThreads_; + // Setting MinBlocksPerMP to be 3 (instead of 2) for 128 threads improves occupancy. + static constexpr int kMinBlocks = kNThreads < 128 ? 5 : 3; + static constexpr int kNItems = kNItems_; + static constexpr int kNRows = kNRows_; + static constexpr int kNBytes = sizeof(input_t); + static_assert(kNBytes == 2 || kNBytes == 4); + static constexpr int kNElts = kNBytes == 4 ? 4 : std::min(8, kNItems); + static_assert(kNItems % kNElts == 0); + static constexpr int kNLoads = kNItems / kNElts; + static constexpr bool kIsComplex = std::is_same_v; + static constexpr bool kIsEvenLen = kIsEvenLen_; + static constexpr bool kIsVariableB = kIsVariableB_; + static constexpr bool kIsVariableC = kIsVariableC_; + static constexpr bool kHasZ = kHasZ_; + + static constexpr bool kDirectIO = kIsEvenLen && kNLoads == 1; + + using vec_t = typename BytesToType::Type; + using scan_t = std::conditional_t; + using BlockLoadT = cub::BlockLoad; + using BlockLoadVecT = cub::BlockLoad; + using BlockLoadWeightT = cub::BlockLoad; + using BlockLoadWeightVecT = cub::BlockLoad; + using BlockStoreT = cub::BlockStore; + using BlockStoreVecT = cub::BlockStore; + // using BlockScanT = cub::BlockScan; + // using BlockScanT = cub::BlockScan; + using BlockScanT = cub::BlockScan; + static constexpr int kSmemIOSize = std::max({sizeof(typename BlockLoadT::TempStorage), + sizeof(typename BlockLoadVecT::TempStorage), + (int(kIsVariableB) + int(kIsVariableC)) * sizeof(typename BlockLoadWeightT::TempStorage), + (int(kIsVariableB) + int(kIsVariableC)) * sizeof(typename BlockLoadWeightVecT::TempStorage), + sizeof(typename BlockStoreT::TempStorage), + sizeof(typename BlockStoreVecT::TempStorage)}); + static constexpr int kSmemSize = kSmemIOSize + sizeof(typename BlockScanT::TempStorage); +}; + +template +__global__ __launch_bounds__(Ktraits::kNThreads, Ktraits::kMinBlocks) +void selective_scan_fwd_kernel(SSMParamsBase params) { + constexpr bool kIsComplex = Ktraits::kIsComplex; + constexpr bool kIsVariableB = Ktraits::kIsVariableB; + constexpr bool kIsVariableC = Ktraits::kIsVariableC; + constexpr bool kHasZ = Ktraits::kHasZ; + constexpr int kNThreads = Ktraits::kNThreads; + constexpr int kNItems = Ktraits::kNItems; + constexpr int kNRows = Ktraits::kNRows; + constexpr bool kDirectIO = Ktraits::kDirectIO; + using input_t = typename Ktraits::input_t; + using weight_t = typename Ktraits::weight_t; + using scan_t = typename Ktraits::scan_t; + + // Shared memory. + extern __shared__ char smem_[]; + // cast to lvalue reference of expected type + // char *smem_loadstorescan = smem_ + 2 * MAX_DSTATE * sizeof(weight_t); + // auto& smem_load = reinterpret_cast(smem_ + 2 * MAX_DSTATE * sizeof(weight_t)); + // auto& smem_load = reinterpret_cast(smem_loadstorescan); + auto& smem_load = reinterpret_cast(smem_); + auto& smem_load_weight = reinterpret_cast(smem_); + auto& smem_load_weight1 = *reinterpret_cast(smem_ + sizeof(typename Ktraits::BlockLoadWeightT::TempStorage)); + auto& smem_store = reinterpret_cast(smem_); + auto& smem_scan = *reinterpret_cast(smem_ + Ktraits::kSmemIOSize); + // weight_t *smem_a = reinterpret_cast(smem_ + smem_loadstorescan_size); + // weight_t *smem_bc = reinterpret_cast(smem_a + MAX_DSTATE); + scan_t *smem_running_prefix = reinterpret_cast(smem_ + Ktraits::kSmemSize); + + const int batch_id = blockIdx.x; + const int dim_id = blockIdx.y; + const int group_id = dim_id / (params.dim_ngroups_ratio); + input_t *u = reinterpret_cast(params.u_ptr) + batch_id * params.u_batch_stride + + dim_id * kNRows * params.u_d_stride; + input_t *delta = reinterpret_cast(params.delta_ptr) + batch_id * params.delta_batch_stride + + dim_id * kNRows * params.delta_d_stride; + weight_t *A = reinterpret_cast(params.A_ptr) + dim_id * kNRows * params.A_d_stride; + weight_t *B = reinterpret_cast(params.B_ptr) + dim_id * kNRows * params.B_d_stride; + input_t *Bvar = reinterpret_cast(params.B_ptr) + batch_id * params.B_batch_stride + group_id * params.B_group_stride; + weight_t *C = reinterpret_cast(params.C_ptr) + dim_id * kNRows * params.C_d_stride; + input_t *Cvar = reinterpret_cast(params.C_ptr) + batch_id * params.C_batch_stride + group_id * params.C_group_stride; + scan_t *x = reinterpret_cast(params.x_ptr) + (batch_id * params.dim + dim_id * kNRows) * params.n_chunks * params.dstate; + + float D_val[kNRows] = {0}; + if (params.D_ptr != nullptr) { + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + D_val[r] = reinterpret_cast(params.D_ptr)[dim_id * kNRows + r]; + } + } + float delta_bias[kNRows] = {0}; + if (params.delta_bias_ptr != nullptr) { + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + delta_bias[r] = reinterpret_cast(params.delta_bias_ptr)[dim_id * kNRows + r]; + } + } + + // for (int state_idx = threadIdx.x; state_idx < params.dstate; state_idx += blockDim.x) { + // smem_a[state_idx] = A[state_idx * params.A_dstate_stride]; + // smem_bc[state_idx] = B[state_idx * params.B_dstate_stride] * C[state_idx * params.C_dstate_stride]; + // } + + constexpr int kChunkSize = kNThreads * kNItems; + for (int chunk = 0; chunk < params.n_chunks; ++chunk) { + input_t u_vals[kNRows][kNItems], delta_vals_load[kNRows][kNItems]; + __syncthreads(); + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + if constexpr (!kDirectIO) { + if (r > 0) { __syncthreads(); } + } + load_input(u + r * params.u_d_stride, u_vals[r], smem_load, params.seqlen - chunk * kChunkSize); + if constexpr (!kDirectIO) { __syncthreads(); } + load_input(delta + r * params.delta_d_stride, delta_vals_load[r], smem_load, params.seqlen - chunk * kChunkSize); + } + u += kChunkSize; + delta += kChunkSize; + + float delta_vals[kNRows][kNItems], delta_u_vals[kNRows][kNItems], out_vals[kNRows][kNItems]; + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + #pragma unroll + for (int i = 0; i < kNItems; ++i) { + float u_val = float(u_vals[r][i]); + delta_vals[r][i] = float(delta_vals_load[r][i]) + delta_bias[r]; + if (params.delta_softplus) { + delta_vals[r][i] = delta_vals[r][i] <= 20.f ? log1pf(expf(delta_vals[r][i])) : delta_vals[r][i]; + } + delta_u_vals[r][i] = delta_vals[r][i] * u_val; + out_vals[r][i] = D_val[r] * u_val; + } + } + + __syncthreads(); + for (int state_idx = 0; state_idx < params.dstate; ++state_idx) { + weight_t A_val[kNRows]; + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + A_val[r] = A[state_idx * params.A_dstate_stride + r * params.A_d_stride]; + // Multiply the real part of A with LOG2E so we can use exp2f instead of expf. + constexpr float kLog2e = M_LOG2E; + if constexpr (!kIsComplex) { + A_val[r] *= kLog2e; + } else { + A_val[r].real_ *= kLog2e; + } + } + // This variable holds B * C if both B and C are constant across seqlen. If only B varies + // across seqlen, this holds C. If only C varies across seqlen, this holds B. + // If both B and C vary, this is unused. + weight_t BC_val[kNRows]; + weight_t B_vals[kNItems], C_vals[kNItems]; + if constexpr (kIsVariableB) { + load_weight(Bvar + state_idx * params.B_dstate_stride, B_vals, + smem_load_weight, (params.seqlen - chunk * kChunkSize) * (!kIsComplex ? 1 : 2)); + if constexpr (!kIsVariableC) { + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + BC_val[r] = C[state_idx * params.C_dstate_stride + r * params.C_d_stride]; + } + } + } + if constexpr (kIsVariableC) { + auto &smem_load_weight_C = !kIsVariableB ? smem_load_weight : smem_load_weight1; + load_weight(Cvar + state_idx * params.C_dstate_stride, C_vals, + smem_load_weight_C, (params.seqlen - chunk * kChunkSize) * (!kIsComplex ? 1 : 2)); + if constexpr (!kIsVariableB) { + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + BC_val[r] = B[state_idx * params.B_dstate_stride + r * params.B_d_stride]; + } + } + } + if constexpr (!kIsVariableB && !kIsVariableC) { + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + BC_val[r] = B[state_idx * params.B_dstate_stride + r * params.B_d_stride] * C[state_idx * params.C_dstate_stride + r * params.C_d_stride]; + } + } + + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + if (r > 0) { __syncthreads(); } // Scan could be using the same smem + scan_t thread_data[kNItems]; + #pragma unroll + for (int i = 0; i < kNItems; ++i) { + if constexpr (!kIsComplex) { + thread_data[i] = make_float2(exp2f(delta_vals[r][i] * A_val[r]), + !kIsVariableB ? delta_u_vals[r][i] : B_vals[i] * delta_u_vals[r][i]); + if constexpr (!Ktraits::kIsEvenLen) { // So that the last state is correct + if (threadIdx.x * kNItems + i >= params.seqlen - chunk * kChunkSize) { + thread_data[i] = make_float2(1.f, 0.f); + } + } + } else { + // Pytorch's implementation of complex exp (which calls thrust) is very slow + complex_t delta_a_exp = cexp2f(delta_vals[r][i] * A_val[r]); + weight_t B_delta_u_val = !kIsVariableB ? delta_u_vals[r][i] : B_vals[i] * delta_u_vals[r][i]; + thread_data[i] = make_float4(delta_a_exp.real_, delta_a_exp.imag_, B_delta_u_val.real_, B_delta_u_val.imag_); + if constexpr (!Ktraits::kIsEvenLen) { // So that the last state is correct + if (threadIdx.x * kNItems + i >= params.seqlen - chunk * kChunkSize) { + thread_data[i] = make_float4(1.f, 0.f, 0.f, 0.f); + } + } + } + } + // Initialize running total + scan_t running_prefix; + if constexpr (!kIsComplex) { + // If we use WARP_SCAN then all lane 0 of all warps (not just thread 0) needs to read + running_prefix = chunk > 0 && threadIdx.x % 32 == 0 ? smem_running_prefix[state_idx + r * MAX_DSTATE] : make_float2(1.f, 0.f); + // running_prefix = chunk > 0 && threadIdx.x == 0 ? smem_running_prefix[state_idx] : make_float2(1.f, 0.f); + } else { + running_prefix = chunk > 0 && threadIdx.x % 32 == 0 ? smem_running_prefix[state_idx + r * MAX_DSTATE] : make_float4(1.f, 0.f, 0.f, 0.f); + // running_prefix = chunk > 0 && threadIdx.x == 0 ? smem_running_prefix[state_idx] : make_float4(1.f, 0.f, 0.f, 0.f); + } + SSMScanPrefixCallbackOp prefix_op(running_prefix); + Ktraits::BlockScanT(smem_scan).InclusiveScan( + thread_data, thread_data, SSMScanOp(), prefix_op + ); + // There's a syncthreads in the scan op, so we don't need to sync here. + // Unless there's only 1 warp, but then it's the same thread (0) reading and writing. + if (threadIdx.x == 0) { + smem_running_prefix[state_idx] = prefix_op.running_prefix; + x[(r * params.n_chunks + chunk) * params.dstate + state_idx] = prefix_op.running_prefix; + } + #pragma unroll + for (int i = 0; i < kNItems; ++i) { + const weight_t C_val = !kIsVariableC + ? BC_val[r] + : (!kIsVariableB ? BC_val[r] * C_vals[i] : C_vals[i]); + if constexpr (!kIsComplex) { + out_vals[r][i] += thread_data[i].y * C_val; + } else { + out_vals[r][i] += (complex_t(thread_data[i].z, thread_data[i].w) * C_val).real_ * 2; + } + } + } + } + + input_t *out = reinterpret_cast(params.out_ptr) + batch_id * params.out_batch_stride + + dim_id * kNRows * params.out_d_stride + chunk * kChunkSize; + __syncthreads(); + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + if constexpr (!kDirectIO) { + if (r > 0) { __syncthreads(); } + } + store_output(out + r * params.out_d_stride, out_vals[r], smem_store, params.seqlen - chunk * kChunkSize); + } + + if constexpr (kHasZ) { + input_t *z = reinterpret_cast(params.z_ptr) + batch_id * params.z_batch_stride + + dim_id * kNRows * params.z_d_stride + chunk * kChunkSize; + input_t *out_z = reinterpret_cast(params.out_z_ptr) + batch_id * params.out_z_batch_stride + + dim_id * kNRows * params.out_z_d_stride + chunk * kChunkSize; + #pragma unroll + for (int r = 0; r < kNRows; ++r) { + input_t z_vals[kNItems]; + __syncthreads(); + load_input(z + r * params.z_d_stride, z_vals, smem_load, params.seqlen - chunk * kChunkSize); + #pragma unroll + for (int i = 0; i < kNItems; ++i) { + float z_val = z_vals[i]; + out_vals[r][i] *= z_val / (1 + expf(-z_val)); + } + __syncthreads(); + store_output(out_z + r * params.out_z_d_stride, out_vals[r], smem_store, params.seqlen - chunk * kChunkSize); + } + } + + Bvar += kChunkSize * (!kIsComplex ? 1 : 2); + Cvar += kChunkSize * (!kIsComplex ? 1 : 2); + } +} + +template +void selective_scan_fwd_launch(SSMParamsBase ¶ms, cudaStream_t stream) { + // Only kNRows == 1 is tested for now, which ofc doesn't differ from previously when we had each block + // processing 1 row. + constexpr int kNRows = 1; + BOOL_SWITCH(params.seqlen % (kNThreads * kNItems) == 0, kIsEvenLen, [&] { + BOOL_SWITCH(params.is_variable_B, kIsVariableB, [&] { + BOOL_SWITCH(params.is_variable_C, kIsVariableC, [&] { + BOOL_SWITCH(params.z_ptr != nullptr , kHasZ, [&] { + using Ktraits = Selective_Scan_fwd_kernel_traits; + // constexpr int kSmemSize = Ktraits::kSmemSize; + constexpr int kSmemSize = Ktraits::kSmemSize + kNRows * MAX_DSTATE * sizeof(typename Ktraits::scan_t); + // printf("smem_size = %d\n", kSmemSize); + dim3 grid(params.batch, params.dim / kNRows); + auto kernel = &selective_scan_fwd_kernel; + if (kSmemSize >= 48 * 1024) { + C10_CUDA_CHECK(cudaFuncSetAttribute( + kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kSmemSize)); + } + kernel<<>>(params); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + }); + }); + }); +} + +template +void selective_scan_fwd_cuda(SSMParamsBase ¶ms, cudaStream_t stream) { + if (params.seqlen <= 128) { + selective_scan_fwd_launch<32, 4, input_t, weight_t>(params, stream); + } else if (params.seqlen <= 256) { + selective_scan_fwd_launch<32, 8, input_t, weight_t>(params, stream); + } else if (params.seqlen <= 512) { + selective_scan_fwd_launch<32, 16, input_t, weight_t>(params, stream); + } else if (params.seqlen <= 1024) { + selective_scan_fwd_launch<64, 16, input_t, weight_t>(params, stream); + } else { + selective_scan_fwd_launch<128, 16, input_t, weight_t>(params, stream); + } +} diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/static_switch.h b/source_code/SegMamba/mamba/csrc/selective_scan/static_switch.h new file mode 100644 index 0000000000000000000000000000000000000000..7920ac045d0a2a1f4c4159ee3eebe51fe1e2c203 --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/static_switch.h @@ -0,0 +1,25 @@ +// Inspired by https://github.com/NVIDIA/DALI/blob/main/include/dali/core/static_switch.h +// and https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Dispatch.h + +#pragma once + +/// @param COND - a boolean expression to switch by +/// @param CONST_NAME - a name given for the constexpr bool variable. +/// @param ... - code to execute for true and false +/// +/// Usage: +/// ``` +/// BOOL_SWITCH(flag, BoolConst, [&] { +/// some_function(...); +/// }); +/// ``` +#define BOOL_SWITCH(COND, CONST_NAME, ...) \ + [&] { \ + if (COND) { \ + constexpr bool CONST_NAME = true; \ + return __VA_ARGS__(); \ + } else { \ + constexpr bool CONST_NAME = false; \ + return __VA_ARGS__(); \ + } \ + }() diff --git a/source_code/SegMamba/mamba/csrc/selective_scan/uninitialized_copy.cuh b/source_code/SegMamba/mamba/csrc/selective_scan/uninitialized_copy.cuh new file mode 100644 index 0000000000000000000000000000000000000000..630622dddcc9041737307810000584a843a01764 --- /dev/null +++ b/source_code/SegMamba/mamba/csrc/selective_scan/uninitialized_copy.cuh @@ -0,0 +1,69 @@ +/****************************************************************************** + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include + +#include + + +namespace detail +{ + +#if defined(_NVHPC_CUDA) +template +__host__ __device__ void uninitialized_copy(T *ptr, U &&val) +{ + // NVBug 3384810 + new (ptr) T(::cuda::std::forward(val)); +} +#else +template ::value, + int + >::type = 0> +__host__ __device__ void uninitialized_copy(T *ptr, U &&val) +{ + *ptr = ::cuda::std::forward(val); +} + +template ::value, + int + >::type = 0> +__host__ __device__ void uninitialized_copy(T *ptr, U &&val) +{ + new (ptr) T(::cuda::std::forward(val)); +} +#endif + +} // namespace detail diff --git a/source_code/SegMamba/mamba/mamba_ssm/models/mixer_seq_simple.py b/source_code/SegMamba/mamba/mamba_ssm/models/mixer_seq_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..383f773f1f700cd53176e51327a5d8dc58158da0 --- /dev/null +++ b/source_code/SegMamba/mamba/mamba_ssm/models/mixer_seq_simple.py @@ -0,0 +1,233 @@ +# Copyright (c) 2023, Albert Gu, Tri Dao. + +import math +from functools import partial + +from collections import namedtuple + +import torch +import torch.nn as nn + +from mamba_ssm.modules.mamba_simple import Mamba, Block +from mamba_ssm.utils.generation import GenerationMixin +from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf + +try: + from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn +except ImportError: + RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None + + +def create_block( + d_model, + ssm_cfg=None, + norm_epsilon=1e-5, + rms_norm=False, + residual_in_fp32=False, + fused_add_norm=False, + layer_idx=None, + device=None, + dtype=None, +): + if ssm_cfg is None: + ssm_cfg = {} + factory_kwargs = {"device": device, "dtype": dtype} + mixer_cls = partial(Mamba, layer_idx=layer_idx, **ssm_cfg, **factory_kwargs) + norm_cls = partial( + nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs + ) + block = Block( + d_model, + mixer_cls, + norm_cls=norm_cls, + fused_add_norm=fused_add_norm, + residual_in_fp32=residual_in_fp32, + ) + block.layer_idx = layer_idx + return block + + +# https://github.com/huggingface/transformers/blob/c28d04e9e252a1a099944e325685f14d242ecdcd/src/transformers/models/gpt2/modeling_gpt2.py#L454 +def _init_weights( + module, + n_layer, + initializer_range=0.02, # Now only used for embedding layer. + rescale_prenorm_residual=True, + n_residuals_per_layer=1, # Change to 2 if we have MLP +): + if isinstance(module, nn.Linear): + if module.bias is not None: + if not getattr(module.bias, "_no_reinit", False): + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, std=initializer_range) + + if rescale_prenorm_residual: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + for name, p in module.named_parameters(): + if name in ["out_proj.weight", "fc2.weight"]: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) + # We need to reinit p since this code could be called multiple times + # Having just p *= scale would repeatedly scale it down + nn.init.kaiming_uniform_(p, a=math.sqrt(5)) + with torch.no_grad(): + p /= math.sqrt(n_residuals_per_layer * n_layer) + + +class MixerModel(nn.Module): + def __init__( + self, + d_model: int, + n_layer: int, + vocab_size: int, + ssm_cfg=None, + norm_epsilon: float = 1e-5, + rms_norm: bool = False, + initializer_cfg=None, + fused_add_norm=False, + residual_in_fp32=False, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.residual_in_fp32 = residual_in_fp32 + + self.embedding = nn.Embedding(vocab_size, d_model, **factory_kwargs) + + # We change the order of residual and layer norm: + # Instead of LN -> Attn / MLP -> Add, we do: + # Add -> LN -> Attn / MLP / Mixer, returning both the residual branch (output of Add) and + # the main branch (output of MLP / Mixer). The model definition is unchanged. + # This is for performance reason: we can fuse add + layer_norm. + self.fused_add_norm = fused_add_norm + if self.fused_add_norm: + if layer_norm_fn is None or rms_norm_fn is None: + raise ImportError("Failed to import Triton LayerNorm / RMSNorm kernels") + + self.layers = nn.ModuleList( + [ + create_block( + d_model, + ssm_cfg=ssm_cfg, + norm_epsilon=norm_epsilon, + rms_norm=rms_norm, + residual_in_fp32=residual_in_fp32, + fused_add_norm=fused_add_norm, + layer_idx=i, + **factory_kwargs, + ) + for i in range(n_layer) + ] + ) + + self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)( + d_model, eps=norm_epsilon, **factory_kwargs + ) + + self.apply( + partial( + _init_weights, + n_layer=n_layer, + **(initializer_cfg if initializer_cfg is not None else {}), + ) + ) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return { + i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + for i, layer in enumerate(self.layers) + } + + def forward(self, input_ids, inference_params=None): + hidden_states = self.embedding(input_ids) + residual = None + for layer in self.layers: + hidden_states, residual = layer( + hidden_states, residual, inference_params=inference_params + ) + if not self.fused_add_norm: + residual = (hidden_states + residual) if residual is not None else hidden_states + hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype)) + else: + # Set prenorm=False here since we don't need the residual + fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn + hidden_states = fused_add_norm_fn( + hidden_states, + self.norm_f.weight, + self.norm_f.bias, + eps=self.norm_f.eps, + residual=residual, + prenorm=False, + residual_in_fp32=self.residual_in_fp32, + ) + return hidden_states + + +class MambaLMHeadModel(nn.Module, GenerationMixin): + + def __init__( + self, + d_model: int, + n_layer: int, + vocab_size: int, + initializer_cfg=None, + pad_vocab_size_multiple: int = 1, + device=None, + dtype=None, + **backbone_kwargs, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + if vocab_size % pad_vocab_size_multiple != 0: + vocab_size += pad_vocab_size_multiple - (vocab_size % pad_vocab_size_multiple) + self.backbone = MixerModel( + d_model=d_model, + n_layer=n_layer, + vocab_size=vocab_size, + initializer_cfg=initializer_cfg, + **backbone_kwargs, + **factory_kwargs, + ) + self.lm_head = nn.Linear(d_model, vocab_size, bias=False, **factory_kwargs) + + # Initialize weights and apply final processing + self.apply( + partial( + _init_weights, + n_layer=n_layer, + **(initializer_cfg if initializer_cfg is not None else {}), + ) + ) + self.tie_weights() + + def tie_weights(self): + self.lm_head.weight = self.backbone.embedding.weight + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return self.backbone.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + + def forward(self, input_ids, position_ids=None, inference_params=None, num_last_tokens=0): + """ + "position_ids" is just to be compatible with Transformer generation. We don't use it. + num_last_tokens: if > 0, only return the logits for the last n tokens + """ + hidden_states = self.backbone(input_ids, inference_params=inference_params) + if num_last_tokens > 0: + hidden_states = hidden_states[:, -num_last_tokens:] + lm_logits = self.lm_head(hidden_states) + CausalLMOutput = namedtuple("CausalLMOutput", ["logits"]) + return CausalLMOutput(logits=lm_logits) + + @classmethod + def from_pretrained(cls, pretrained_model_name, device=None, dtype=None, **kwargs): + config = load_config_hf(pretrained_model_name) + model = cls(**config, device=device, dtype=dtype, **kwargs) + model.load_state_dict(load_state_dict_hf(pretrained_model_name, device=device, dtype=dtype)) + return model diff --git a/source_code/SegMamba/mamba/mamba_ssm/ops/triton/layernorm.py b/source_code/SegMamba/mamba/mamba_ssm/ops/triton/layernorm.py new file mode 100644 index 0000000000000000000000000000000000000000..8df9d042a34b6584196f218f5ffeeb104799bd5e --- /dev/null +++ b/source_code/SegMamba/mamba/mamba_ssm/ops/triton/layernorm.py @@ -0,0 +1,636 @@ +# Copyright (c) 2023, Tri Dao. +# Implement residual + layer_norm / rms_norm. + +# Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html +# For the backward pass, we keep weight_grad and bias_grad in registers and accumulate. +# This is faster for dimensions up to 8k, but after that it's much slower due to register spilling. +# The models we train have hidden dim up to 8k anyway (e.g. Llama 70B), so this is fine. + +import math + +import torch +import torch.nn.functional as F +from torch.cuda.amp import custom_fwd, custom_bwd + +import triton +import triton.language as tl + + +def layer_norm_ref(x, weight, bias, residual=None, eps=1e-6, prenorm=False, upcast=False): + dtype = x.dtype + if upcast: + weight = weight.float() + bias = bias.float() if bias is not None else None + if upcast: + x = x.float() + residual = residual.float() if residual is not None else residual + if residual is not None: + x = (x + residual).to(x.dtype) + out = F.layer_norm(x.to(weight.dtype), x.shape[-1:], weight=weight, bias=bias, eps=eps).to( + dtype + ) + return out if not prenorm else (out, x) + + +def rms_norm_ref(x, weight, bias, residual=None, eps=1e-6, prenorm=False, upcast=False): + dtype = x.dtype + if upcast: + weight = weight.float() + bias = bias.float() if bias is not None else None + if upcast: + x = x.float() + residual = residual.float() if residual is not None else residual + if residual is not None: + x = (x + residual).to(x.dtype) + rstd = 1 / torch.sqrt((x.square()).mean(dim=-1, keepdim=True) + eps) + out = (x * rstd * weight) + bias if bias is not None else (x * rstd * weight) + out = out.to(dtype) + return out if not prenorm else (out, x) + + +@triton.autotune( + configs=[ + triton.Config({}, num_warps=1), + triton.Config({}, num_warps=2), + triton.Config({}, num_warps=4), + triton.Config({}, num_warps=8), + triton.Config({}, num_warps=16), + triton.Config({}, num_warps=32), + ], + key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS"], +) +# @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None}) +# @triton.heuristics({"HAS_RESIDUAL": lambda args: args["RESIDUAL"] is not None}) +@triton.jit +def _layer_norm_fwd_1pass_kernel( + X, # pointer to the input + Y, # pointer to the output + W, # pointer to the weights + B, # pointer to the biases + RESIDUAL, # pointer to the residual + RESIDUAL_OUT, # pointer to the residual + Mean, # pointer to the mean + Rstd, # pointer to the 1/std + stride_x_row, # how much to increase the pointer when moving by 1 row + stride_y_row, + stride_res_row, + stride_res_out_row, + N, # number of columns in X + eps, # epsilon to avoid division by zero + IS_RMS_NORM: tl.constexpr, + BLOCK_N: tl.constexpr, + HAS_RESIDUAL: tl.constexpr, + STORE_RESIDUAL_OUT: tl.constexpr, + HAS_BIAS: tl.constexpr, +): + # Map the program id to the row of X and Y it should compute. + row = tl.program_id(0) + X += row * stride_x_row + Y += row * stride_y_row + if HAS_RESIDUAL: + RESIDUAL += row * stride_res_row + if STORE_RESIDUAL_OUT: + RESIDUAL_OUT += row * stride_res_out_row + # Compute mean and variance + cols = tl.arange(0, BLOCK_N) + x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32) + if HAS_RESIDUAL: + residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32) + x += residual + if STORE_RESIDUAL_OUT: + tl.store(RESIDUAL_OUT + cols, x, mask=cols < N) + if not IS_RMS_NORM: + mean = tl.sum(x, axis=0) / N + tl.store(Mean + row, mean) + xbar = tl.where(cols < N, x - mean, 0.0) + var = tl.sum(xbar * xbar, axis=0) / N + else: + xbar = tl.where(cols < N, x, 0.0) + var = tl.sum(xbar * xbar, axis=0) / N + rstd = 1 / tl.sqrt(var + eps) + tl.store(Rstd + row, rstd) + # Normalize and apply linear transformation + mask = cols < N + w = tl.load(W + cols, mask=mask).to(tl.float32) + if HAS_BIAS: + b = tl.load(B + cols, mask=mask).to(tl.float32) + x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd + y = x_hat * w + b if HAS_BIAS else x_hat * w + # Write output + tl.store(Y + cols, y, mask=mask) + + +def _layer_norm_fwd( + x, weight, bias, eps, residual=None, out_dtype=None, residual_dtype=None, is_rms_norm=False +): + if residual is not None: + residual_dtype = residual.dtype + M, N = x.shape + assert x.stride(-1) == 1 + if residual is not None: + assert residual.stride(-1) == 1 + assert residual.shape == (M, N) + assert weight.shape == (N,) + assert weight.stride(-1) == 1 + if bias is not None: + assert bias.stride(-1) == 1 + assert bias.shape == (N,) + # allocate output + y = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype) + assert y.stride(-1) == 1 + if residual is not None or (residual_dtype is not None and residual_dtype != x.dtype): + residual_out = torch.empty(M, N, device=x.device, dtype=residual_dtype) + assert residual_out.stride(-1) == 1 + else: + residual_out = None + mean = torch.empty((M,), dtype=torch.float32, device="cuda") if not is_rms_norm else None + rstd = torch.empty((M,), dtype=torch.float32, device="cuda") + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_N: + raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.") + # heuristics for number of warps + with torch.cuda.device(x.device.index): + _layer_norm_fwd_1pass_kernel[(M,)]( + x, + y, + weight, + bias, + residual, + residual_out, + mean, + rstd, + x.stride(0), + y.stride(0), + residual.stride(0) if residual is not None else 0, + residual_out.stride(0) if residual_out is not None else 0, + N, + eps, + is_rms_norm, + BLOCK_N, + residual is not None, + residual_out is not None, + bias is not None, + ) + # residual_out is None if residual is None and residual_dtype == input_dtype + return y, mean, rstd, residual_out if residual_out is not None else x + + +@triton.autotune( + configs=[ + triton.Config({}, num_warps=1), + triton.Config({}, num_warps=2), + triton.Config({}, num_warps=4), + triton.Config({}, num_warps=8), + triton.Config({}, num_warps=16), + triton.Config({}, num_warps=32), + ], + key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS"], +) +# @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None}) +# @triton.heuristics({"HAS_DRESIDUAL": lambda args: args["DRESIDUAL"] is not None}) +# @triton.heuristics({"STORE_DRESIDUAL": lambda args: args["DRESIDUAL_IN"] is not None}) +@triton.heuristics({"RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None}) +@triton.jit +def _layer_norm_bwd_kernel( + X, # pointer to the input + W, # pointer to the weights + B, # pointer to the biases + Y, # pointer to the output to be recomputed + DY, # pointer to the output gradient + DX, # pointer to the input gradient + DW, # pointer to the partial sum of weights gradient + DB, # pointer to the partial sum of biases gradient + DRESIDUAL, + DRESIDUAL_IN, + Mean, # pointer to the mean + Rstd, # pointer to the 1/std + stride_x_row, # how much to increase the pointer when moving by 1 row + stride_y_row, + stride_dy_row, + stride_dx_row, + stride_dres_row, + stride_dres_in_row, + M, # number of rows in X + N, # number of columns in X + eps, # epsilon to avoid division by zero + rows_per_program, + IS_RMS_NORM: tl.constexpr, + BLOCK_N: tl.constexpr, + HAS_DRESIDUAL: tl.constexpr, + STORE_DRESIDUAL: tl.constexpr, + HAS_BIAS: tl.constexpr, + RECOMPUTE_OUTPUT: tl.constexpr, +): + # Map the program id to the elements of X, DX, and DY it should compute. + row_block_id = tl.program_id(0) + row_start = row_block_id * rows_per_program + cols = tl.arange(0, BLOCK_N) + mask = cols < N + X += row_start * stride_x_row + if HAS_DRESIDUAL: + DRESIDUAL += row_start * stride_dres_row + if STORE_DRESIDUAL: + DRESIDUAL_IN += row_start * stride_dres_in_row + DY += row_start * stride_dy_row + DX += row_start * stride_dx_row + if RECOMPUTE_OUTPUT: + Y += row_start * stride_y_row + w = tl.load(W + cols, mask=mask).to(tl.float32) + if RECOMPUTE_OUTPUT and HAS_BIAS: + b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32) + dw = tl.zeros((BLOCK_N,), dtype=tl.float32) + if HAS_BIAS: + db = tl.zeros((BLOCK_N,), dtype=tl.float32) + row_end = min((row_block_id + 1) * rows_per_program, M) + for row in range(row_start, row_end): + # Load data to SRAM + x = tl.load(X + cols, mask=mask, other=0).to(tl.float32) + dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32) + if not IS_RMS_NORM: + mean = tl.load(Mean + row) + rstd = tl.load(Rstd + row) + # Compute dx + xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd + xhat = tl.where(mask, xhat, 0.0) + if RECOMPUTE_OUTPUT: + y = xhat * w + b if HAS_BIAS else xhat * w + tl.store(Y + cols, y, mask=mask) + wdy = w * dy + dw += dy * xhat + if HAS_BIAS: + db += dy + if not IS_RMS_NORM: + c1 = tl.sum(xhat * wdy, axis=0) / N + c2 = tl.sum(wdy, axis=0) / N + dx = (wdy - (xhat * c1 + c2)) * rstd + else: + c1 = tl.sum(xhat * wdy, axis=0) / N + dx = (wdy - xhat * c1) * rstd + if HAS_DRESIDUAL: + dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32) + dx += dres + # Write dx + if STORE_DRESIDUAL: + tl.store(DRESIDUAL_IN + cols, dx, mask=mask) + tl.store(DX + cols, dx, mask=mask) + + X += stride_x_row + if HAS_DRESIDUAL: + DRESIDUAL += stride_dres_row + if STORE_DRESIDUAL: + DRESIDUAL_IN += stride_dres_in_row + if RECOMPUTE_OUTPUT: + Y += stride_y_row + DY += stride_dy_row + DX += stride_dx_row + tl.store(DW + row_block_id * N + cols, dw, mask=mask) + if HAS_BIAS: + tl.store(DB + row_block_id * N + cols, db, mask=mask) + + +def _layer_norm_bwd( + dy, + x, + weight, + bias, + eps, + mean, + rstd, + dresidual=None, + has_residual=False, + is_rms_norm=False, + x_dtype=None, + recompute_output=False, +): + M, N = x.shape + assert x.stride(-1) == 1 + assert dy.stride(-1) == 1 + assert dy.shape == (M, N) + if dresidual is not None: + assert dresidual.stride(-1) == 1 + assert dresidual.shape == (M, N) + assert weight.shape == (N,) + assert weight.stride(-1) == 1 + if bias is not None: + assert bias.stride(-1) == 1 + assert bias.shape == (N,) + # allocate output + dx = ( + torch.empty_like(x) + if x_dtype is None + else torch.empty(M, N, dtype=x_dtype, device=x.device) + ) + dresidual_in = torch.empty_like(x) if has_residual and dx.dtype != x.dtype else None + y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None + + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_N: + raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.") + sm_count = torch.cuda.get_device_properties(x.device).multi_processor_count + _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device) + _db = ( + torch.empty((sm_count, N), dtype=torch.float32, device=bias.device) + if bias is not None + else None + ) + rows_per_program = math.ceil(M / sm_count) + grid = (sm_count,) + with torch.cuda.device(x.device.index): + _layer_norm_bwd_kernel[grid]( + x, + weight, + bias, + y, + dy, + dx, + _dw, + _db, + dresidual, + dresidual_in, + mean, + rstd, + x.stride(0), + 0 if not recompute_output else y.stride(0), + dy.stride(0), + dx.stride(0), + dresidual.stride(0) if dresidual is not None else 0, + dresidual_in.stride(0) if dresidual_in is not None else 0, + M, + N, + eps, + rows_per_program, + is_rms_norm, + BLOCK_N, + dresidual is not None, + dresidual_in is not None, + bias is not None, + ) + dw = _dw.sum(0).to(weight.dtype) + db = _db.sum(0).to(bias.dtype) if bias is not None else None + # Don't need to compute dresidual_in separately in this case + if has_residual and dx.dtype == x.dtype: + dresidual_in = dx + return (dx, dw, db, dresidual_in) if not recompute_output else (dx, dw, db, dresidual_in, y) + + +class LayerNormFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x, + weight, + bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, + ): + x_shape_og = x.shape + # reshape input data into 2D tensor + x = x.reshape(-1, x.shape[-1]) + if x.stride(-1) != 1: + x = x.contiguous() + if residual is not None: + assert residual.shape == x_shape_og + residual = residual.reshape(-1, residual.shape[-1]) + if residual.stride(-1) != 1: + residual = residual.contiguous() + weight = weight.contiguous() + if bias is not None: + bias = bias.contiguous() + residual_dtype = ( + residual.dtype + if residual is not None + else (torch.float32 if residual_in_fp32 else None) + ) + y, mean, rstd, residual_out = _layer_norm_fwd( + x, weight, bias, eps, residual, residual_dtype=residual_dtype, is_rms_norm=is_rms_norm + ) + ctx.save_for_backward(residual_out, weight, bias, mean, rstd) + ctx.x_shape_og = x_shape_og + ctx.eps = eps + ctx.is_rms_norm = is_rms_norm + ctx.has_residual = residual is not None + ctx.prenorm = prenorm + ctx.x_dtype = x.dtype + y = y.reshape(x_shape_og) + return y if not prenorm else (y, residual_out.reshape(x_shape_og)) + + @staticmethod + def backward(ctx, dy, *args): + x, weight, bias, mean, rstd = ctx.saved_tensors + dy = dy.reshape(-1, dy.shape[-1]) + if dy.stride(-1) != 1: + dy = dy.contiguous() + assert dy.shape == x.shape + if ctx.prenorm: + dresidual = args[0] + dresidual = dresidual.reshape(-1, dresidual.shape[-1]) + if dresidual.stride(-1) != 1: + dresidual = dresidual.contiguous() + assert dresidual.shape == x.shape + else: + dresidual = None + dx, dw, db, dresidual_in = _layer_norm_bwd( + dy, + x, + weight, + bias, + ctx.eps, + mean, + rstd, + dresidual, + ctx.has_residual, + ctx.is_rms_norm, + x_dtype=ctx.x_dtype, + ) + return ( + dx.reshape(ctx.x_shape_og), + dw, + db, + dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None, + None, + None, + None, + None, + ) + + +def layer_norm_fn( + x, + weight, + bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, +): + return LayerNormFn.apply(x, weight, bias, residual, eps, prenorm, residual_in_fp32, is_rms_norm) + + +def rms_norm_fn(x, weight, bias, residual=None, prenorm=False, residual_in_fp32=False, eps=1e-6): + return LayerNormFn.apply(x, weight, bias, residual, eps, prenorm, residual_in_fp32, True) + + +class RMSNorm(torch.nn.Module): + def __init__(self, hidden_size, eps=1e-5, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.eps = eps + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.register_parameter("bias", None) + self.reset_parameters() + + def reset_parameters(self): + torch.nn.init.ones_(self.weight) + + def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False): + return rms_norm_fn( + x, + self.weight, + self.bias, + residual=residual, + eps=self.eps, + prenorm=prenorm, + residual_in_fp32=residual_in_fp32, + is_rms_norm=True, + ) + + +class LayerNormLinearFn(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward( + ctx, + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, + ): + x_shape_og = x.shape + # reshape input data into 2D tensor + x = x.reshape(-1, x.shape[-1]) + if x.stride(-1) != 1: + x = x.contiguous() + if residual is not None: + assert residual.shape == x_shape_og + residual = residual.reshape(-1, residual.shape[-1]) + if residual.stride(-1) != 1: + residual = residual.contiguous() + norm_weight = norm_weight.contiguous() + if norm_bias is not None: + norm_bias = norm_bias.contiguous() + residual_dtype = ( + residual.dtype + if residual is not None + else (torch.float32 if residual_in_fp32 else None) + ) + y, mean, rstd, residual_out = _layer_norm_fwd( + x, + norm_weight, + norm_bias, + eps, + residual, + out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype(), + residual_dtype=residual_dtype, + is_rms_norm=is_rms_norm, + ) + y = y.reshape(x_shape_og) + dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else y.dtype + linear_weight = linear_weight.to(dtype) + linear_bias = linear_bias.to(dtype) if linear_bias is not None else None + out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias) + # We don't store y, will be recomputed in the backward pass to save memory + ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd) + ctx.x_shape_og = x_shape_og + ctx.eps = eps + ctx.is_rms_norm = is_rms_norm + ctx.has_residual = residual is not None + ctx.prenorm = prenorm + ctx.x_dtype = x.dtype + ctx.linear_bias_is_none = linear_bias is None + return out if not prenorm else (out, residual_out.reshape(x_shape_og)) + + @staticmethod + @custom_bwd + def backward(ctx, dout, *args): + x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors + dout = dout.reshape(-1, dout.shape[-1]) + dy = F.linear(dout, linear_weight.t()) + dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0) + if dy.stride(-1) != 1: + dy = dy.contiguous() + assert dy.shape == x.shape + if ctx.prenorm: + dresidual = args[0] + dresidual = dresidual.reshape(-1, dresidual.shape[-1]) + if dresidual.stride(-1) != 1: + dresidual = dresidual.contiguous() + assert dresidual.shape == x.shape + else: + dresidual = None + dx, dnorm_weight, dnorm_bias, dresidual_in, y = _layer_norm_bwd( + dy, + x, + norm_weight, + norm_bias, + ctx.eps, + mean, + rstd, + dresidual, + ctx.has_residual, + ctx.is_rms_norm, + x_dtype=ctx.x_dtype, + recompute_output=True, + ) + dlinear_weight = torch.einsum("bo,bi->oi", dout, y) + return ( + dx.reshape(ctx.x_shape_og), + dnorm_weight, + dnorm_bias, + dlinear_weight, + dlinear_bias, + dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None, + None, + None, + None, + None, + ) + + +def layer_norm_linear_fn( + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, +): + return LayerNormLinearFn.apply( + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual, + eps, + prenorm, + residual_in_fp32, + is_rms_norm, + ) diff --git a/source_code/SegMamba/mamba/mamba_ssm/ops/triton/selective_state_update.py b/source_code/SegMamba/mamba/mamba_ssm/ops/triton/selective_state_update.py new file mode 100644 index 0000000000000000000000000000000000000000..fa95de73f173292914c5f00fbe9426937d00e502 --- /dev/null +++ b/source_code/SegMamba/mamba/mamba_ssm/ops/triton/selective_state_update.py @@ -0,0 +1,192 @@ +# Copyright (c) 2023, Tri Dao. + +"""We want triton==2.1.0 for this +""" + +import math +import torch +import torch.nn.functional as F + +import triton +import triton.language as tl + +from einops import rearrange, repeat + + +@triton.heuristics({"HAS_DT_BIAS": lambda args: args["dt_bias_ptr"] is not None}) +@triton.heuristics({"HAS_D": lambda args: args["D_ptr"] is not None}) +@triton.heuristics({"HAS_Z": lambda args: args["z_ptr"] is not None}) +@triton.heuristics({"BLOCK_SIZE_DSTATE": lambda args: triton.next_power_of_2(args["dstate"])}) +@triton.jit +def _selective_scan_update_kernel( + # Pointers to matrices + state_ptr, x_ptr, dt_ptr, dt_bias_ptr, A_ptr, B_ptr, C_ptr, D_ptr, z_ptr, out_ptr, + # Matrix dimensions + batch, dim, dstate, + # Strides + stride_state_batch, stride_state_dim, stride_state_dstate, + stride_x_batch, stride_x_dim, + stride_dt_batch, stride_dt_dim, + stride_dt_bias_dim, + stride_A_dim, stride_A_dstate, + stride_B_batch, stride_B_dstate, + stride_C_batch, stride_C_dstate, + stride_D_dim, + stride_z_batch, stride_z_dim, + stride_out_batch, stride_out_dim, + # Meta-parameters + DT_SOFTPLUS: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + HAS_DT_BIAS: tl.constexpr, + HAS_D: tl.constexpr, + HAS_Z: tl.constexpr, + BLOCK_SIZE_DSTATE: tl.constexpr, +): + pid_m = tl.program_id(axis=0) + pid_b = tl.program_id(axis=1) + state_ptr += pid_b * stride_state_batch + x_ptr += pid_b * stride_x_batch + dt_ptr += pid_b * stride_dt_batch + B_ptr += pid_b * stride_B_batch + C_ptr += pid_b * stride_C_batch + if HAS_Z: + z_ptr += pid_b * stride_z_batch + out_ptr += pid_b * stride_out_batch + + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = tl.arange(0, BLOCK_SIZE_DSTATE) + state_ptrs = state_ptr + (offs_m[:, None] * stride_state_dim + offs_n[None, :] * stride_state_dstate) + x_ptrs = x_ptr + offs_m * stride_x_dim + dt_ptrs = dt_ptr + offs_m * stride_dt_dim + if HAS_DT_BIAS: + dt_bias_ptrs = dt_bias_ptr + offs_m * stride_dt_bias_dim + A_ptrs = A_ptr + (offs_m[:, None] * stride_A_dim + offs_n[None, :] * stride_A_dstate) + B_ptrs = B_ptr + offs_n * stride_B_dstate + C_ptrs = C_ptr + offs_n * stride_C_dstate + if HAS_D: + D_ptrs = D_ptr + offs_m * stride_D_dim + if HAS_Z: + z_ptrs = z_ptr + offs_m * stride_z_dim + out_ptrs = out_ptr + offs_m * stride_out_dim + + state = tl.load(state_ptrs, mask=(offs_m[:, None] < dim) & (offs_n[None, :] < dstate), other=0.0) + x = tl.load(x_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + dt = tl.load(dt_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + if HAS_DT_BIAS: + dt += tl.load(dt_bias_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + if DT_SOFTPLUS: + dt = tl.log(1.0 + tl.exp(dt)) + A = tl.load(A_ptrs, mask=(offs_m[:, None] < dim) & (offs_n[None, :] < dstate), other=0.0).to(tl.float32) + dA = tl.exp(A * dt[:, None]) + B = tl.load(B_ptrs, mask=offs_n < dstate, other=0.0).to(tl.float32) + C = tl.load(C_ptrs, mask=offs_n < dstate, other=0.0).to(tl.float32) + if HAS_D: + D = tl.load(D_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + if HAS_Z: + z = tl.load(z_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + + dB = B[None, :] * dt[:, None] + state = state * dA + dB * x[:, None] + tl.store(state_ptrs, state, mask=(offs_m[:, None] < dim) & (offs_n[None, :] < dstate)) + out = tl.sum(state * C[None, :], axis=1) + if HAS_D: + out += x * D + if HAS_Z: + out *= z * tl.sigmoid(z) + tl.store(out_ptrs, out, mask=offs_m < dim) + + +def selective_state_update(state, x, dt, A, B, C, D=None, z=None, dt_bias=None, dt_softplus=False): + """ + Argument: + state: (batch, dim, dstate) + x: (batch, dim) + dt: (batch, dim) + A: (dim, dstate) + B: (batch, dstate) + C: (batch, dstate) + D: (dim,) + z: (batch, dim) + dt_bias: (dim,) + Return: + out: (batch, dim) + """ + batch, dim, dstate = state.shape + assert x.shape == (batch, dim) + assert dt.shape == x.shape + assert A.shape == (dim, dstate) + assert B.shape == (batch, dstate) + assert C.shape == B.shape + if D is not None: + assert D.shape == (dim,) + if z is not None: + assert z.shape == x.shape + if dt_bias is not None: + assert dt_bias.shape == (dim,) + out = torch.empty_like(x) + grid = lambda META: (triton.cdiv(dim, META['BLOCK_SIZE_M']), batch) + z_strides = ((z.stride(0), z.stride(1)) if z is not None else (0, 0)) + # We don't want autotune since it will overwrite the state + # We instead tune by hand. + BLOCK_SIZE_M, num_warps = ((32, 4) if dstate <= 16 + else ((16, 4) if dstate <= 32 else + ((8, 4) if dstate <= 64 else + ((4, 4) if dstate <= 128 else + ((4, 8)))))) + with torch.cuda.device(x.device.index): + _selective_scan_update_kernel[grid]( + state, x, dt, dt_bias, A, B, C, D, z, out, + batch, dim, dstate, + state.stride(0), state.stride(1), state.stride(2), + x.stride(0), x.stride(1), + dt.stride(0), dt.stride(1), + dt_bias.stride(0) if dt_bias is not None else 0, + A.stride(0), A.stride(1), + B.stride(0), B.stride(1), + C.stride(0), C.stride(1), + D.stride(0) if D is not None else 0, + z_strides[0], z_strides[1], + out.stride(0), out.stride(1), + dt_softplus, + BLOCK_SIZE_M, + num_warps=num_warps, + ) + return out + + +def selective_state_update_ref(state, x, dt, A, B, C, D=None, z=None, dt_bias=None, dt_softplus=False): + """ + Argument: + state: (batch, dim, dstate) + x: (batch, dim) + dt: (batch, dim) + A: (dim, dstate) + B: (batch, dstate) + C: (batch, dstate) + D: (dim,) + z: (batch, dim) + dt_bias: (dim,) + Return: + out: (batch, dim) + """ + batch, dim, dstate = state.shape + assert x.shape == (batch, dim) + assert dt.shape == x.shape + assert A.shape == (dim, dstate) + assert B.shape == (batch, dstate) + assert C.shape == B.shape + if D is not None: + assert D.shape == (dim,) + if z is not None: + assert z.shape == x.shape + if dt_bias is not None: + assert dt_bias.shape == (dim,) + dt = dt + dt_bias + dt = F.softplus(dt) if dt_softplus else dt + dA = torch.exp(rearrange(dt, "b d -> b d 1") * A) # (batch, dim, dstate) + dB = rearrange(dt, "b d -> b d 1") * rearrange(B, "b n -> b 1 n") # (batch, dim, dstate) + state.copy_(state * dA + dB * rearrange(x, "b d -> b d 1")) # (batch, dim, dstate + out = torch.einsum("bdn,bn->bd", state.to(C.dtype), C) + if D is not None: + out += (x * D).to(out.dtype) + return (out if z is None else out * F.silu(z)).to(x.dtype) diff --git a/source_code/SegMamba/mamba/mamba_ssm/utils/generation.py b/source_code/SegMamba/mamba/mamba_ssm/utils/generation.py new file mode 100644 index 0000000000000000000000000000000000000000..9d766b29ac28a388a7d77b22aa2cb1eda733c0f4 --- /dev/null +++ b/source_code/SegMamba/mamba/mamba_ssm/utils/generation.py @@ -0,0 +1,377 @@ +# Copyright (c) 2023, Albert Gu, Tri Dao. +import gc +import time +from collections import namedtuple +from dataclasses import dataclass, field +from functools import partial +from typing import Callable, Optional, Sequence, Union + +import torch +import torch.nn.functional as F +from einops import rearrange, repeat +from torch import Tensor +from torch.profiler import ProfilerActivity, profile, record_function +from transformers.generation import GreedySearchDecoderOnlyOutput, SampleDecoderOnlyOutput + + +@dataclass +class InferenceParams: + """Inference parameters that are passed to the main model in order + to efficienly calculate and store the context during inference.""" + + max_seqlen: int + max_batch_size: int + seqlen_offset: int = 0 + batch_size_offset: int = 0 + key_value_memory_dict: dict = field(default_factory=dict) + lengths_per_sample: Optional[Tensor] = None + + def reset(self, max_seqlen, max_batch_size): + self.max_seqlen = max_seqlen + self.max_batch_size = max_batch_size + self.seqlen_offset = 0 + if self.lengths_per_sample is not None: + self.lengths_per_sample.zero_() + + +# https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/sampling.py +# https://github.com/huggingface/transformers/blob/a44985b41cfa2de48a5e1de7f1f93b7483da25d1/src/transformers/generation/logits_process.py#L231 +def modify_logits_for_top_k_filtering(logits, top_k): + """Set the logits for none top-k values to -inf. Done in-place.""" + indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] + logits.masked_fill_(indices_to_remove, float("-Inf")) + + +# https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/sampling.py +# https://github.com/huggingface/transformers/blob/a44985b41cfa2de48a5e1de7f1f93b7483da25d1/src/transformers/generation/logits_process.py#L170 +def modify_logits_for_top_p_filtering(logits, top_p): + """Set the logits for none top-p values to -inf. Done in-place.""" + if top_p <= 0.0 or top_p >= 1.0: + return + # First sort and calculate cumulative sum of probabilities. + sorted_logits, sorted_indices = torch.sort(logits, descending=False) + cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1) + # Remove tokens with cumulative top_p above the threshold (token with 0 are kept) + sorted_indices_to_remove = cumulative_probs <= (1 - top_p) + # scatter sorted tensors to original indexing + indices_to_remove = sorted_indices_to_remove.scatter( + 1, sorted_indices, sorted_indices_to_remove + ) + logits.masked_fill_(indices_to_remove, float("-inf")) + + +def sample(logits, top_k=1, top_p=0.0, temperature=1.0): + """Sample from top-k logits. + Arguments: + logits: Tensor of shape (batch_size, vocab_size) + """ + if top_k == 1: # Short-circuit for greedy decoding + return logits.argmax(dim=-1) + else: + if top_p > 0.0: + assert top_p <= 1.0, "top-p should be in (0, 1]." + if top_k > 0: + top_k = min(top_k, logits.size(-1)) # Safety check + logits_top, indices = torch.topk(logits, top_k, dim=-1) + if temperature != 1.0: + logits_top /= temperature + modify_logits_for_top_p_filtering(logits_top, top_p) + return indices[ + torch.arange(indices.shape[0], device=indices.device), + torch.multinomial(torch.softmax(logits_top, dim=-1), num_samples=1).squeeze(dim=-1), + ] + else: + # Clone so that when we modify for top_p we don't change the original logits + logits_top = logits / temperature if temperature != 1.0 else logits.clone() + modify_logits_for_top_p_filtering(logits_top, top_p) + return torch.multinomial(torch.softmax(logits_top, dim=-1), num_samples=1).squeeze( + dim=-1 + ) + + +@torch.inference_mode() +def decode( + input_ids, + model, + max_length, + top_k=1, + top_p=0.0, + temperature=1.0, + eos_token_id=None, + teacher_outputs=None, + vocab_size=None, + tensor_parallel=1, + cg=False, + enable_timing=False, +): + """Decoding, either greedy or with top-k or top-p sampling. + If top-k = 0, don't limit the number of candidates (pure sampling). + Top-k and top-p can be used together. If top_k > 0 and top_p > 0, then top-k is applied first, + then top-p. + We assume that all sequences in the same batch have the same length. + + Arguments: + input_ids: (batch, seq_len) + max_length: int + teacher_outputs (optional): (batch, seq_len). If provided, instead of sampling from the + logits, the next token is taken from the teacher_outputs. Useful for testing. + Returns: GreedySearchDecoderOnlyOutput or SampleDecoderOnlyOutput, with the following fields: + sequences: (batch, max_length) + scores: tuples of (batch, vocab_size) + """ + batch_size, seqlen_og = input_ids.shape + teacher_output_len = teacher_outputs.shape[1] if teacher_outputs is not None else 0 + if cg: + if not hasattr(model, "_decoding_cache"): + model._decoding_cache = None + model._decoding_cache = update_graph_cache( + model, + model._decoding_cache, + batch_size, + seqlen_og, + max_length, + tensor_parallel=tensor_parallel, + ) + inference_params = model._decoding_cache.inference_params + inference_params.reset(max_length, batch_size) + else: + inference_params = InferenceParams(max_seqlen=max_length, max_batch_size=batch_size) + + def get_logits(input_ids, inference_params): + decoding = inference_params.seqlen_offset > 0 + if decoding: + position_ids = torch.full( + (batch_size, 1), + inference_params.seqlen_offset, + dtype=torch.long, + device=input_ids.device, + ) + else: + position_ids = None + if not cg or not decoding: + logits = model( + input_ids, + position_ids=position_ids, + inference_params=inference_params, + num_last_tokens=1, + ).logits.squeeze(dim=1) + else: + logits = model._decoding_cache.run( + input_ids, position_ids, inference_params.seqlen_offset + ).squeeze(dim=1) + return logits[..., :vocab_size] if vocab_size is not None else logits + + def sample_tokens(logits, inference_params): + if teacher_outputs is None or teacher_output_len <= inference_params.seqlen_offset: + token = sample(logits, top_k=top_k, top_p=top_p, temperature=temperature) + else: + token = teacher_outputs[:, inference_params.seqlen_offset] + # return rearrange(token, "b -> b 1") + return token.unsqueeze(1) + + def should_stop(current_token, inference_params): + if inference_params.seqlen_offset == 0: + return False + if eos_token_id is not None and (current_token == eos_token_id).all(): + return True + if inference_params.seqlen_offset >= max_length - 1: + return True + return False + + start = torch.cuda.Event(enable_timing=enable_timing) + end = torch.cuda.Event(enable_timing=enable_timing) + + if enable_timing: + if tensor_parallel > 1: + torch.distributed.barrier() + start.record() + scores, sequences = [], [input_ids] + while not should_stop(sequences[-1], inference_params): + scores.append(get_logits(sequences[-1], inference_params)) + inference_params.seqlen_offset += sequences[-1].shape[1] + sequences.append(sample_tokens(scores[-1], inference_params)) + if enable_timing: + end.record() + if tensor_parallel > 1: + torch.distributed.barrier() + torch.cuda.synchronize() + print(f"Prompt processing + decoding time: {(start.elapsed_time(end)):.0f}ms") + output_cls = GreedySearchDecoderOnlyOutput if top_k == 1 else SampleDecoderOnlyOutput + return output_cls(sequences=torch.cat(sequences, dim=1), scores=tuple(scores)) + + +class GenerationMixin: + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + raise NotImplementedError + + def generate( + self, + input_ids, + max_length, + top_k=1, + top_p=0.0, + temperature=1.0, + return_dict_in_generate=False, + output_scores=False, + **kwargs, + ): + output = decode( + input_ids, self, max_length, top_k=top_k, top_p=top_p, temperature=temperature, **kwargs + ) + if not output_scores: + output.scores = None + return output if return_dict_in_generate else output.sequences + + +def allocate_inference_cache( + max_batch_size, + max_seqlen, + nheads, + headdim, + layers: Union[int, Sequence], + device, + dtype=torch.float16, +): + assert dtype in [torch.float16, torch.bfloat16, torch.float32] + kv_cache_shape = (max_batch_size, max_seqlen, 2, nheads, headdim) + if isinstance(layers, int): + layers = range(layers) + return {i: torch.empty(kv_cache_shape, device=device, dtype=dtype) for i in layers} + + +@dataclass +class DecodingCGCache: + max_batch_size: int = 0 + max_seqlen: int = 0 + device = None + dtype = None + callables: dict = field(default_factory=dict) + mempool = None + inference_params: Optional[InferenceParams] = None + run: Optional[Callable] = None + + +@torch.inference_mode() +def update_graph_cache( + model, + cache, + batch_size, + seqlen_og, + max_seqlen, + decoding_seqlens=(1,), + tensor_parallel=1, + dtype=None, + n_warmups=2, +): + if cache is None: + cache = DecodingCGCache() + param_example = next(iter(model.parameters())) + device = param_example.device + if dtype is None: + dtype = param_example.dtype + if ( + (device, dtype) != (cache.device, cache.dtype) + or batch_size > cache.max_batch_size + or max_seqlen > cache.max_seqlen + ): # Invalidate the cache + cache.callables = {} + cache.mempool = None + cache.inference_params = None + gc.collect() + cache.device, cache.dtype = device, dtype + cache.max_batch_size, cache.max_seqlen = batch_size, max_seqlen + if hasattr(model, "allocate_inference_cache"): + inf_cache = model.allocate_inference_cache(batch_size, max_seqlen, dtype) + else: + headdim = getattr( + model.config, + "head_dim", + model.config.hidden_size // model.config.num_attention_heads, + ) + inf_cache = allocate_inference_cache( + batch_size, + max_seqlen, + model.config.num_attention_heads // tensor_parallel, + headdim, + model.config.num_hidden_layers, + device, + dtype, + ) + lengths_per_sample = torch.full((batch_size,), seqlen_og, dtype=torch.int32, device=device) + cache.inference_params = InferenceParams( + max_seqlen=max_seqlen, + max_batch_size=batch_size, + seqlen_offset=seqlen_og, + key_value_memory_dict=inf_cache, + lengths_per_sample=lengths_per_sample, + ) + cache.mempool = torch.cuda.graphs.graph_pool_handle() + for decoding_seqlen in decoding_seqlens: + if (batch_size, decoding_seqlen) not in cache.callables: + cache.callables[batch_size, decoding_seqlen] = capture_graph( + model, + cache.inference_params, + batch_size, + max_seqlen, + decoding_seqlen=decoding_seqlen, + mempool=cache.mempool, + n_warmups=n_warmups, + ) + + def dispatch(input_ids, position_ids, seqlen): + batch_size, decoding_seqlen = input_ids.shape[:2] + return cache.callables[batch_size, decoding_seqlen](input_ids, position_ids, seqlen) + + cache.run = dispatch + cache.inference_params.seqlen_offset = 0 # Reset so it's not confusing + return cache + + +def capture_graph( + model, inference_params, batch_size, max_seqlen, decoding_seqlen=1, mempool=None, n_warmups=2 +): + device = next(iter(model.parameters())).device + input_ids = torch.full((batch_size, decoding_seqlen), 0, dtype=torch.long, device=device) + position_ids = torch.full((batch_size, decoding_seqlen), 0, dtype=torch.long, device=device) + seqlen_offset_og = inference_params.seqlen_offset + inference_params.seqlen_offset = max_seqlen - decoding_seqlen + inference_params.lengths_per_sample[:] = inference_params.seqlen_offset + + # Warmup before capture + s = torch.cuda.Stream() + s.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(s): + for _ in range(n_warmups): + logits = model( + input_ids, + position_ids=position_ids, + inference_params=inference_params, + num_last_tokens=decoding_seqlen, + ).logits + s.synchronize() + # This might be needed for correctness if we run with NCCL_GRAPH_MIXING_SUPPORT=0, + # which requires that graph launch and non-captured launch to not overlap (I think, + # that's how I interpret the documentation). I'm not sure if this is required. + if torch.distributed.is_initialized(): + torch.distributed.barrier() + torch.cuda.current_stream().wait_stream(s) + # Captures the graph + # To allow capture, automatically sets a side stream as the current stream in the context + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, pool=mempool): + logits = model( + input_ids, + position_ids=position_ids, + inference_params=inference_params, + num_last_tokens=decoding_seqlen, + ).logits + + def run(new_input_ids, new_position_ids, seqlen): + inference_params.lengths_per_sample[:] = seqlen + input_ids.copy_(new_input_ids) + position_ids.copy_(new_position_ids) + graph.replay() + return logits.clone() + + inference_params.seqlen_offset = seqlen_offset_og + return run diff --git a/source_code/SegMamba/mamba/tests/ops/test_selective_scan.py b/source_code/SegMamba/mamba/tests/ops/test_selective_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..26b34a37560f08ced653a1d9320a14f3d3f9ebd3 --- /dev/null +++ b/source_code/SegMamba/mamba/tests/ops/test_selective_scan.py @@ -0,0 +1,423 @@ +# Copyright (C) 2023, Tri Dao. + +import math + +import torch +import torch.nn.functional as F +from torch.autograd import gradcheck +import pytest + +from einops import rearrange + +from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_ref +from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, mamba_inner_ref +from mamba_ssm.ops.selective_scan_interface import bimamba_inner_fn, bimamba_inner_ref + + +# @pytest.mark.parametrize('wtype', [torch.float32, torch.complex64]) +@pytest.mark.parametrize('wtype', [torch.float32]) +# @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize('itype', [torch.float32]) +# @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096]) +@pytest.mark.parametrize('seqlen', [128, 256, 512, 1024, 2048, 4096]) +# @pytest.mark.parametrize('seqlen', [128]) +# @pytest.mark.parametrize("return_last_state", [False, True]) +@pytest.mark.parametrize("return_last_state", [True]) +# @pytest.mark.parametrize('has_delta_bias', [False, True]) +@pytest.mark.parametrize('has_delta_bias', [True]) +# @pytest.mark.parametrize('delta_softplus', [False, True]) +@pytest.mark.parametrize('delta_softplus', [True]) +# @pytest.mark.parametrize('has_z', [False, True]) +@pytest.mark.parametrize('has_z', [True]) +# @pytest.mark.parametrize('has_D', [False, True]) +@pytest.mark.parametrize('has_D', [True]) +@pytest.mark.parametrize("varBC_groups", [1, 2]) +# @pytest.mark.parametrize("varBC_groups", [1]) +# @pytest.mark.parametrize("is_variable_C", [False, True]) +@pytest.mark.parametrize("is_variable_C", [True]) +# @pytest.mark.parametrize("is_variable_B", [False, True]) +@pytest.mark.parametrize("is_variable_B", [True]) +def test_selective_scan(is_variable_B, is_variable_C, varBC_groups, has_D, has_z, has_delta_bias, + delta_softplus, return_last_state, seqlen, itype, wtype): + if varBC_groups > 1 and (not is_variable_B or not is_variable_C): + pytest.skip() # This config is not applicable + device = 'cuda' + rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3) + if itype == torch.bfloat16: + rtol, atol = 3e-2, 5e-2 + rtolw, atolw = (1e-3, 1e-3) + if has_z: # If we have z, the errors on the weights seem higher + rtolw = max(rtolw, rtol) + atolw = max(atolw, atol) + # set seed + torch.random.manual_seed(0) + batch_size = 2 + dim = 4 + dstate = 8 + is_complex = wtype == torch.complex64 + A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_() + if not is_variable_B: + B_shape = (dim, dstate) + elif varBC_groups == 1: + B_shape = (batch_size, dstate, seqlen if not is_complex else seqlen * 2) + else: + B_shape = (batch_size, varBC_groups, dstate, seqlen if not is_complex else seqlen * 2) + B = torch.randn(*B_shape, device=device, dtype=wtype if not is_variable_B else itype, + requires_grad=True) + if not is_variable_C: + C_shape = (dim, dstate) + elif varBC_groups == 1: + C_shape = (batch_size, dstate, seqlen if not is_complex else seqlen * 2) + else: + C_shape = (batch_size, varBC_groups, dstate, seqlen if not is_complex else seqlen * 2) + C = torch.randn(*C_shape, device=device, dtype=wtype if not is_variable_C else itype, + requires_grad=True) + if has_D: + D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True) + else: + D = None + if has_z: + z = torch.randn(batch_size, dim, seqlen, device=device, dtype=itype, requires_grad=True) + else: + z = None + if has_delta_bias: + delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_() + else: + delta_bias = None + u = torch.randn(batch_size, dim, seqlen, device=device, dtype=itype, requires_grad=True) + delta = (0.5 * torch.rand(batch_size, dim, seqlen, device=device, dtype=itype)).requires_grad_() + A_ref = A.detach().clone().requires_grad_() + B_ref = B.detach().clone().requires_grad_() + C_ref = C.detach().clone().requires_grad_() + D_ref = D.detach().clone().requires_grad_() if D is not None else None + z_ref = z.detach().clone().requires_grad_() if z is not None else None + u_ref = u.detach().clone().requires_grad_() + delta_ref = delta.detach().clone().requires_grad_() + delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None + out, *rest = selective_scan_fn( + u, delta, A, B, C, D, z=z, + delta_bias=delta_bias, delta_softplus=delta_softplus, + return_last_state=return_last_state + ) + if return_last_state: + state = rest[0] + out_ref, *rest = selective_scan_ref( + u_ref, delta_ref, A_ref, B_ref, C_ref, D_ref, z=z_ref, + delta_bias=delta_bias_ref, delta_softplus=delta_softplus, + return_last_state=return_last_state + ) + if return_last_state: + state_ref = rest[0] + # dA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A)) + # dt_u = delta * u + + print(f'Output max diff: {(out - out_ref).abs().max().item()}') + print(f'Output mean diff: {(out - out_ref).abs().mean().item()}') + assert torch.allclose(out, out_ref, rtol=rtol, atol=atol) + if return_last_state: + print(f'State max diff: {(state - state_ref).abs().max().item()}') + assert torch.allclose(state, state_ref, rtol=rtol, atol=atol) + + g = torch.randn_like(out) + out_ref.backward(g) + out.backward(g) + + print(f'du max diff: {(u.grad - u_ref.grad).abs().max().item()}') + print(f'ddelta max diff: {(delta.grad - delta_ref.grad).abs().max().item()}') + print(f'dA max diff: {(A.grad - A_ref.grad).abs().max().item()}') + print(f'dB max diff: {(B.grad - B_ref.grad).abs().max().item()}') + print(f'dC max diff: {(C.grad - C_ref.grad).abs().max().item()}') + if has_D: + print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}') + if has_z: + print(f'dz max diff: {(z.grad - z_ref.grad).abs().max().item()}') + if has_delta_bias: + print(f'ddelta_bias max diff: {(delta_bias.grad - delta_bias_ref.grad).abs().max().item()}') + + assert torch.allclose(u.grad, u_ref.grad.to(dtype=itype), rtol=rtol * 2, atol=atol * 2) + assert torch.allclose(delta.grad, delta_ref.grad.to(dtype=itype), rtol=rtol * 5, atol=atol * 10) + assert torch.allclose(A.grad, A_ref.grad, rtol=rtolw, atol=atolw * 5) + assert torch.allclose(B.grad, B_ref.grad, rtol=rtolw if not is_variable_B else rtol, + atol=atolw if not is_variable_B else atol) + assert torch.allclose(C.grad, C_ref.grad, rtol=rtolw if not is_variable_C else rtol, + atol=atolw if not is_variable_C else atol) + if has_D: + assert torch.allclose(D.grad, D_ref.grad, rtol=rtolw, atol=atolw) + if has_z: + assert torch.allclose(z.grad, z_ref.grad, rtol=rtolw, atol=atolw) + if has_delta_bias: + assert torch.allclose(delta_bias.grad, delta_bias_ref.grad, rtol=rtolw, atol=atolw) + + +@pytest.mark.parametrize('wtype', [torch.float32, torch.complex64]) +# @pytest.mark.parametrize('wtype', [torch.complex64]) +# @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize('itype', [torch.float32]) +# @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096]) +@pytest.mark.parametrize('seqlen', [128]) +@pytest.mark.parametrize("is_variable_C", [False, True]) +# @pytest.mark.parametrize("is_variable_C", [False]) +@pytest.mark.parametrize("is_variable_B", [False, True]) +# @pytest.mark.parametrize("is_variable_B", [True]) +def test_mamba_inner_fn(is_variable_B, is_variable_C, seqlen, itype, wtype): + device = 'cuda' + rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3) + if itype == torch.bfloat16: + rtol, atol = 3e-2, 5e-2 + rtolw, atolw = (1e-3, 1e-3) + # If we have z, the errors on the weights seem higher + rtolw = max(rtolw, rtol) + atolw = max(atolw, atol) + # set seed + torch.random.manual_seed(0) + batch_size = 2 + dim = 768 + dstate = 8 + dt_rank = 48 + is_complex = wtype == torch.complex64 + xz = torch.randn(batch_size, 2 * dim, seqlen, device=device, dtype=itype, requires_grad=True) + conv1d_weight = torch.randn(dim, 1, 3, device=device, dtype=torch.float32, requires_grad=True) + conv1d_bias = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True) + x_proj_weight = torch.randn(dt_rank + (bool(is_variable_B) + bool(is_variable_C)) * dstate + * (1 if not is_complex else 2), + dim, device=device, dtype=itype, requires_grad=True) + delta_proj_weight = torch.randn(dim, dt_rank, device=device, dtype=itype, requires_grad=True) + out_proj_weight = torch.randn(dim // 2, dim, device=device, dtype=itype, requires_grad=True) + out_proj_bias = None + A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_() + B = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True) + if not is_variable_B else None) + C = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True) + if not is_variable_C else None) + D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True) + delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_() + B_proj_bias = None + C_proj_bias = None + xz_ref = xz.detach().clone().requires_grad_() + conv1d_weight_ref = conv1d_weight.detach().clone().requires_grad_() + conv1d_bias_ref = conv1d_bias.detach().clone().requires_grad_() + x_proj_weight_ref = x_proj_weight.detach().clone().requires_grad_() + delta_proj_weight_ref = delta_proj_weight.detach().clone().requires_grad_() + out_proj_weight_ref = out_proj_weight.detach().clone().requires_grad_() + out_proj_bias_ref = (out_proj_bias.detach().clone().requires_grad_() + if out_proj_bias is not None else None) + A_ref = A.detach().clone().requires_grad_() + B_ref = B.detach().clone().requires_grad_() if B is not None else None + C_ref = C.detach().clone().requires_grad_() if C is not None else None + D_ref = D.detach().clone().requires_grad_() + delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None + out = mamba_inner_fn(xz, conv1d_weight, conv1d_bias, x_proj_weight, delta_proj_weight, + out_proj_weight, out_proj_bias, + A, B, C, D, delta_bias=delta_bias, delta_softplus=True) + out_ref = mamba_inner_ref(xz_ref, conv1d_weight_ref, conv1d_bias_ref, x_proj_weight_ref, + delta_proj_weight_ref, out_proj_weight_ref, out_proj_bias_ref, + A_ref, B_ref, C_ref, D_ref, + delta_bias=delta_bias_ref, delta_softplus=True) + # dA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A)) + # dt_u = delta * u + print("mamba_inner_fn") + print(f'Output max diff: {(out - out_ref).abs().max().item()}') + print(f'Output mean diff: {(out - out_ref).abs().mean().item()}') + assert torch.allclose(out, out_ref, rtol=rtol, atol=atol) + + g = torch.randn_like(out) + out_ref.backward(g) + out.backward(g) + + print(f'dxz max diff: {(xz.grad - xz_ref.grad).abs().max().item()}') + print(f'dA max diff: {(A.grad - A_ref.grad).abs().max().item()}') + if not is_variable_B: + print(f'dB max diff: {(B.grad - B_ref.grad).abs().max().item()}') + if not is_variable_C: + print(f'dC max diff: {(C.grad - C_ref.grad).abs().max().item()}') + print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}') + print(f'ddelta_bias max diff: {(delta_bias.grad - delta_bias_ref.grad).abs().max().item()}') + print(f'dout_proj_weight max diff: {(out_proj_weight.grad - out_proj_weight_ref.grad).abs().max().item()}') + print(f'ddelta_proj_weight max diff: {(delta_proj_weight.grad - delta_proj_weight_ref.grad).abs().max().item()}') + print(f'dx_proj_weight max diff: {(x_proj_weight.grad - x_proj_weight_ref.grad).abs().max().item()}') + print(f'dconv1d_weight max diff: {(conv1d_weight.grad - conv1d_weight_ref.grad).abs().max().item()}') + print(f'dconv1d_bias max diff: {(conv1d_bias.grad - conv1d_bias_ref.grad).abs().max().item()}') + + # assert torch.allclose(xz.grad, xz_ref.grad.to(dtype=itype), rtol=rtol * 2, atol=atol * 2) + # assert torch.allclose(delta.grad, delta_ref.grad.to(dtype=itype), rtol=rtol * 5, atol=atol * 10) + # assert torch.allclose(A.grad, A_ref.grad, rtol=rtolw, atol=atolw * 5) + # assert torch.allclose(B.grad, B_ref.grad, rtol=rtolw if not is_variable_B else rtol, + # atol=atolw if not is_variable_B else atol) + # assert torch.allclose(C.grad, C_ref.grad, rtol=rtolw if not is_variable_C else rtol, + # atol=atolw if not is_variable_C else atol) + # assert torch.allclose(D.grad, D_ref.grad, rtol=rtolw, atol=atolw) + # assert torch.allclose(delta_bias.grad, delta_bias_ref.grad, rtol=rtolw, atol=atolw) + + +# test_mamba_inner_fn(False, False, 128, torch.float32, torch.float32) + + +@pytest.mark.parametrize('wtype', [torch.float32, torch.complex64]) +# @pytest.mark.parametrize('wtype', [torch.complex64]) +# @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize('itype', [torch.float32]) +# @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096]) +@pytest.mark.parametrize('seqlen', [128]) +@pytest.mark.parametrize("is_variable_C", [False, True]) +# @pytest.mark.parametrize("is_variable_C", [False]) +@pytest.mark.parametrize("is_variable_B", [False, True]) +# @pytest.mark.parametrize("is_variable_B", [True]) +def test_bimamba_inner_fn(is_variable_B, is_variable_C, seqlen, itype, wtype): + device = 'cuda' + rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3) + if itype == torch.bfloat16: + rtol, atol = 3e-2, 5e-2 + rtolw, atolw = (1e-3, 1e-3) + # If we have z, the errors on the weights seem higher + rtolw = max(rtolw, rtol) + atolw = max(atolw, atol) + # set seed + torch.random.manual_seed(0) + batch_size = 2 + dim = 768 + dstate = 8 + dt_rank = 48 + is_complex = wtype == torch.complex64 + xz = torch.randn(batch_size, 2 * dim, seqlen, device=device, dtype=itype, requires_grad=True) + conv1d_weight = torch.randn(dim, 1, 3, device=device, dtype=torch.float32, requires_grad=True) + conv1d_bias = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True) + x_proj_weight = torch.randn(dt_rank + (bool(is_variable_B) + bool(is_variable_C)) * dstate + * (1 if not is_complex else 2), + dim, device=device, dtype=itype, requires_grad=True) + delta_proj_weight = torch.randn(dim, dt_rank, device=device, dtype=itype, requires_grad=True) + out_proj_weight = torch.randn(dim // 2, dim, device=device, dtype=itype, requires_grad=True) + out_proj_bias = None + A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_() + A_b = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_() + B = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True) + if not is_variable_B else None) + C = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True) + if not is_variable_C else None) + D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True) + delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_() + B_proj_bias = None + C_proj_bias = None + xz_ref = xz.detach().clone().requires_grad_() + conv1d_weight_ref = conv1d_weight.detach().clone().requires_grad_() + conv1d_bias_ref = conv1d_bias.detach().clone().requires_grad_() + x_proj_weight_ref = x_proj_weight.detach().clone().requires_grad_() + delta_proj_weight_ref = delta_proj_weight.detach().clone().requires_grad_() + out_proj_weight_ref = out_proj_weight.detach().clone().requires_grad_() + out_proj_bias_ref = (out_proj_bias.detach().clone().requires_grad_() + if out_proj_bias is not None else None) + A_ref = A.detach().clone().requires_grad_() + A_b_ref = A_b.detach().clone().requires_grad_() + B_ref = B.detach().clone().requires_grad_() if B is not None else None + C_ref = C.detach().clone().requires_grad_() if C is not None else None + D_ref = D.detach().clone().requires_grad_() + delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None + out = bimamba_inner_fn(xz, conv1d_weight, conv1d_bias, x_proj_weight, delta_proj_weight, + out_proj_weight, out_proj_bias, + A, A_b, B, C, D, delta_bias=delta_bias, delta_softplus=True) + out_ref = bimamba_inner_fn(xz_ref, conv1d_weight_ref, conv1d_bias_ref, x_proj_weight_ref, + delta_proj_weight_ref, out_proj_weight_ref, out_proj_bias_ref, + A_ref, A_b_ref, B_ref, C_ref, D_ref, + delta_bias=delta_bias_ref, delta_softplus=True) + # dA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A)) + # dt_u = delta * u + print("bimamba_inner_fn") + print(f'Output max diff: {(out - out_ref).abs().max().item()}') + print(f'Output mean diff: {(out - out_ref).abs().mean().item()}') + assert torch.allclose(out, out_ref, rtol=rtol, atol=atol) + + g = torch.randn_like(out) + out_ref.backward(g) + out.backward(g) + + print(f'dxz max diff: {(xz.grad - xz_ref.grad).abs().max().item()}') + print(f'dA max diff: {(A.grad - A_ref.grad).abs().max().item()}') + print(f'dA_b max diff: {(A_b.grad - A_b_ref.grad).abs().max().item()}') + if not is_variable_B: + print(f'dB max diff: {(B.grad - B_ref.grad).abs().max().item()}') + if not is_variable_C: + print(f'dC max diff: {(C.grad - C_ref.grad).abs().max().item()}') + print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}') + print(f'ddelta_bias max diff: {(delta_bias.grad - delta_bias_ref.grad).abs().max().item()}') + print(f'dout_proj_weight max diff: {(out_proj_weight.grad - out_proj_weight_ref.grad).abs().max().item()}') + print(f'ddelta_proj_weight max diff: {(delta_proj_weight.grad - delta_proj_weight_ref.grad).abs().max().item()}') + print(f'dx_proj_weight max diff: {(x_proj_weight.grad - x_proj_weight_ref.grad).abs().max().item()}') + print(f'dconv1d_weight max diff: {(conv1d_weight.grad - conv1d_weight_ref.grad).abs().max().item()}') + print(f'dconv1d_bias max diff: {(conv1d_bias.grad - conv1d_bias_ref.grad).abs().max().item()}') + +@pytest.mark.parametrize('wtype', [torch.float32, torch.complex64]) +# @pytest.mark.parametrize('wtype', [torch.complex64]) +# @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize('itype', [torch.float32]) +# @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096]) +@pytest.mark.parametrize('seqlen', [128]) +@pytest.mark.parametrize("is_variable_C", [False, True]) +# @pytest.mark.parametrize("is_variable_C", [False]) +@pytest.mark.parametrize("is_variable_B", [False, True]) +# @pytest.mark.parametrize("is_variable_B", [True]) +def test_bimamba_inner_fn_grad_check(is_variable_B, is_variable_C, seqlen, itype, wtype): + device = 'cuda' + rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3) + if itype == torch.bfloat16: + rtol, atol = 3e-2, 5e-2 + rtolw, atolw = (1e-3, 1e-3) + # If we have z, the errors on the weights seem higher + rtolw = max(rtolw, rtol) + atolw = max(atolw, atol) + # set seed + torch.random.manual_seed(0) + batch_size = 2 // 2 + dim = 768 // 8 + dstate = 8 // 8 + dt_rank = 48 // 8 + is_complex = wtype == torch.complex64 + xz = torch.randn(batch_size, 2 * dim, seqlen, device=device, dtype=itype, requires_grad=True) + conv1d_weight = torch.randn(dim, 1, 3, device=device, dtype=torch.float32, requires_grad=True) + conv1d_bias = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True) + x_proj_weight = torch.randn(dt_rank + (bool(is_variable_B) + bool(is_variable_C)) * dstate + * (1 if not is_complex else 2), + dim, device=device, dtype=itype, requires_grad=True) + delta_proj_weight = torch.randn(dim, dt_rank, device=device, dtype=itype, requires_grad=True) + out_proj_weight = torch.randn(dim // 2, dim, device=device, dtype=itype, requires_grad=True) + out_proj_bias = None + A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_() + A_b = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_() + B = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True) + if not is_variable_B else None) + C = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True) + if not is_variable_C else None) + D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True) + delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_() + B_proj_bias = None + C_proj_bias = None + xz_ref = xz.detach().clone().requires_grad_() + conv1d_weight_ref = conv1d_weight.detach().clone().requires_grad_() + conv1d_bias_ref = conv1d_bias.detach().clone().requires_grad_() + x_proj_weight_ref = x_proj_weight.detach().clone().requires_grad_() + delta_proj_weight_ref = delta_proj_weight.detach().clone().requires_grad_() + out_proj_weight_ref = out_proj_weight.detach().clone().requires_grad_() + out_proj_bias_ref = (out_proj_bias.detach().clone().requires_grad_() + if out_proj_bias is not None else None) + A_ref = A.detach().clone().requires_grad_() + A_b_ref = A_b.detach().clone().requires_grad_() + B_ref = B.detach().clone().requires_grad_() if B is not None else None + C_ref = C.detach().clone().requires_grad_() if C is not None else None + D_ref = D.detach().clone().requires_grad_() + delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None + + # func = bimamba_inner_fn + # func = mamba_inner_fn + func = mamba_inner_ref + + # gradok = gradcheck(func, (xz, conv1d_weight, conv1d_bias, x_proj_weight, delta_proj_weight,out_proj_weight, out_proj_bias, A, A_b, B, C, D, delta_bias, None, None, True)) + gradok = gradcheck(func, (xz, conv1d_weight, conv1d_bias, x_proj_weight, delta_proj_weight,out_proj_weight, out_proj_bias, A, B, C, D, delta_bias, None, None, True), eps=1e-6, atol=1e-4, nondet_tol=1.) + print(f'* {gradok} check_gradient_numerical bimamba_inner_fn') + + + +# test_bimamba_inner_fn(True, True, 128, torch.float32, torch.float32) +# test_mamba_inner_fn(True, True, 128, torch.float32, torch.float32) +test_bimamba_inner_fn_grad_check(True, True, 128, torch.float32, torch.float32) + +# input = (torch.randn(20,20,dtype=torch.double,requires_grad=True), torch.randn(30,20,dtype=torch.double,requires_grad=True)) +# test = gradcheck(torch.nn.functional.linear, input, eps=1e-6, atol=1e-4) +# print(test) \ No newline at end of file diff --git a/source_code/SegMamba/monai/_extensions/loader.py b/source_code/SegMamba/monai/_extensions/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..7affd1a3eb84ccb8fb81441e4099991b90167b78 --- /dev/null +++ b/source_code/SegMamba/monai/_extensions/loader.py @@ -0,0 +1,93 @@ +# 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 platform +from _thread import interrupt_main +from contextlib import contextmanager +from glob import glob +from os import path +from threading import Timer +from types import ModuleType + +import torch + +from monai.utils.module import get_torch_version_tuple, optional_import + +dir_path = path.dirname(path.realpath(__file__)) + + +@contextmanager +def timeout(time, message): + timer = None + try: + timer = Timer(time, interrupt_main) + timer.daemon = True + timer.start() + yield + except KeyboardInterrupt as e: + if timer is not None and timer.is_alive(): + raise e # interrupt from user? + raise TimeoutError(message) from e + finally: + if timer is not None: + try: + timer.cancel() + finally: + pass + + +def load_module( + module_name: str, defines: dict | None = None, verbose_build: bool = False, build_timeout: int = 300 +) -> ModuleType: + """ + Handles the loading of c++ extension modules. + + Args: + module_name: Name of the module to load. + Must match the name of the relevant source directory in the `_extensions` directory. + defines: Dictionary containing names and values of compilation defines. + verbose_build: Set to true to enable build logging. + build_timeout: Time in seconds before the build will throw an exception to prevent hanging. + """ + + # Ensuring named module exists in _extensions directory. + module_dir = path.join(dir_path, module_name) + if not path.exists(module_dir): + raise ValueError(f"No extension module named {module_name}") + + platform_str = f"_{platform.system()}_{platform.python_version()}_" + platform_str += "".join(f"{v}" for v in get_torch_version_tuple()[:2]) + # Adding configuration to module name. + if defines is not None: + module_name = "_".join([module_name] + [f"{v}" for v in defines.values()]) + + # Gathering source files. + source = glob(path.join(module_dir, "**", "*.cpp"), recursive=True) + if torch.cuda.is_available(): + source += glob(path.join(module_dir, "**", "*.cu"), recursive=True) + platform_str += f"_{torch.version.cuda}" + + # Constructing compilation argument list. + define_args = [] if not defines else [f"-D {key}={defines[key]}" for key in defines] + + # Ninja may be blocked by something out of our control. + # This will error if the build takes longer than expected. + with timeout(build_timeout, "Build appears to be blocked. Is there a stopped process building the same extension?"): + load, _ = optional_import("torch.utils.cpp_extension", name="load") # main trigger some JIT config in pytorch + # This will either run the build or return the existing .so object. + name = module_name + platform_str.replace(".", "_") + module = load( + name=name, sources=source, extra_cflags=define_args, extra_cuda_cflags=define_args, verbose=verbose_build + ) + + return module # type: ignore[no-any-return] diff --git a/source_code/SegMamba/monai/apps/datasets.py b/source_code/SegMamba/monai/apps/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..67ea3059cce5f098e87d8c5326133326bb2e2fdf --- /dev/null +++ b/source_code/SegMamba/monai/apps/datasets.py @@ -0,0 +1,745 @@ +# 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 sys +import warnings +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any + +import numpy as np + +from monai.apps.tcia import ( + DCM_FILENAME_REGEX, + download_tcia_series_instance, + get_tcia_metadata, + get_tcia_ref_uid, + match_tcia_ref_uid_in_study, +) +from monai.apps.utils import download_and_extract +from monai.config.type_definitions import PathLike +from monai.data import ( + CacheDataset, + PydicomReader, + load_decathlon_datalist, + load_decathlon_properties, + partition_dataset, + select_cross_validation_folds, +) +from monai.transforms import LoadImaged, Randomizable +from monai.utils import ensure_tuple + +__all__ = ["MedNISTDataset", "DecathlonDataset", "CrossValidation", "TciaDataset"] + + +class MedNISTDataset(Randomizable, CacheDataset): + """ + The Dataset to automatically download MedNIST data and generate items for training, validation or test. + It's based on `CacheDataset` to accelerate the training process. + + Args: + root_dir: target directory to download and load MedNIST dataset. + section: expected data section, can be: `training`, `validation` or `test`. + transform: transforms to execute operations on input data. + download: whether to download and extract the MedNIST from resource link, default is False. + if expected file already exists, skip downloading even set it to True. + user can manually copy `MedNIST.tar.gz` file or `MedNIST` folder to root directory. + seed: random seed to randomly split training, validation and test datasets, default is 0. + val_frac: percentage of validation fraction in the whole dataset, default is 0.1. + test_frac: percentage of test fraction in the whole dataset, default is 0.1. + cache_num: number of items to be cached. Default is `sys.maxsize`. + will take the minimum of (cache_num, data_length x cache_rate, data_length). + cache_rate: percentage of cached data in total, default is 1.0 (cache all). + will take the minimum of (cache_num, data_length x cache_rate, data_length). + num_workers: the number of worker threads if computing cache in the initialization. + If num_workers is None then the number returned by os.cpu_count() is used. + If a value less than 1 is specified, 1 will be used instead. + progress: whether to display a progress bar when downloading dataset and computing the transform cache content. + copy_cache: whether to `deepcopy` the cache content before applying the random transforms, + default to `True`. if the random transforms don't modify the cached content + (for example, randomly crop from the cached image and deepcopy the crop region) + or if every cache item is only used once in a `multi-processing` environment, + may set `copy=False` for better performance. + as_contiguous: whether to convert the cached NumPy array or PyTorch tensor to be contiguous. + it may help improve the performance of following logic. + runtime_cache: whether to compute cache at the runtime, default to `False` to prepare + the cache content at initialization. See: :py:class:`monai.data.CacheDataset`. + + Raises: + ValueError: When ``root_dir`` is not a directory. + RuntimeError: When ``dataset_dir`` doesn't exist and downloading is not selected (``download=False``). + + """ + + resource = "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/MedNIST.tar.gz" + md5 = "0bc7306e7427e00ad1c5526a6677552d" + compressed_file_name = "MedNIST.tar.gz" + dataset_folder_name = "MedNIST" + + def __init__( + self, + root_dir: PathLike, + section: str, + transform: Sequence[Callable] | Callable = (), + download: bool = False, + seed: int = 0, + val_frac: float = 0.1, + test_frac: float = 0.1, + cache_num: int = sys.maxsize, + cache_rate: float = 1.0, + num_workers: int | None = 1, + progress: bool = True, + copy_cache: bool = True, + as_contiguous: bool = True, + runtime_cache: bool = False, + ) -> None: + root_dir = Path(root_dir) + if not root_dir.is_dir(): + raise ValueError("Root directory root_dir must be a directory.") + self.section = section + self.val_frac = val_frac + self.test_frac = test_frac + self.set_random_state(seed=seed) + tarfile_name = root_dir / self.compressed_file_name + dataset_dir = root_dir / self.dataset_folder_name + self.num_class = 0 + if download: + download_and_extract( + url=self.resource, + filepath=tarfile_name, + output_dir=root_dir, + hash_val=self.md5, + hash_type="md5", + progress=progress, + ) + + if not dataset_dir.is_dir(): + raise RuntimeError( + f"Cannot find dataset directory: {dataset_dir}, please use download=True to download it." + ) + data = self._generate_data_list(dataset_dir) + if transform == (): + transform = LoadImaged("image") + CacheDataset.__init__( + self, + data=data, + transform=transform, + cache_num=cache_num, + cache_rate=cache_rate, + num_workers=num_workers, + progress=progress, + copy_cache=copy_cache, + as_contiguous=as_contiguous, + runtime_cache=runtime_cache, + ) + + def randomize(self, data: np.ndarray) -> None: + self.R.shuffle(data) + + def get_num_classes(self) -> int: + """Get number of classes.""" + return self.num_class + + def _generate_data_list(self, dataset_dir: PathLike) -> list[dict]: + """ + Raises: + ValueError: When ``section`` is not one of ["training", "validation", "test"]. + + """ + dataset_dir = Path(dataset_dir) + class_names = sorted(f"{x.name}" for x in dataset_dir.iterdir() if x.is_dir()) # folder name as the class name + self.num_class = len(class_names) + image_files = [[f"{x}" for x in (dataset_dir / class_names[i]).iterdir()] for i in range(self.num_class)] + num_each = [len(image_files[i]) for i in range(self.num_class)] + image_files_list = [] + image_class = [] + class_name = [] + for i in range(self.num_class): + image_files_list.extend(image_files[i]) + image_class.extend([i] * num_each[i]) + class_name.extend([class_names[i]] * num_each[i]) + + length = len(image_files_list) + indices = np.arange(length) + self.randomize(indices) + + test_length = int(length * self.test_frac) + val_length = int(length * self.val_frac) + if self.section == "test": + section_indices = indices[:test_length] + elif self.section == "validation": + section_indices = indices[test_length : test_length + val_length] + elif self.section == "training": + section_indices = indices[test_length + val_length :] + else: + raise ValueError( + f'Unsupported section: {self.section}, available options are ["training", "validation", "test"].' + ) + # the types of label and class name should be compatible with the pytorch dataloader + return [ + {"image": image_files_list[i], "label": image_class[i], "class_name": class_name[i]} + for i in section_indices + ] + + +class DecathlonDataset(Randomizable, CacheDataset): + """ + The Dataset to automatically download the data of Medical Segmentation Decathlon challenge + (http://medicaldecathlon.com/) and generate items for training, validation or test. + It will also load these properties from the JSON config file of dataset. user can call `get_properties()` + to get specified properties or all the properties loaded. + It's based on :py:class:`monai.data.CacheDataset` to accelerate the training process. + + Args: + root_dir: user's local directory for caching and loading the MSD datasets. + task: which task to download and execute: one of list ("Task01_BrainTumour", "Task02_Heart", + "Task03_Liver", "Task04_Hippocampus", "Task05_Prostate", "Task06_Lung", "Task07_Pancreas", + "Task08_HepaticVessel", "Task09_Spleen", "Task10_Colon"). + section: expected data section, can be: `training`, `validation` or `test`. + transform: transforms to execute operations on input data. + for further usage, use `EnsureChannelFirstd` to convert the shape to [C, H, W, D]. + download: whether to download and extract the Decathlon from resource link, default is False. + if expected file already exists, skip downloading even set it to True. + user can manually copy tar file or dataset folder to the root directory. + val_frac: percentage of validation fraction in the whole dataset, default is 0.2. + seed: random seed to randomly shuffle the datalist before splitting into training and validation, default is 0. + note to set same seed for `training` and `validation` sections. + cache_num: number of items to be cached. Default is `sys.maxsize`. + will take the minimum of (cache_num, data_length x cache_rate, data_length). + cache_rate: percentage of cached data in total, default is 1.0 (cache all). + will take the minimum of (cache_num, data_length x cache_rate, data_length). + num_workers: the number of worker threads if computing cache in the initialization. + If num_workers is None then the number returned by os.cpu_count() is used. + If a value less than 1 is specified, 1 will be used instead. + progress: whether to display a progress bar when downloading dataset and computing the transform cache content. + copy_cache: whether to `deepcopy` the cache content before applying the random transforms, + default to `True`. if the random transforms don't modify the cached content + (for example, randomly crop from the cached image and deepcopy the crop region) + or if every cache item is only used once in a `multi-processing` environment, + may set `copy=False` for better performance. + as_contiguous: whether to convert the cached NumPy array or PyTorch tensor to be contiguous. + it may help improve the performance of following logic. + runtime_cache: whether to compute cache at the runtime, default to `False` to prepare + the cache content at initialization. See: :py:class:`monai.data.CacheDataset`. + + Raises: + ValueError: When ``root_dir`` is not a directory. + ValueError: When ``task`` is not one of ["Task01_BrainTumour", "Task02_Heart", + "Task03_Liver", "Task04_Hippocampus", "Task05_Prostate", "Task06_Lung", "Task07_Pancreas", + "Task08_HepaticVessel", "Task09_Spleen", "Task10_Colon"]. + RuntimeError: When ``dataset_dir`` doesn't exist and downloading is not selected (``download=False``). + + Example:: + + transform = Compose( + [ + LoadImaged(keys=["image", "label"]), + EnsureChannelFirstd(keys=["image", "label"]), + ScaleIntensityd(keys="image"), + ToTensord(keys=["image", "label"]), + ] + ) + + val_data = DecathlonDataset( + root_dir="./", task="Task09_Spleen", transform=transform, section="validation", seed=12345, download=True + ) + + print(val_data[0]["image"], val_data[0]["label"]) + + """ + + resource = { + "Task01_BrainTumour": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task01_BrainTumour.tar", + "Task02_Heart": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task02_Heart.tar", + "Task03_Liver": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task03_Liver.tar", + "Task04_Hippocampus": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task04_Hippocampus.tar", + "Task05_Prostate": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task05_Prostate.tar", + "Task06_Lung": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task06_Lung.tar", + "Task07_Pancreas": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task07_Pancreas.tar", + "Task08_HepaticVessel": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task08_HepaticVessel.tar", + "Task09_Spleen": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task09_Spleen.tar", + "Task10_Colon": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task10_Colon.tar", + } + md5 = { + "Task01_BrainTumour": "240a19d752f0d9e9101544901065d872", + "Task02_Heart": "06ee59366e1e5124267b774dbd654057", + "Task03_Liver": "a90ec6c4aa7f6a3d087205e23d4e6397", + "Task04_Hippocampus": "9d24dba78a72977dbd1d2e110310f31b", + "Task05_Prostate": "35138f08b1efaef89d7424d2bcc928db", + "Task06_Lung": "8afd997733c7fc0432f71255ba4e52dc", + "Task07_Pancreas": "4f7080cfca169fa8066d17ce6eb061e4", + "Task08_HepaticVessel": "641d79e80ec66453921d997fbf12a29c", + "Task09_Spleen": "410d4a301da4e5b2f6f86ec3ddba524e", + "Task10_Colon": "bad7a188931dc2f6acf72b08eb6202d0", + } + + def __init__( + self, + root_dir: PathLike, + task: str, + section: str, + transform: Sequence[Callable] | Callable = (), + download: bool = False, + seed: int = 0, + val_frac: float = 0.2, + cache_num: int = sys.maxsize, + cache_rate: float = 1.0, + num_workers: int = 1, + progress: bool = True, + copy_cache: bool = True, + as_contiguous: bool = True, + runtime_cache: bool = False, + ) -> None: + root_dir = Path(root_dir) + if not root_dir.is_dir(): + raise ValueError("Root directory root_dir must be a directory.") + self.section = section + self.val_frac = val_frac + self.set_random_state(seed=seed) + if task not in self.resource: + raise ValueError(f"Unsupported task: {task}, available options are: {list(self.resource.keys())}.") + dataset_dir = root_dir / task + tarfile_name = f"{dataset_dir}.tar" + if download: + download_and_extract( + url=self.resource[task], + filepath=tarfile_name, + output_dir=root_dir, + hash_val=self.md5[task], + hash_type="md5", + progress=progress, + ) + + if not dataset_dir.exists(): + raise RuntimeError( + f"Cannot find dataset directory: {dataset_dir}, please use download=True to download it." + ) + self.indices: np.ndarray = np.array([]) + data = self._generate_data_list(dataset_dir) + # as `release` key has typo in Task04 config file, ignore it. + property_keys = [ + "name", + "description", + "reference", + "licence", + "tensorImageSize", + "modality", + "labels", + "numTraining", + "numTest", + ] + self._properties = load_decathlon_properties(dataset_dir / "dataset.json", property_keys) + if transform == (): + transform = LoadImaged(["image", "label"]) + CacheDataset.__init__( + self, + data=data, + transform=transform, + cache_num=cache_num, + cache_rate=cache_rate, + num_workers=num_workers, + progress=progress, + copy_cache=copy_cache, + as_contiguous=as_contiguous, + runtime_cache=runtime_cache, + ) + + def get_indices(self) -> np.ndarray: + """ + Get the indices of datalist used in this dataset. + + """ + return self.indices + + def randomize(self, data: np.ndarray) -> None: + self.R.shuffle(data) + + def get_properties(self, keys: Sequence[str] | str | None = None) -> dict: + """ + Get the loaded properties of dataset with specified keys. + If no keys specified, return all the loaded properties. + + """ + if keys is None: + return self._properties + if self._properties is not None: + return {key: self._properties[key] for key in ensure_tuple(keys)} + return {} + + def _generate_data_list(self, dataset_dir: PathLike) -> list[dict]: + # the types of the item in data list should be compatible with the dataloader + dataset_dir = Path(dataset_dir) + section = "training" if self.section in ["training", "validation"] else "test" + datalist = load_decathlon_datalist(dataset_dir / "dataset.json", True, section) + return self._split_datalist(datalist) + + def _split_datalist(self, datalist: list[dict]) -> list[dict]: + if self.section == "test": + return datalist + length = len(datalist) + indices = np.arange(length) + self.randomize(indices) + + val_length = int(length * self.val_frac) + if self.section == "training": + self.indices = indices[val_length:] + else: + self.indices = indices[:val_length] + + return [datalist[i] for i in self.indices] + + +class TciaDataset(Randomizable, CacheDataset): + """ + The Dataset to automatically download the data from a public The Cancer Imaging Archive (TCIA) dataset + and generate items for training, validation or test. + + The Highdicom library is used to load dicom data with modality "SEG", but only a part of collections are + supported, such as: "C4KC-KiTS", "NSCLC-Radiomics", "NSCLC-Radiomics-Interobserver1", " QIN-PROSTATE-Repeatability" + and "PROSTATEx". Therefore, if "seg" is included in `keys` of the `LoadImaged` transform and loading some + other collections, errors may be raised. For supported collections, the original "SEG" information may not + always be consistent for each dicom file. Therefore, to avoid creating different format of labels, please use + the `label_dict` argument of `PydicomReader` when calling the `LoadImaged` transform. The prepared label dicts + of collections that are mentioned above is also saved in: `monai.apps.tcia.TCIA_LABEL_DICT`. You can also refer + to the second example bellow. + + + This class is based on :py:class:`monai.data.CacheDataset` to accelerate the training process. + + Args: + root_dir: user's local directory for caching and loading the TCIA dataset. + collection: name of a TCIA collection. + a TCIA dataset is defined as a collection. Please check the following list to browse + the collection list (only public collections can be downloaded): + https://www.cancerimagingarchive.net/collections/ + section: expected data section, can be: `training`, `validation` or `test`. + transform: transforms to execute operations on input data. + for further usage, use `EnsureChannelFirstd` to convert the shape to [C, H, W, D]. + If not specified, `LoadImaged(reader="PydicomReader", keys=["image"])` will be used as the default + transform. In addition, we suggest to set the argument `labels` for `PydicomReader` if segmentations + are needed to be loaded. The original labels for each dicom series may be different, using this argument + is able to unify the format of labels. + download: whether to download and extract the dataset, default is False. + if expected file already exists, skip downloading even set it to True. + user can manually copy tar file or dataset folder to the root directory. + download_len: number of series that will be downloaded, the value should be larger than 0 or -1, where -1 means + all series will be downloaded. Default is -1. + seg_type: modality type of segmentation that is used to do the first step download. Default is "SEG". + modality_tag: tag of modality. Default is (0x0008, 0x0060). + ref_series_uid_tag: tag of referenced Series Instance UID. Default is (0x0020, 0x000e). + ref_sop_uid_tag: tag of referenced SOP Instance UID. Default is (0x0008, 0x1155). + specific_tags: tags that will be loaded for "SEG" series. This argument will be used in + `monai.data.PydicomReader`. Default is [(0x0008, 0x1115), (0x0008,0x1140), (0x3006, 0x0010), + (0x0020,0x000D), (0x0010,0x0010), (0x0010,0x0020), (0x0020,0x0011), (0x0020,0x0012)]. + fname_regex: a regular expression to match the file names when the input is a folder. + If provided, only the matched files will be included. For example, to include the file name + "image_0001.dcm", the regular expression could be `".*image_(\\d+).dcm"`. + Default to `"^(?!.*LICENSE).*"`, ignoring any file name containing `"LICENSE"`. + val_frac: percentage of validation fraction in the whole dataset, default is 0.2. + seed: random seed to randomly shuffle the datalist before splitting into training and validation, default is 0. + note to set same seed for `training` and `validation` sections. + cache_num: number of items to be cached. Default is `sys.maxsize`. + will take the minimum of (cache_num, data_length x cache_rate, data_length). + cache_rate: percentage of cached data in total, default is 0.0 (no cache). + will take the minimum of (cache_num, data_length x cache_rate, data_length). + num_workers: the number of worker threads if computing cache in the initialization. + If num_workers is None then the number returned by os.cpu_count() is used. + If a value less than 1 is specified, 1 will be used instead. + progress: whether to display a progress bar when downloading dataset and computing the transform cache content. + copy_cache: whether to `deepcopy` the cache content before applying the random transforms, + default to `True`. if the random transforms don't modify the cached content + (for example, randomly crop from the cached image and deepcopy the crop region) + or if every cache item is only used once in a `multi-processing` environment, + may set `copy=False` for better performance. + as_contiguous: whether to convert the cached NumPy array or PyTorch tensor to be contiguous. + it may help improve the performance of following logic. + runtime_cache: whether to compute cache at the runtime, default to `False` to prepare + the cache content at initialization. See: :py:class:`monai.data.CacheDataset`. + + Example:: + + # collection is "Pancreatic-CT-CBCT-SEG", seg_type is "RTSTRUCT" + data = TciaDataset( + root_dir="./", collection="Pancreatic-CT-CBCT-SEG", seg_type="RTSTRUCT", download=True + ) + + # collection is "C4KC-KiTS", seg_type is "SEG", and load both images and segmentations + from monai.apps.tcia import TCIA_LABEL_DICT + transform = Compose( + [ + LoadImaged(reader="PydicomReader", keys=["image", "seg"], label_dict=TCIA_LABEL_DICT["C4KC-KiTS"]), + EnsureChannelFirstd(keys=["image", "seg"]), + ResampleToMatchd(keys="image", key_dst="seg"), + ] + ) + data = TciaDataset( + root_dir="./", collection="C4KC-KiTS", section="validation", seed=12345, download=True + ) + + print(data[0]["seg"].shape) + + """ + + def __init__( + self, + root_dir: PathLike, + collection: str, + section: str, + transform: Sequence[Callable] | Callable = (), + download: bool = False, + download_len: int = -1, + seg_type: str = "SEG", + modality_tag: tuple = (0x0008, 0x0060), + ref_series_uid_tag: tuple = (0x0020, 0x000E), + ref_sop_uid_tag: tuple = (0x0008, 0x1155), + specific_tags: tuple = ( + (0x0008, 0x1115), # Referenced Series Sequence + (0x0008, 0x1140), # Referenced Image Sequence + (0x3006, 0x0010), # Referenced Frame of Reference Sequence + (0x0020, 0x000D), # Study Instance UID + (0x0010, 0x0010), # Patient's Name + (0x0010, 0x0020), # Patient ID + (0x0020, 0x0011), # Series Number + (0x0020, 0x0012), # Acquisition Number + ), + fname_regex: str = DCM_FILENAME_REGEX, + seed: int = 0, + val_frac: float = 0.2, + cache_num: int = sys.maxsize, + cache_rate: float = 0.0, + num_workers: int = 1, + progress: bool = True, + copy_cache: bool = True, + as_contiguous: bool = True, + runtime_cache: bool = False, + ) -> None: + root_dir = Path(root_dir) + if not root_dir.is_dir(): + raise ValueError("Root directory root_dir must be a directory.") + + self.section = section + self.val_frac = val_frac + self.seg_type = seg_type + self.modality_tag = modality_tag + self.ref_series_uid_tag = ref_series_uid_tag + self.ref_sop_uid_tag = ref_sop_uid_tag + + self.set_random_state(seed=seed) + download_dir = os.path.join(root_dir, collection) + load_tags = list(specific_tags) + load_tags += [modality_tag] + self.load_tags = load_tags + if download: + seg_series_list = get_tcia_metadata( + query=f"getSeries?Collection={collection}&Modality={seg_type}", attribute="SeriesInstanceUID" + ) + if download_len > 0: + seg_series_list = seg_series_list[:download_len] + if len(seg_series_list) == 0: + raise ValueError(f"Cannot find data with collection: {collection} seg_type: {seg_type}") + for series_uid in seg_series_list: + self._download_series_reference_data(series_uid, download_dir) + + if not os.path.exists(download_dir): + raise RuntimeError(f"Cannot find dataset directory: {download_dir}.") + self.fname_regex = fname_regex + + self.indices: np.ndarray = np.array([]) + self.datalist = self._generate_data_list(download_dir) + + if transform == (): + transform = LoadImaged(keys=["image"], reader="PydicomReader", fname_regex=self.fname_regex) + CacheDataset.__init__( + self, + data=self.datalist, + transform=transform, + cache_num=cache_num, + cache_rate=cache_rate, + num_workers=num_workers, + progress=progress, + copy_cache=copy_cache, + as_contiguous=as_contiguous, + runtime_cache=runtime_cache, + ) + + def get_indices(self) -> np.ndarray: + """ + Get the indices of datalist used in this dataset. + + """ + return self.indices + + def randomize(self, data: np.ndarray) -> None: + self.R.shuffle(data) + + def _download_series_reference_data(self, series_uid: str, download_dir: str) -> None: + """ + First of all, download a series from TCIA according to `series_uid`. + Then find all referenced series and download. + """ + seg_first_dir = os.path.join(download_dir, "raw", series_uid) + download_tcia_series_instance( + series_uid=series_uid, download_dir=download_dir, output_dir=seg_first_dir, check_md5=False + ) + dicom_files = [f for f in sorted(os.listdir(seg_first_dir)) if f.endswith(".dcm")] + # achieve series number and patient id from the first dicom file + dcm_path = os.path.join(seg_first_dir, dicom_files[0]) + ds = PydicomReader(stop_before_pixels=True, specific_tags=self.load_tags).read(dcm_path) + # (0x0010,0x0020) and (0x0010,0x0010), better to be contained in `specific_tags` + patient_id = ds.PatientID if ds.PatientID else ds.PatientName + if not patient_id: + warnings.warn(f"unable to find patient name of dicom file: {dcm_path}, use 'patient' instead.") + patient_id = "patient" + # (0x0020,0x0011) and (0x0020,0x0012), better to be contained in `specific_tags` + series_num = ds.SeriesNumber if ds.SeriesNumber else ds.AcquisitionNumber + if not series_num: + warnings.warn(f"unable to find series number of dicom file: {dcm_path}, use '0' instead.") + series_num = 0 + + series_num = str(series_num) + seg_dir = os.path.join(download_dir, patient_id, series_num, self.seg_type.lower()) + dcm_dir = os.path.join(download_dir, patient_id, series_num, "image") + + # get ref uuid + ref_uid_list = [] + for dcm_file in dicom_files: + dcm_path = os.path.join(seg_first_dir, dcm_file) + ds = PydicomReader(stop_before_pixels=True, specific_tags=self.load_tags).read(dcm_path) + if ds[self.modality_tag].value == self.seg_type: + ref_uid = get_tcia_ref_uid( + ds, find_sop=False, ref_series_uid_tag=self.ref_series_uid_tag, ref_sop_uid_tag=self.ref_sop_uid_tag + ) + if ref_uid == "": + ref_sop_uid = get_tcia_ref_uid( + ds, + find_sop=True, + ref_series_uid_tag=self.ref_series_uid_tag, + ref_sop_uid_tag=self.ref_sop_uid_tag, + ) + ref_uid = match_tcia_ref_uid_in_study(ds.StudyInstanceUID, ref_sop_uid) + if ref_uid != "": + ref_uid_list.append(ref_uid) + if not ref_uid_list: + warnings.warn(f"Cannot find the referenced Series Instance UID from series: {series_uid}.") + else: + download_tcia_series_instance( + series_uid=ref_uid_list[0], download_dir=download_dir, output_dir=dcm_dir, check_md5=False + ) + if not os.path.exists(seg_dir): + shutil.copytree(seg_first_dir, seg_dir) + + def _generate_data_list(self, dataset_dir: PathLike) -> list[dict]: + # the types of the item in data list should be compatible with the dataloader + dataset_dir = Path(dataset_dir) + datalist = [] + patient_list = [f.name for f in os.scandir(dataset_dir) if f.is_dir() and f.name != "raw"] + for patient_id in patient_list: + series_list = [f.name for f in os.scandir(os.path.join(dataset_dir, patient_id)) if f.is_dir()] + for series_num in series_list: + seg_key = self.seg_type.lower() + image_path = os.path.join(dataset_dir, patient_id, series_num, "image") + mask_path = os.path.join(dataset_dir, patient_id, series_num, seg_key) + + if os.path.exists(image_path): + datalist.append({"image": image_path, seg_key: mask_path}) + else: + datalist.append({seg_key: mask_path}) + + return self._split_datalist(datalist) + + def _split_datalist(self, datalist: list[dict]) -> list[dict]: + if self.section == "test": + return datalist + length = len(datalist) + indices = np.arange(length) + self.randomize(indices) + + val_length = int(length * self.val_frac) + if self.section == "training": + self.indices = indices[val_length:] + else: + self.indices = indices[:val_length] + + return [datalist[i] for i in self.indices] + + +class CrossValidation: + """ + Cross validation dataset based on the general dataset which must have `_split_datalist` API. + + Args: + dataset_cls: dataset class to be used to create the cross validation partitions. + It must have `_split_datalist` API. + nfolds: number of folds to split the data for cross validation. + seed: random seed to randomly shuffle the datalist before splitting into N folds, default is 0. + dataset_params: other additional parameters for the dataset_cls base class. + + Example of 5 folds cross validation training:: + + cvdataset = CrossValidation( + dataset_cls=DecathlonDataset, + nfolds=5, + seed=12345, + root_dir="./", + task="Task09_Spleen", + section="training", + transform=train_transform, + download=True, + ) + dataset_fold0_train = cvdataset.get_dataset(folds=[1, 2, 3, 4]) + dataset_fold0_val = cvdataset.get_dataset(folds=0, transform=val_transform, download=False) + # execute training for fold 0 ... + + dataset_fold1_train = cvdataset.get_dataset(folds=[0, 2, 3, 4]) + dataset_fold1_val = cvdataset.get_dataset(folds=1, transform=val_transform, download=False) + # execute training for fold 1 ... + + ... + + dataset_fold4_train = ... + # execute training for fold 4 ... + + """ + + def __init__(self, dataset_cls: object, nfolds: int = 5, seed: int = 0, **dataset_params: Any) -> None: + if not hasattr(dataset_cls, "_split_datalist"): + raise ValueError("dataset class must have _split_datalist API.") + self.dataset_cls = dataset_cls + self.nfolds = nfolds + self.seed = seed + self.dataset_params = dataset_params + + def get_dataset(self, folds: Sequence[int] | int, **dataset_params: Any) -> object: + """ + Generate dataset based on the specified fold indices in the cross validation group. + + Args: + folds: index of folds for training or validation, if a list of values, concatenate the data. + dataset_params: other additional parameters for the dataset_cls base class, will override + the same parameters in `self.dataset_params`. + + """ + nfolds = self.nfolds + seed = self.seed + dataset_params_ = dict(self.dataset_params) + dataset_params_.update(dataset_params) + + class _NsplitsDataset(self.dataset_cls): # type: ignore + + def _split_datalist(self, datalist: list[dict]) -> list[dict]: + data = partition_dataset(data=datalist, num_partitions=nfolds, shuffle=True, seed=seed) + return select_cross_validation_folds(partitions=data, folds=folds) + + return _NsplitsDataset(**dataset_params_) diff --git a/source_code/SegMamba/monai/apps/utils.py b/source_code/SegMamba/monai/apps/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0c998146a3f688b8b957019e0834121d98934dbd --- /dev/null +++ b/source_code/SegMamba/monai/apps/utils.py @@ -0,0 +1,336 @@ +# 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 hashlib +import json +import logging +import os +import shutil +import sys +import tarfile +import tempfile +import warnings +import zipfile +from pathlib import Path +from typing import TYPE_CHECKING, Any +from urllib.error import ContentTooShortError, HTTPError, URLError +from urllib.parse import urlparse +from urllib.request import urlopen, urlretrieve + +from monai.config.type_definitions import PathLike +from monai.utils import look_up_option, min_version, optional_import + +gdown, has_gdown = optional_import("gdown", "4.7.3") + +if TYPE_CHECKING: + from tqdm import tqdm + + has_tqdm = True +else: + tqdm, has_tqdm = optional_import("tqdm", "4.47.0", min_version, "tqdm") + +__all__ = ["check_hash", "download_url", "extractall", "download_and_extract", "get_logger", "SUPPORTED_HASH_TYPES"] + +DEFAULT_FMT = "%(asctime)s - %(levelname)s - %(message)s" +SUPPORTED_HASH_TYPES = {"md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512} + + +def get_logger( + module_name: str = "monai.apps", + fmt: str = DEFAULT_FMT, + datefmt: str | None = None, + logger_handler: logging.Handler | None = None, +) -> logging.Logger: + """ + Get a `module_name` logger with the specified format and date format. + By default, the logger will print to `stdout` at the INFO level. + If `module_name` is `None`, return the root logger. + `fmt` and `datafmt` are passed to a `logging.Formatter` object + (https://docs.python.org/3/library/logging.html#formatter-objects). + `logger_handler` can be used to add an additional handler. + """ + adds_stdout_handler = module_name is not None and module_name not in logging.root.manager.loggerDict + logger = logging.getLogger(module_name) + logger.propagate = False + logger.setLevel(logging.INFO) + if adds_stdout_handler: # don't add multiple stdout or add to the root + handler = logging.StreamHandler(sys.stdout) + formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) + handler.setFormatter(formatter) + logger.addHandler(handler) + if logger_handler is not None: + logger.addHandler(logger_handler) + return logger + + +# apps module-level default logger +logger = get_logger("monai.apps") +__all__.append("logger") + + +def _basename(p: PathLike) -> str: + """get the last part of the path (removing the trailing slash if it exists)""" + sep = os.path.sep + (os.path.altsep or "") + "/ " + return Path(f"{p}".rstrip(sep)).name + + +def _download_with_progress(url: str, filepath: Path, progress: bool = True) -> None: + """ + Retrieve file from `url` to `filepath`, optionally showing a progress bar. + """ + try: + if has_tqdm and progress: + + class TqdmUpTo(tqdm): + """ + Provides `update_to(n)` which uses `tqdm.update(delta_n)`. + Inspired by the example in https://github.com/tqdm/tqdm. + """ + + def update_to(self, b: int = 1, bsize: int = 1, tsize: int | None = None) -> None: + """ + Args: + b: number of blocks transferred so far, default: 1. + bsize: size of each block (in tqdm units), default: 1. + tsize: total size (in tqdm units). if None, remains unchanged. + """ + if tsize is not None: + self.total = tsize + self.update(b * bsize - self.n) # will also set self.n = b * bsize + + with TqdmUpTo(unit="B", unit_scale=True, unit_divisor=1024, miniters=1, desc=_basename(filepath)) as t: + urlretrieve(url, filepath, reporthook=t.update_to) + else: + if not has_tqdm and progress: + warnings.warn("tqdm is not installed, will not show the downloading progress bar.") + urlretrieve(url, filepath) + except (URLError, HTTPError, ContentTooShortError, OSError) as e: + logger.error(f"Download failed from {url} to {filepath}.") + raise e + + +def check_hash(filepath: PathLike, val: str | None = None, hash_type: str = "md5") -> bool: + """ + Verify hash signature of specified file. + + Args: + filepath: path of source file to verify hash value. + val: expected hash value of the file. + hash_type: type of hash algorithm to use, default is `"md5"`. + The supported hash types are `"md5"`, `"sha1"`, `"sha256"`, `"sha512"`. + See also: :py:data:`monai.apps.utils.SUPPORTED_HASH_TYPES`. + + """ + if val is None: + logger.info(f"Expected {hash_type} is None, skip {hash_type} check for file {filepath}.") + return True + actual_hash_func = look_up_option(hash_type.lower(), SUPPORTED_HASH_TYPES) + + if sys.version_info >= (3, 9): + actual_hash = actual_hash_func(usedforsecurity=False) # allows checks on FIPS enabled machines + else: + actual_hash = actual_hash_func() + + try: + with open(filepath, "rb") as f: + for chunk in iter(lambda: f.read(1024 * 1024), b""): + actual_hash.update(chunk) + except Exception as e: + logger.error(f"Exception in check_hash: {e}") + return False + if val != actual_hash.hexdigest(): + logger.error(f"check_hash failed {actual_hash.hexdigest()}.") + return False + + logger.info(f"Verified '{_basename(filepath)}', {hash_type}: {val}.") + return True + + +def download_url( + url: str, + filepath: PathLike = "", + hash_val: str | None = None, + hash_type: str = "md5", + progress: bool = True, + **gdown_kwargs: Any, +) -> None: + """ + Download file from specified URL link, support process bar and hash check. + + Args: + url: source URL link to download file. + filepath: target filepath to save the downloaded file (including the filename). + If undefined, `os.path.basename(url)` will be used. + hash_val: expected hash value to validate the downloaded file. + if None, skip hash validation. + hash_type: 'md5' or 'sha1', defaults to 'md5'. + progress: whether to display a progress bar. + gdown_kwargs: other args for `gdown` except for the `url`, `output` and `quiet`. + these args will only be used if download from google drive. + details of the args of it: + https://github.com/wkentaro/gdown/blob/main/gdown/download.py + + Raises: + RuntimeError: When the hash validation of the ``filepath`` existing file fails. + RuntimeError: When a network issue or denied permission prevents the + file download from ``url`` to ``filepath``. + URLError: See urllib.request.urlretrieve. + HTTPError: See urllib.request.urlretrieve. + ContentTooShortError: See urllib.request.urlretrieve. + IOError: See urllib.request.urlretrieve. + RuntimeError: When the hash validation of the ``url`` downloaded file fails. + + """ + if not filepath: + filepath = Path(".", _basename(url)).resolve() + logger.info(f"Default downloading to '{filepath}'") + filepath = Path(filepath) + if filepath.exists(): + if not check_hash(filepath, hash_val, hash_type): + raise RuntimeError( + f"{hash_type} check of existing file failed: filepath={filepath}, expected {hash_type}={hash_val}." + ) + logger.info(f"File exists: {filepath}, skipped downloading.") + return + try: + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_name = Path(tmp_dir, _basename(filepath)) + if urlparse(url).netloc == "drive.google.com": + if not has_gdown: + raise RuntimeError("To download files from Google Drive, please install the gdown dependency.") + if "fuzzy" not in gdown_kwargs: + gdown_kwargs["fuzzy"] = True # default to true for flexible url + gdown.download(url, f"{tmp_name}", quiet=not progress, **gdown_kwargs) + elif urlparse(url).netloc == "cloud-api.yandex.net": + with urlopen(url) as response: + code = response.getcode() + if code == 200: + download_url = json.load(response)["href"] + _download_with_progress(download_url, tmp_name, progress=progress) + else: + raise RuntimeError( + f"Download of file from {download_url}, received from {url} " + + f" to {filepath} failed due to network issue or denied permission." + ) + else: + _download_with_progress(url, tmp_name, progress=progress) + if not tmp_name.exists(): + raise RuntimeError( + f"Download of file from {url} to {filepath} failed due to network issue or denied permission." + ) + file_dir = filepath.parent + if file_dir: + os.makedirs(file_dir, exist_ok=True) + shutil.move(f"{tmp_name}", f"{filepath}") # copy the downloaded to a user-specified cache. + except (PermissionError, NotADirectoryError): # project-monai/monai issue #3613 #3757 for windows + pass + logger.info(f"Downloaded: {filepath}") + if not check_hash(filepath, hash_val, hash_type): + raise RuntimeError( + f"{hash_type} check of downloaded file failed: URL={url}, " + f"filepath={filepath}, expected {hash_type}={hash_val}." + ) + + +def extractall( + filepath: PathLike, + output_dir: PathLike = ".", + hash_val: str | None = None, + hash_type: str = "md5", + file_type: str = "", + has_base: bool = True, +) -> None: + """ + Extract file to the output directory. + Expected file types are: `zip`, `tar.gz` and `tar`. + + Args: + filepath: the file path of compressed file. + output_dir: target directory to save extracted files. + hash_val: expected hash value to validate the compressed file. + if None, skip hash validation. + hash_type: 'md5' or 'sha1', defaults to 'md5'. + file_type: string of file type for decompressing. Leave it empty to infer the type from the filepath basename. + has_base: whether the extracted files have a base folder. This flag is used when checking if the existing + folder is a result of `extractall`, if it is, the extraction is skipped. For example, if A.zip is unzipped + to folder structure `A/*.png`, this flag should be True; if B.zip is unzipped to `*.png`, this flag should + be False. + + Raises: + RuntimeError: When the hash validation of the ``filepath`` compressed file fails. + NotImplementedError: When the ``filepath`` file extension is not one of [zip", "tar.gz", "tar"]. + + """ + if has_base: + # the extracted files will be in this folder + cache_dir = Path(output_dir, _basename(filepath).split(".")[0]) + else: + cache_dir = Path(output_dir) + if cache_dir.exists() and next(cache_dir.iterdir(), None) is not None: + logger.info(f"Non-empty folder exists in {cache_dir}, skipped extracting.") + return + filepath = Path(filepath) + if hash_val and not check_hash(filepath, hash_val, hash_type): + raise RuntimeError( + f"{hash_type} check of compressed file failed: " f"filepath={filepath}, expected {hash_type}={hash_val}." + ) + logger.info(f"Writing into directory: {output_dir}.") + _file_type = file_type.lower().strip() + if filepath.name.endswith("zip") or _file_type == "zip": + zip_file = zipfile.ZipFile(filepath) + zip_file.extractall(output_dir) + zip_file.close() + return + if filepath.name.endswith("tar") or filepath.name.endswith("tar.gz") or "tar" in _file_type: + tar_file = tarfile.open(filepath) + tar_file.extractall(output_dir) + tar_file.close() + return + raise NotImplementedError( + f'Unsupported file type, available options are: ["zip", "tar.gz", "tar"]. name={filepath} type={file_type}.' + ) + + +def download_and_extract( + url: str, + filepath: PathLike = "", + output_dir: PathLike = ".", + hash_val: str | None = None, + hash_type: str = "md5", + file_type: str = "", + has_base: bool = True, + progress: bool = True, +) -> None: + """ + Download file from URL and extract it to the output directory. + + Args: + url: source URL link to download file. + filepath: the file path of the downloaded compressed file. + use this option to keep the directly downloaded compressed file, to avoid further repeated downloads. + output_dir: target directory to save extracted files. + default is the current directory. + hash_val: expected hash value to validate the downloaded file. + if None, skip hash validation. + hash_type: 'md5' or 'sha1', defaults to 'md5'. + file_type: string of file type for decompressing. Leave it empty to infer the type from url's base file name. + has_base: whether the extracted files have a base folder. This flag is used when checking if the existing + folder is a result of `extractall`, if it is, the extraction is skipped. For example, if A.zip is unzipped + to folder structure `A/*.png`, this flag should be True; if B.zip is unzipped to `*.png`, this flag should + be False. + progress: whether to display progress bar. + """ + with tempfile.TemporaryDirectory() as tmp_dir: + filename = filepath or Path(tmp_dir, _basename(url)).resolve() + download_url(url=url, filepath=filename, hash_val=hash_val, hash_type=hash_type, progress=progress) + extractall(filepath=filename, output_dir=output_dir, file_type=file_type, has_base=has_base) diff --git a/source_code/SegMamba/monai/auto3dseg/__init__.py b/source_code/SegMamba/monai/auto3dseg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5d15613bdb49707fe3dceebcea069df49bfcac --- /dev/null +++ b/source_code/SegMamba/monai/auto3dseg/__init__.py @@ -0,0 +1,37 @@ +# 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 .algo_gen import Algo, AlgoGen +from .analyzer import ( + Analyzer, + FgImageStats, + FgImageStatsSumm, + FilenameStats, + ImageStats, + ImageStatsSumm, + LabelStats, + LabelStatsSumm, +) +from .operations import Operations, SampleOperations, SummaryOperations +from .seg_summarizer import SegSummarizer +from .utils import ( + algo_from_pickle, + algo_to_pickle, + concat_multikeys_to_dict, + concat_val_to_np, + datafold_read, + get_foreground_image, + get_foreground_label, + get_label_ccp, + verify_report_format, +) diff --git a/source_code/SegMamba/monai/auto3dseg/algo_gen.py b/source_code/SegMamba/monai/auto3dseg/algo_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..38ac542cff6d3532f55cca24960af1e898c487fb --- /dev/null +++ b/source_code/SegMamba/monai/auto3dseg/algo_gen.py @@ -0,0 +1,107 @@ +# 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 monai.config import PathLike +from monai.transforms import Randomizable + + +class Algo: + """ + An algorithm in this context is loosely defined as a data processing pipeline consisting of multiple components + such as image preprocessing, followed by deep learning model training and evaluation. + """ + + template_path: PathLike | None = None + + def set_data_stats(self, *args, **kwargs): + """Provide dataset (and summaries) so that the model creation can depend on the input datasets.""" + pass + + def train(self, *args, **kwargs): + """Read training/validation data and output a model.""" + pass + + def predict(self, *args, **kwargs): + """Read test data and output model predictions.""" + pass + + def get_score(self, *args, **kwargs): + """Returns the model quality measurement based on training and validation datasets.""" + pass + + def get_output_path(self, *args, **kwargs): + """Returns the algo output paths for scripts location""" + pass + + +class AlgoGen(Randomizable): + """ + A data-driven algorithm generator. It optionally takes the following inputs: + + - training dataset properties (such as data statistics from ``monai.auto3dseg.analyzer``), + - previous algorithm's scores measuring the model quality, + - computational budgets, + + and generates ``Algo`` instances. The generated algos are to be trained with the training datasets:: + + scores + +------------------------+ + | +---------+ | + +-----------+ +-->| | +-----+----+ + | Dataset, | | AlgoGen |--->| Algo | + | summaries |------>| | +----------+ + +-----+-----+ +---------+ ^ + | | + +----------------------------------+ + + This class also maintains a history of previously generated Algo and their corresponding validation scores. + The Algo generation process may be stochastic (using ``Randomizable.R`` as the source random state). + """ + + def set_data_stats(self, *args, **kwargs): # type ignore + """Provide dataset summaries/properties so that the generator can be conditioned on the input datasets.""" + pass + + def set_budget(self, *args, **kwargs): + """Provide computational budget so that the generator outputs algorithms that requires reasonable resources.""" + pass + + def set_score(self, *args, **kwargs): + """Feedback from the previously generated algo, the score can be used for new Algo generations.""" + pass + + def get_data_stats(self, *args, **kwargs): + """Get current dataset summaries.""" + pass + + def get_budget(self, *args, **kwargs): + """Get the current computational budget.""" + pass + + def get_history(self, *args, **kwargs): + """Get the previously generated algo.""" + pass + + def generate(self): + """Generate new Algo -- based on data_stats, budget, and history of previous algo generations.""" + pass + + def run_algo(self, *args, **kwargs): + """ + Launch the Algos. This is useful for light-weight Algos where there's no need to distribute the training jobs. + + If the generated Algos require significant scheduling of parallel executions, a job scheduler/controller + implemented separately is preferred to run them. In this case the controller should also report back the + scores and the algo history, so that the future ``AlgoGen.generate`` can leverage the information. + """ + pass diff --git a/source_code/SegMamba/monai/auto3dseg/analyzer.py b/source_code/SegMamba/monai/auto3dseg/analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..37f3faea2151d6500d7f88af78288f2ee431265e --- /dev/null +++ b/source_code/SegMamba/monai/auto3dseg/analyzer.py @@ -0,0 +1,1038 @@ +# 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 time +from abc import ABC, abstractmethod +from collections.abc import Hashable, Mapping +from copy import deepcopy +from typing import Any + +import numpy as np +import torch + +from monai.apps.utils import get_logger +from monai.auto3dseg.operations import Operations, SampleOperations, SummaryOperations +from monai.auto3dseg.utils import ( + concat_multikeys_to_dict, + concat_val_to_np, + get_foreground_image, + get_foreground_label, + get_label_ccp, + verify_report_format, +) +from monai.bundle.config_parser import ConfigParser +from monai.bundle.utils import ID_SEP_KEY +from monai.data import MetaTensor, affine_to_spacing +from monai.transforms.transform import MapTransform +from monai.transforms.utils_pytorch_numpy_unification import sum, unique +from monai.utils import convert_to_numpy +from monai.utils.enums import DataStatsKeys, ImageStatsKeys, LabelStatsKeys +from monai.utils.misc import ImageMetaKey, label_union + +logger = get_logger(module_name=__name__) + +__all__ = [ + "Analyzer", + "ImageStats", + "FgImageStats", + "LabelStats", + "ImageStatsSumm", + "FgImageStatsSumm", + "LabelStatsSumm", + "FilenameStats", + "ImageHistogram", + "ImageHistogramSumm", +] + + +class Analyzer(MapTransform, ABC): + """ + The Analyzer component is a base class. Other classes inherit this class will provide a callable + with the same class name and produces one pre-formatted dictionary for the input data. The format + is pre-defined by the init function of the class that inherit this base class. Function operations + can also be registered before the runtime of the callable. + + Args: + report_format: a dictionary that outlines the key structures of the report format. + + """ + + def __init__(self, stats_name: str, report_format: dict) -> None: + super().__init__(None) + parser = ConfigParser(report_format, globals=False) # ConfigParser.globals not picklable + self.report_format = parser.get("") + self.stats_name = stats_name + self.ops = ConfigParser({}, globals=False) + + def update_ops(self, key: str, op: Operations) -> None: + """ + Register a statistical operation to the Analyzer and update the report_format. + + Args: + key: value key in the report. + op: Operation sub-class object that represents statistical operations. + + """ + self.ops[key] = op + parser = ConfigParser(self.report_format) + + if parser.get(key, "None") != "None": + parser[key] = op + + self.report_format = parser.get("") + + def update_ops_nested_label(self, nested_key: str, op: Operations) -> None: + """ + Update operations for nested label format. Operation value in report_format will be resolved + to a dict with only keys. + + Args: + nested_key: str that has format of 'key1#0#key2'. + op: Operation sub-class object that represents statistical operations. + """ + keys = nested_key.split(ID_SEP_KEY) + if len(keys) != 3: + raise ValueError("Nested_key input format is wrong. Please ensure it is like key1#0#key2") + root: str + child_key: str + (root, _, child_key) = keys + if root not in self.ops: + self.ops[root] = [{}] + self.ops[root][0].update({child_key: None}) + + self.ops[nested_key] = op + + parser = ConfigParser(self.report_format) + if parser.get(nested_key, "NA") != "NA": + parser[nested_key] = op + + def get_report_format(self) -> dict: + """ + Get the report format by resolving the registered operations recursively. + + Returns: + a dictionary with {keys: None} pairs. + + """ + self.resolve_format(self.report_format) + return self.report_format # type: ignore[no-any-return] + + @staticmethod + def unwrap_ops(func): + """ + Unwrap a function value and generates the same set keys in a dict when the function is actually + called in runtime + + Args: + func: Operation sub-class object that represents statistical operations. The func object + should have a `data` dictionary which stores the statistical operation information. + For some operations (ImageStats for example), it may also contain the data_addon + property, which is part of the update process. + + Returns: + a dict with a set of keys. + + """ + ret = dict.fromkeys(list(func.data)) + if hasattr(func, "data_addon"): + for key in func.data_addon: + ret.update({key: None}) + return ret + + def resolve_format(self, report: dict) -> None: + """ + Resolve the format of the pre-defined report. + + Args: + report: the dictionary to resolve. Values will be replaced in-place. + + """ + for k, v in report.items(): + if isinstance(v, Operations): + report[k] = self.unwrap_ops(v) + elif isinstance(v, list) and len(v) > 0: + self.resolve_format(v[0]) + else: + report[k] = v + + @abstractmethod + def __call__(self, data: Any) -> dict: + """Analyze the dict format dataset, return the summary report""" + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + +class ImageStats(Analyzer): + """ + Analyzer to extract image stats properties for each case(image). + + Args: + image_key: the key to find image data in the callable function input (data) + + Examples: + + .. code-block:: python + + import numpy as np + from monai.auto3dseg import ImageStats + from monai.data import MetaTensor + + input = {} + input['image'] = np.random.rand(1,30,30,30) + input['image'] = MetaTensor(np.random.rand(1,30,30,30)) # MetaTensor + analyzer = ImageStats(image_key="image") + print(analyzer(input)["image_stats"]) + + Notes: + if the image data is NumPy array, the spacing stats will be [1.0] * `ndims` of the array, + where the `ndims` is the lesser value between the image dimension and 3. + + """ + + def __init__(self, image_key: str, stats_name: str = DataStatsKeys.IMAGE_STATS) -> None: + if not isinstance(image_key, str): + raise ValueError("image_key input must be str") + + self.image_key = image_key + + report_format = { + ImageStatsKeys.SHAPE: None, + ImageStatsKeys.CHANNELS: None, + ImageStatsKeys.CROPPED_SHAPE: None, + ImageStatsKeys.SPACING: None, + ImageStatsKeys.SIZEMM: None, + ImageStatsKeys.INTENSITY: None, + } + + super().__init__(stats_name, report_format) + self.update_ops(ImageStatsKeys.INTENSITY, SampleOperations()) + + def __call__(self, data): + """ + Callable to execute the pre-defined functions + + Returns: + A dictionary. The dict has the key in self.report_format. The value of + ImageStatsKeys.INTENSITY is in a list format. Each element of the value list + has stats pre-defined by SampleOperations (max, min, ....). + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Note: + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + + """ + d = dict(data) + start = time.time() + restore_grad_state = torch.is_grad_enabled() + torch.set_grad_enabled(False) + + ndas = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])] + if "nda_croppeds" not in d: + nda_croppeds = [get_foreground_image(nda) for nda in ndas] + + # perform calculation + report = deepcopy(self.get_report_format()) + + report[ImageStatsKeys.SHAPE] = [list(nda.shape) for nda in ndas] + report[ImageStatsKeys.CHANNELS] = len(ndas) + report[ImageStatsKeys.CROPPED_SHAPE] = [list(nda_c.shape) for nda_c in nda_croppeds] + report[ImageStatsKeys.SPACING] = ( + affine_to_spacing(data[self.image_key].affine).tolist() + if isinstance(data[self.image_key], MetaTensor) + else [1.0] * min(3, data[self.image_key].ndim) + ) + + report[ImageStatsKeys.SIZEMM] = [ + a * b for a, b in zip(report[ImageStatsKeys.SHAPE][0], report[ImageStatsKeys.SPACING]) + ] + + report[ImageStatsKeys.INTENSITY] = [ + self.ops[ImageStatsKeys.INTENSITY].evaluate(nda_c) for nda_c in nda_croppeds + ] + + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + + d[self.stats_name] = report + + torch.set_grad_enabled(restore_grad_state) + logger.debug(f"Get image stats spent {time.time()-start}") + return d + + +class FgImageStats(Analyzer): + """ + Analyzer to extract foreground label properties for each case(image and label). + + Args: + image_key: the key to find image data in the callable function input (data) + label_key: the key to find label data in the callable function input (data) + + Examples: + + .. code-block:: python + + import numpy as np + from monai.auto3dseg import FgImageStats + + input = {} + input['image'] = np.random.rand(1,30,30,30) + input['label'] = np.ones([30,30,30]) + analyzer = FgImageStats(image_key='image', label_key='label') + print(analyzer(input)["image_foreground_stats"]) + + """ + + def __init__(self, image_key: str, label_key: str, stats_name: str = DataStatsKeys.FG_IMAGE_STATS): + self.image_key = image_key + self.label_key = label_key + + report_format = {ImageStatsKeys.INTENSITY: None} + + super().__init__(stats_name, report_format) + self.update_ops(ImageStatsKeys.INTENSITY, SampleOperations()) + + def __call__(self, data: Mapping) -> dict: + """ + Callable to execute the pre-defined functions + + Returns: + A dictionary. The dict has the key in self.report_format and value + in a list format. Each element of the value list has stats pre-defined + by SampleOperations (max, min, ....). + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Note: + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + """ + + d = dict(data) + start = time.time() + restore_grad_state = torch.is_grad_enabled() + torch.set_grad_enabled(False) + + ndas = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])] + ndas_label = d[self.label_key] # (H,W,D) + + if ndas_label.shape != ndas[0].shape: + raise ValueError(f"Label shape {ndas_label.shape} is different from image shape {ndas[0].shape}") + + nda_foregrounds = [get_foreground_label(nda, ndas_label) for nda in ndas] + nda_foregrounds = [nda if nda.numel() > 0 else MetaTensor([0.0]) for nda in nda_foregrounds] + + # perform calculation + report = deepcopy(self.get_report_format()) + + report[ImageStatsKeys.INTENSITY] = [ + self.ops[ImageStatsKeys.INTENSITY].evaluate(nda_f) for nda_f in nda_foregrounds + ] + + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + + d[self.stats_name] = report + + torch.set_grad_enabled(restore_grad_state) + logger.debug(f"Get foreground image stats spent {time.time()-start}") + return d + + +class LabelStats(Analyzer): + """ + Analyzer to extract label stats properties for each case(image and label). + + Args: + image_key: the key to find image data in the callable function input (data) + label_key: the key to find label data in the callable function input (data) + do_ccp: performs connected component analysis. Default is True. + + Examples: + + .. code-block:: python + + import numpy as np + from monai.auto3dseg import LabelStats + + input = {} + input['image'] = np.random.rand(1,30,30,30) + input['label'] = np.ones([30,30,30]) + analyzer = LabelStats(image_key='image', label_key='label') + print(analyzer(input)["label_stats"]) + + """ + + def __init__( + self, image_key: str, label_key: str, stats_name: str = DataStatsKeys.LABEL_STATS, do_ccp: bool | None = True + ): + self.image_key = image_key + self.label_key = label_key + self.do_ccp = do_ccp + + report_format: dict[LabelStatsKeys, Any] = { + LabelStatsKeys.LABEL_UID: None, + LabelStatsKeys.IMAGE_INTST: None, + LabelStatsKeys.LABEL: [{LabelStatsKeys.PIXEL_PCT: None, LabelStatsKeys.IMAGE_INTST: None}], + } + + if self.do_ccp: + report_format[LabelStatsKeys.LABEL][0].update( + {LabelStatsKeys.LABEL_SHAPE: None, LabelStatsKeys.LABEL_NCOMP: None} + ) + + super().__init__(stats_name, report_format) + self.update_ops(LabelStatsKeys.IMAGE_INTST, SampleOperations()) + + id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.IMAGE_INTST]) + self.update_ops_nested_label(id_seq, SampleOperations()) + + def __call__(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTensor | dict]: + """ + Callable to execute the pre-defined functions. + + Returns: + A dictionary. The dict has the key in self.report_format and value + in a list format. Each element of the value list has stats pre-defined + by SampleOperations (max, min, ....). + + Examples: + output dict contains { + LabelStatsKeys.LABEL_UID:[0,1,3], + LabelStatsKeys.IMAGE_INTST: {...}, + LabelStatsKeys.LABEL:[ + { + LabelStatsKeys.PIXEL_PCT: 0.8, + LabelStatsKeys.IMAGE_INTST: {...}, + LabelStatsKeys.LABEL_SHAPE: [...], + LabelStatsKeys.LABEL_NCOMP: 1 + } + { + LabelStatsKeys.PIXEL_PCT: 0.1, + LabelStatsKeys.IMAGE_INTST: {...}, + LabelStatsKeys.LABEL_SHAPE: [...], + LabelStatsKeys.LABEL_NCOMP: 1 + } + { + LabelStatsKeys.PIXEL_PCT: 0.1, + LabelStatsKeys.IMAGE_INTST: {...}, + LabelStatsKeys.LABEL_SHAPE: [...], + LabelStatsKeys.LABEL_NCOMP: 1 + } + ] + } + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Notes: + The label class_ID of the dictionary in LabelStatsKeys.LABEL IS NOT the + index. Instead, the class_ID is the LabelStatsKeys.LABEL_UID with the same + index. For instance, the last dict in LabelStatsKeys.LABEL in the Examples + is 3, which is the last element under LabelStatsKeys.LABEL_UID. + + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + """ + d: dict[Hashable, MetaTensor] = dict(data) + start = time.time() + if isinstance(d[self.image_key], (torch.Tensor, MetaTensor)) and d[self.image_key].device.type == "cuda": + using_cuda = True + else: + using_cuda = False + restore_grad_state = torch.is_grad_enabled() + torch.set_grad_enabled(False) + + ndas: list[MetaTensor] = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])] # type: ignore + ndas_label: MetaTensor = d[self.label_key].astype(torch.int16) # (H,W,D) + + if ndas_label.shape != ndas[0].shape: + raise ValueError(f"Label shape {ndas_label.shape} is different from image shape {ndas[0].shape}") + + nda_foregrounds: list[torch.Tensor] = [get_foreground_label(nda, ndas_label) for nda in ndas] + nda_foregrounds = [nda if nda.numel() > 0 else torch.Tensor([0]) for nda in nda_foregrounds] + + unique_label = unique(ndas_label) + if isinstance(ndas_label, (MetaTensor, torch.Tensor)): + unique_label = unique_label.data.cpu().numpy() + + unique_label = unique_label.astype(np.int16).tolist() + + label_substats = [] # each element is one label + pixel_sum = 0 + pixel_arr = [] + for index in unique_label: + start_label = time.time() + label_dict: dict[str, Any] = {} + mask_index = ndas_label == index + + nda_masks = [nda[mask_index] for nda in ndas] + label_dict[LabelStatsKeys.IMAGE_INTST] = [ + self.ops[LabelStatsKeys.IMAGE_INTST].evaluate(nda_m) for nda_m in nda_masks + ] + + pixel_count = sum(mask_index) + pixel_arr.append(pixel_count) + pixel_sum += pixel_count + if self.do_ccp: # apply connected component + if using_cuda: + # The back end of get_label_ccp is CuPy + # which is unable to automatically release CUDA GPU memory held by PyTorch + del nda_masks + torch.cuda.empty_cache() + shape_list, ncomponents = get_label_ccp(mask_index) + label_dict[LabelStatsKeys.LABEL_SHAPE] = shape_list + label_dict[LabelStatsKeys.LABEL_NCOMP] = ncomponents + + label_substats.append(label_dict) + logger.debug(f" label {index} stats takes {time.time() - start_label}") + + for i, _ in enumerate(unique_label): + label_substats[i].update({LabelStatsKeys.PIXEL_PCT: float(pixel_arr[i] / pixel_sum)}) + + report = deepcopy(self.get_report_format()) + report[LabelStatsKeys.LABEL_UID] = unique_label + report[LabelStatsKeys.IMAGE_INTST] = [ + self.ops[LabelStatsKeys.IMAGE_INTST].evaluate(nda_f) for nda_f in nda_foregrounds + ] + report[LabelStatsKeys.LABEL] = label_substats + + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + + d[self.stats_name] = report # type: ignore[assignment] + + torch.set_grad_enabled(restore_grad_state) + logger.debug(f"Get label stats spent {time.time()-start}") + return d # type: ignore[return-value] + + +class ImageStatsSumm(Analyzer): + """ + This summary analyzer processes the values of specific key `stats_name` in a list of dict. + Typically, the list of dict is the output of case analyzer under the same prefix + (ImageStats). + + Args: + stats_name: the key of the to-process value in the dict. + average: whether to average the statistical value across different image modalities. + + """ + + def __init__(self, stats_name: str = DataStatsKeys.IMAGE_STATS, average: bool | None = True): + self.summary_average = average + report_format = { + ImageStatsKeys.SHAPE: None, + ImageStatsKeys.CHANNELS: None, + ImageStatsKeys.CROPPED_SHAPE: None, + ImageStatsKeys.SPACING: None, + ImageStatsKeys.SIZEMM: None, + ImageStatsKeys.INTENSITY: None, + } + super().__init__(stats_name, report_format) + + self.update_ops(ImageStatsKeys.SHAPE, SampleOperations()) + self.update_ops(ImageStatsKeys.CHANNELS, SampleOperations()) + self.update_ops(ImageStatsKeys.CROPPED_SHAPE, SampleOperations()) + self.update_ops(ImageStatsKeys.SPACING, SampleOperations()) + self.update_ops(ImageStatsKeys.SIZEMM, SampleOperations()) + self.update_ops(ImageStatsKeys.INTENSITY, SummaryOperations()) + + def __call__(self, data: list[dict]) -> dict: + """ + Callable to execute the pre-defined functions + + Returns: + A dictionary. The dict has the key in self.report_format and value + in a list format. Each element of the value list has stats pre-defined + by SampleOperations (max, min, ....). + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Examples: + output dict contains a dictionary for all of the following keys{ + ImageStatsKeys.SHAPE:{...} + ImageStatsKeys.CHANNELS: {...}, + ImageStatsKeys.CROPPED_SHAPE: {...}, + ImageStatsKeys.SPACING: {...}, + ImageStatsKeys.SIZEMM: {...}, + ImageStatsKeys.INTENSITY: {...}, + } + + Notes: + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + """ + if not isinstance(data, list): + raise ValueError(f"Callable {self.__class__} requires list inputs") + + if len(data) == 0: + raise ValueError(f"Callable {self.__class__} input list is empty") + + if self.stats_name not in data[0]: + raise KeyError(f"{self.stats_name} is not in input data") + + report = deepcopy(self.get_report_format()) + + for k in [ + ImageStatsKeys.SHAPE, + ImageStatsKeys.CHANNELS, + ImageStatsKeys.CROPPED_SHAPE, + ImageStatsKeys.SPACING, + ImageStatsKeys.SIZEMM, + ]: + v_np = concat_val_to_np(data, [self.stats_name, k]) + report[k] = self.ops[k].evaluate(v_np, dim=(0, 1) if v_np.ndim > 2 and self.summary_average else 0) + + intst_str = ImageStatsKeys.INTENSITY + op_keys = report[intst_str].keys() # template, max/min/... + intst_dict = concat_multikeys_to_dict(data, [self.stats_name, intst_str], op_keys) + report[intst_str] = self.ops[intst_str].evaluate(intst_dict, dim=None if self.summary_average else 0) + + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + + return report + + +class FgImageStatsSumm(Analyzer): + """ + This summary analyzer processes the values of specific key `stats_name` in a list of + dict. Typically, the list of dict is the output of case analyzer under the similar name + (FgImageStats). + + Args: + stats_name: the key of the to-process value in the dict. + average: whether to average the statistical value across different image modalities. + + """ + + def __init__(self, stats_name: str = DataStatsKeys.FG_IMAGE_STATS, average: bool | None = True): + self.summary_average = average + + report_format = {ImageStatsKeys.INTENSITY: None} + super().__init__(stats_name, report_format) + self.update_ops(ImageStatsKeys.INTENSITY, SummaryOperations()) + + def __call__(self, data: list[dict]) -> dict: + """ + Callable to execute the pre-defined functions. + + Returns: + A dictionary. The dict has the key in self.report_format and value + in a list format. Each element of the value list has stats pre-defined + by SampleOperations (max, min, ....) and SummaryOperation (max of the + max, mean of the mean, etc). + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Examples: + output dict contains a dictionary for all of the following keys{ + ImageStatsKeys.INTENSITY: {...}, + } + + Notes: + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + """ + if not isinstance(data, list): + raise ValueError(f"Callable {self.__class__} requires list inputs") + + if len(data) == 0: + raise ValueError(f"Callable {self.__class__} input list is empty") + + if self.stats_name not in data[0]: + raise KeyError(f"{self.stats_name} is not in input data.") + + report = deepcopy(self.get_report_format()) + intst_str = ImageStatsKeys.INTENSITY + op_keys = report[intst_str].keys() # template, max/min/... + intst_dict = concat_multikeys_to_dict(data, [self.stats_name, intst_str], op_keys) + + report[intst_str] = self.ops[intst_str].evaluate(intst_dict, dim=None if self.summary_average else 0) + + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + + return report + + +class LabelStatsSumm(Analyzer): + """ + This summary analyzer processes the values of specific key `stats_name` in a list of + dict. Typically, the list of dict is the output of case analyzer under the similar name + (LabelStats). + + Args: + stats_name: the key of the to-process value in the dict. + average: whether to average the statistical value across different image modalities. + + """ + + def __init__( + self, stats_name: str = DataStatsKeys.LABEL_STATS, average: bool | None = True, do_ccp: bool | None = True + ): + self.summary_average = average + self.do_ccp = do_ccp + + report_format: dict[str, Any] = { + LabelStatsKeys.LABEL_UID: None, + LabelStatsKeys.IMAGE_INTST: None, + LabelStatsKeys.LABEL: [{LabelStatsKeys.PIXEL_PCT: None, LabelStatsKeys.IMAGE_INTST: None}], + } + if self.do_ccp: + report_format[LabelStatsKeys.LABEL][0].update( + {LabelStatsKeys.LABEL_SHAPE: None, LabelStatsKeys.LABEL_NCOMP: None} + ) + + super().__init__(stats_name, report_format) + self.update_ops(LabelStatsKeys.IMAGE_INTST, SummaryOperations()) + + # label-0-'pixel percentage' + id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.PIXEL_PCT]) + self.update_ops_nested_label(id_seq, SampleOperations()) + # label-0-'image intensity' + id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.IMAGE_INTST]) + self.update_ops_nested_label(id_seq, SummaryOperations()) + # label-0-shape + id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.LABEL_SHAPE]) + self.update_ops_nested_label(id_seq, SampleOperations()) + # label-0-ncomponents + id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.LABEL_NCOMP]) + self.update_ops_nested_label(id_seq, SampleOperations()) + + def __call__(self, data: list[dict]) -> dict: + """ + Callable to execute the pre-defined functions + + Returns: + A dictionary. The dict has the key in self.report_format and value + in a list format. Each element of the value list has stats pre-defined + by SampleOperations (max, min, ....) and SummaryOperation (max of the + max, mean of the mean, etc). + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Notes: + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + """ + if not isinstance(data, list): + raise ValueError(f"Callable {self.__class__} requires list inputs") + + if len(data) == 0: + raise ValueError(f"Callable {self.__class__} input list is empty") + + if self.stats_name not in data[0]: + raise KeyError(f"{self.stats_name} is not in input data") + + report = deepcopy(self.get_report_format()) + # unique class ID + uid_np = concat_val_to_np(data, [self.stats_name, LabelStatsKeys.LABEL_UID], axis=None, ragged=True) + unique_label = label_union(uid_np) + report[LabelStatsKeys.LABEL_UID] = unique_label + + # image intensity + intst_str = LabelStatsKeys.IMAGE_INTST + op_keys = report[intst_str].keys() # template, max/min/... + intst_dict = concat_multikeys_to_dict(data, [self.stats_name, intst_str], op_keys) + report[intst_str] = self.ops[intst_str].evaluate(intst_dict, dim=None if self.summary_average else 0) + + detailed_label_list = [] + # iterate through each label + label_str = LabelStatsKeys.LABEL + for label_id in unique_label: + stats = {} + + pct_str = LabelStatsKeys.PIXEL_PCT + pct_fixed_keys = [self.stats_name, label_str, label_id, pct_str] + pct_np = concat_val_to_np(data, pct_fixed_keys, allow_missing=True) + stats[pct_str] = self.ops[label_str][0][pct_str].evaluate( + pct_np, dim=(0, 1) if pct_np.ndim > 2 and self.summary_average else 0 + ) + + if self.do_ccp: + ncomp_str = LabelStatsKeys.LABEL_NCOMP + ncomp_fixed_keys = [self.stats_name, LabelStatsKeys.LABEL, label_id, ncomp_str] + ncomp_np = concat_val_to_np(data, ncomp_fixed_keys, allow_missing=True) + stats[ncomp_str] = self.ops[label_str][0][ncomp_str].evaluate( + ncomp_np, dim=(0, 1) if ncomp_np.ndim > 2 and self.summary_average else 0 + ) + + shape_str = LabelStatsKeys.LABEL_SHAPE + shape_fixed_keys = [self.stats_name, label_str, label_id, LabelStatsKeys.LABEL_SHAPE] + shape_np = concat_val_to_np(data, shape_fixed_keys, ragged=True, allow_missing=True) + stats[shape_str] = self.ops[label_str][0][shape_str].evaluate( + shape_np, dim=(0, 1) if shape_np.ndim > 2 and self.summary_average else 0 + ) + # label shape is a 3-element value, but the number of labels in each image + # can vary from 0 to N. So the value in a list format is "ragged" + + intst_str = LabelStatsKeys.IMAGE_INTST + intst_fixed_keys = [self.stats_name, label_str, label_id, intst_str] + op_keys = report[label_str][0][intst_str].keys() + intst_dict = concat_multikeys_to_dict(data, intst_fixed_keys, op_keys, allow_missing=True) + stats[intst_str] = self.ops[label_str][0][intst_str].evaluate( + intst_dict, dim=None if self.summary_average else 0 + ) + + detailed_label_list.append(stats) + + report[LabelStatsKeys.LABEL] = detailed_label_list + + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + + return report + + +class FilenameStats(Analyzer): + """ + This class finds the file path for the loaded image/label and writes the info + into the data pipeline as a monai transforms. + + Args: + key: the key to fetch the filename (for example, "image", "label"). + stats_name: the key to store the filename in the output stats report. + + """ + + def __init__(self, key: str | None, stats_name: str) -> None: + self.key = key + super().__init__(stats_name, {}) + + def __call__(self, data): + d = dict(data) + + if self.key: # when there is no (label) file, key can be None + if self.key not in d: # check whether image/label is in the data + raise ValueError(f"Data with key {self.key} is missing.") + if not isinstance(d[self.key], MetaTensor): + raise ValueError(f"Value type of {self.key} is not MetaTensor.") + if ImageMetaKey.FILENAME_OR_OBJ not in d[self.key].meta: + raise ValueError(f"{ImageMetaKey.FILENAME_OR_OBJ} not found in MetaTensor {d[self.key]}.") + d[self.stats_name] = d[self.key].meta[ImageMetaKey.FILENAME_OR_OBJ] + else: + d[self.stats_name] = "None" + + return d + + +class ImageHistogram(Analyzer): + """ + Analyzer to compute intensity histogram. + + Args: + image_key: the key to find image data in the callable function input (data) + hist_bins: list of positive integers (one for each channel) for setting the number of bins used to + compute the histogram. Defaults to [100]. + hist_range: list of lists of two floats (one for each channel) setting the intensity range to + compute the histogram. Defaults to [-500, 500]. + + Examples: + + .. code-block:: python + + import numpy as np + from monai.auto3dseg.analyzer import ImageHistogram + + input = {} + input['image'] = np.random.rand(1,30,30,30) + input['label'] = np.ones([30,30,30]) + analyzer = ImageHistogram(image_key='image') + print(analyzer(input)) + + """ + + def __init__( + self, + image_key: str, + stats_name: str = DataStatsKeys.IMAGE_HISTOGRAM, + hist_bins: list[int] | int | None = None, + hist_range: list | None = None, + ): + self.image_key = image_key + + # set defaults + self.hist_bins: list[int] = ( + [100] if hist_bins is None else hist_bins if isinstance(hist_bins, list) else [hist_bins] + ) + self.hist_range: list = [-500, 500] if hist_range is None else hist_range + + report_format = {"counts": None, "bin_edges": None} + + super().__init__(stats_name, report_format) + self.update_ops(ImageStatsKeys.HISTOGRAM, SampleOperations()) + + # check histogram configurations for each channel in list + if not all(isinstance(hr, list) for hr in self.hist_range): + self.hist_range = [self.hist_range] + if len(self.hist_bins) != len(self.hist_range): + raise ValueError( + f"Number of histogram bins ({len(self.hist_bins)}) and " + f"histogram ranges ({len(self.hist_range)}) need to be the same!" + ) + for i, hist_params in enumerate(zip(self.hist_bins, self.hist_range)): + _hist_bins, _hist_range = hist_params + if not isinstance(_hist_bins, int) or _hist_bins < 0: + raise ValueError(f"Expected {i+1}. hist_bins value to be positive integer but got {_hist_bins}") + if not isinstance(_hist_range, list) or len(_hist_range) != 2: + raise ValueError(f"Expected {i+1}. hist_range values to be list of length 2 but received {_hist_range}") + + def __call__(self, data: dict) -> dict: + """ + Callable to execute the pre-defined functions + + Returns: + A dictionary. The dict has the key in self.report_format and value + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Note: + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + """ + + d = dict(data) + + ndas = convert_to_numpy(d[self.image_key], wrap_sequence=True) # (1,H,W,D) or (C,H,W,D) + nr_channels = np.shape(ndas)[0] + + # adjust histogram params to match channels + if len(self.hist_bins) == 1: + self.hist_bins = nr_channels * self.hist_bins + if len(self.hist_bins) != nr_channels: + raise ValueError( + f"There is a mismatch between the number of channels ({nr_channels}) " + f"and number histogram bins ({len(self.hist_bins)})." + ) + if len(self.hist_range) == 1: + self.hist_range = nr_channels * self.hist_range + if len(self.hist_range) != nr_channels: + raise ValueError( + f"There is a mismatch between the number of channels ({nr_channels}) " + f"and histogram ranges ({len(self.hist_range)})." + ) + + # perform calculation + reports = [] + for channel in range(nr_channels): + counts, bin_edges = np.histogram( + ndas[channel, ...], + bins=self.hist_bins[channel], + range=(self.hist_range[channel][0], self.hist_range[channel][1]), + ) + _report = {"counts": counts.tolist(), "bin_edges": bin_edges.tolist()} + if not verify_report_format(_report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + reports.append(_report) + + d[self.stats_name] = reports + return d + + +class ImageHistogramSumm(Analyzer): + """ + This summary analyzer processes the values of specific key `stats_name` in a list of dict. + Typically, the list of dict is the output of case analyzer under the same prefix + (ImageHistogram). + + Args: + stats_name: the key of the to-process value in the dict. + average: whether to average the statistical value across different image modalities. + + """ + + def __init__(self, stats_name: str = DataStatsKeys.IMAGE_HISTOGRAM, average: bool | None = True): + self.summary_average = average + report_format = {ImageStatsKeys.HISTOGRAM: None} + super().__init__(stats_name, report_format) + + self.update_ops(ImageStatsKeys.HISTOGRAM, SummaryOperations()) + + def __call__(self, data: list[dict]) -> dict: + """ + Callable to execute the pre-defined functions + + Returns: + A dictionary. The dict has the key in self.report_format and value + in a list format. Each element of the value list has stats pre-defined + by SampleOperations (max, min, ....). + + Raises: + RuntimeError if the stats report generated is not consistent with the pre- + defined report_format. + + Examples: + output dict contains a dictionary for all of the following keys{ + ImageStatsKeys.SHAPE:{...} + ImageStatsKeys.CHANNELS: {...}, + ImageStatsKeys.CROPPED_SHAPE: {...}, + ImageStatsKeys.SPACING: {...}, + ImageStatsKeys.SIZEMM: {...}, + ImageStatsKeys.INTENSITY: {...}, + } + + Notes: + The stats operation uses numpy and torch to compute max, min, and other + functions. If the input has nan/inf, the stats results will be nan/inf. + """ + if not isinstance(data, list): + raise ValueError(f"Callable {self.__class__} requires list inputs") + + if len(data) == 0: + raise ValueError(f"Callable {self.__class__} input list is empty") + + if self.stats_name not in data[0]: + raise KeyError(f"{self.stats_name} is not in input data") + + summ_histogram: dict = {} + + for d in data: + if not summ_histogram: + summ_histogram = d[DataStatsKeys.IMAGE_HISTOGRAM] + # convert to numpy for computing total histogram + for k in range(len(summ_histogram)): + summ_histogram[k]["counts"] = np.array(summ_histogram[k]["counts"]) + else: + for k in range(len(summ_histogram)): + summ_histogram[k]["counts"] += np.array(d[DataStatsKeys.IMAGE_HISTOGRAM][k]["counts"]) + if np.all(summ_histogram[k]["bin_edges"] != d[DataStatsKeys.IMAGE_HISTOGRAM][k]["bin_edges"]): + raise ValueError( + f"bin edges are not consistent! {summ_histogram[k]['bin_edges']} vs. " + f"{d[DataStatsKeys.IMAGE_HISTOGRAM][k]['bin_edges']}" + ) + + # convert back to list + for k in range(len(summ_histogram)): + summ_histogram[k]["counts"] = summ_histogram[k]["counts"].tolist() + + report = {ImageStatsKeys.HISTOGRAM: summ_histogram} + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + + return report diff --git a/source_code/SegMamba/monai/auto3dseg/operations.py b/source_code/SegMamba/monai/auto3dseg/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..404a6d326ee633b4f3d55425a987d405f4382697 --- /dev/null +++ b/source_code/SegMamba/monai/auto3dseg/operations.py @@ -0,0 +1,152 @@ +# 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 import UserDict +from functools import partial +from typing import Any + +from monai.transforms.utils_pytorch_numpy_unification import max, mean, median, min, percentile, std + +__all__ = ["Operations", "SampleOperations", "SummaryOperations"] + + +class Operations(UserDict): + """ + Base class of operation interface + """ + + def evaluate(self, data: Any, **kwargs: Any) -> dict: + """ + For key-value pairs in the self.data, if the value is a callable, + then this function will apply the callable to the input data. + The result will be written under the same key under the output dict. + + Args: + data: input data. + + Returns: + a dictionary which has same keys as the self.data if the value + is callable. + """ + return {k: v(data, **kwargs) for k, v in self.data.items() if callable(v)} + + +class SampleOperations(Operations): + """ + Apply statistical operation to a sample (image/ndarray/tensor). + + Notes: + Percentile operation uses a partial function that embeds different kwargs (q). + In order to print the result nicely, data_addon is added to map the numbers + generated by percentile to different keys ("percentile_00_5" for example). + Annotation of the postfix means the percentage for percentile computation. + For example, _00_5 means 0.5% and _99_5 means 99.5%. + + Example: + + .. code-block:: python + + # use the existing operations + import numpy as np + op = SampleOperations() + data_np = np.random.rand(10, 10).astype(np.float64) + print(op.evaluate(data_np)) + + # add a new operation + op.update({"sum": np.sum}) + print(op.evaluate(data_np)) + """ + + def __init__(self) -> None: + self.data = { + "max": max, + "mean": mean, + "median": median, + "min": min, + "stdev": std, + "percentile": partial(percentile, q=[0.5, 10, 90, 99.5]), + } + self.data_addon = { + "percentile_00_5": ("percentile", 0), + "percentile_10_0": ("percentile", 1), + "percentile_90_0": ("percentile", 2), + "percentile_99_5": ("percentile", 3), + } + + def evaluate(self, data: Any, **kwargs: Any) -> dict: + """ + Applies the callables to the data, and convert the + numerics to list or Python numeric types (int/float). + + Args: + data: input data + """ + ret = super().evaluate(data, **kwargs) + for k, v in self.data_addon.items(): + cache = v[0] + idx = v[1] + if isinstance(v, tuple) and cache in ret: + ret.update({k: ret[cache][idx]}) + + for k, v in ret.items(): + ret[k] = v.tolist() # type: ignore + return ret + + +class SummaryOperations(Operations): + """ + Apply statistical operation to summarize a dict. The key-value looks like: {"max", "min" + ,"mean", ....}. The value may contain multiple values in a list format. Then this operation + will apply the operation to the list. Typically, the dict is generated by multiple + `SampleOperation` and `concat_multikeys_to_dict` functions. + + Examples: + + .. code-block:: python + + import numpy as np + data = { + "min": np.random.rand(4), + "max": np.random.rand(4), + "mean": np.random.rand(4), + "sum": np.random.rand(4), + } + op = SummaryOperations() + print(op.evaluate(data)) # "sum" is not registered yet, so it won't contain "sum" + + op.update({"sum", np.sum}) + print(op.evaluate(data)) # output has "sum" + """ + + def __init__(self) -> None: + self.data = { + "max": max, + "mean": mean, + "median": mean, + "min": min, + "stdev": mean, + "percentile_00_5": mean, + "percentile_10_0": mean, + "percentile_90_0": mean, + "percentile_99_5": mean, + } + + def evaluate(self, data: Any, **kwargs: Any) -> dict: + """ + Applies the callables to the data, and convert the numerics to list or Python + numeric types (int/float). + + Args: + data: input data + """ + return {k: v(data[k], **kwargs).tolist() for k, v in self.data.items() if (callable(v) and k in data)} diff --git a/source_code/SegMamba/monai/auto3dseg/seg_summarizer.py b/source_code/SegMamba/monai/auto3dseg/seg_summarizer.py new file mode 100644 index 0000000000000000000000000000000000000000..14a10635df2f226f83d0719d5b402841ea672cf1 --- /dev/null +++ b/source_code/SegMamba/monai/auto3dseg/seg_summarizer.py @@ -0,0 +1,213 @@ +# 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 typing import Any + +from monai.auto3dseg.analyzer import ( + Analyzer, + FgImageStats, + FgImageStatsSumm, + FilenameStats, + ImageHistogram, + ImageHistogramSumm, + ImageStats, + ImageStatsSumm, + LabelStats, + LabelStatsSumm, +) +from monai.transforms import Compose +from monai.utils.enums import DataStatsKeys + +__all__ = ["SegSummarizer"] + + +class SegSummarizer(Compose): + """ + SegSummarizer serializes the operations for data analysis in Auto3Dseg pipeline. It loads + two types of analyzer functions and execute differently. The first type of analyzer is + CaseAnalyzer which is similar to traditional monai transforms. It can be composed with other + transforms to process the data dict which has image/label keys. The second type of analyzer + is SummaryAnalyzer which works only on a list of dictionary. Each dictionary is the output + of the case analyzers on a single dataset. + + Args: + 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 None, the DataAnalyzer + will skip looking for labels and all label-related operations. + do_ccp: apply the connected component algorithm to process the labels/images. + hist_bins: list of positive integers (one for each channel) for setting the number of bins used to + compute the histogram. Defaults to [100]. + hist_range: list of lists of two floats (one for each channel) setting the intensity range to + compute the histogram. Defaults to [-500, 500]. + histogram_only: whether to only compute histograms. Defaults to False. + + Examples: + .. code-block:: python + + # imports + + summarizer = SegSummarizer("image", "label") + transform_list = [ + LoadImaged(keys=keys), + EnsureChannelFirstd(keys=keys), # this creates label to be (1,H,W,D) + ToDeviced(keys=keys, device=device, non_blocking=True), + Orientationd(keys=keys, axcodes="RAS"), + EnsureTyped(keys=keys, data_type="tensor"), + Lambdad(keys="label", func=lambda x: torch.argmax(x, dim=0, keepdim=True) if x.shape[0] > 1 else x), + SqueezeDimd(keys=["label"], dim=0), + summarizer, + ] + ... + # skip some steps to set up data loader + dataset = data.DataLoader(ds, batch_size=1, shuffle=False, num_workers=n_workers, collate_fn=no_collation) + transform = Compose(transform_list) + stats = [] + for batch_data in dataset: + d = transform(batch_data[0]) + stats.append(d) + report = summarizer.summarize(stats) + """ + + def __init__( + self, + image_key: str, + label_key: str | None, + average: bool = True, + do_ccp: bool = True, + hist_bins: list[int] | int | None = None, + hist_range: list | None = None, + histogram_only: bool = False, + ) -> None: + self.image_key = image_key + self.label_key = label_key + # set defaults + self.hist_bins: list[int] | int = [100] if hist_bins is None else hist_bins + self.hist_range: list = [-500, 500] if hist_range is None else hist_range + self.histogram_only = histogram_only + + self.summary_analyzers: list[Any] = [] + super().__init__() + + self.add_analyzer(FilenameStats(image_key, DataStatsKeys.BY_CASE_IMAGE_PATH), None) + self.add_analyzer(FilenameStats(label_key, DataStatsKeys.BY_CASE_LABEL_PATH), None) + if not self.histogram_only: + self.add_analyzer(ImageStats(image_key), ImageStatsSumm(average=average)) + + if label_key is None: + return + + self.add_analyzer(FgImageStats(image_key, label_key), FgImageStatsSumm(average=average)) + + self.add_analyzer( + LabelStats(image_key, label_key, do_ccp=do_ccp), LabelStatsSumm(average=average, do_ccp=do_ccp) + ) + + # compute histograms + if self.hist_bins != 0: + self.add_analyzer( + ImageHistogram(image_key=image_key, hist_bins=hist_bins, hist_range=hist_range), ImageHistogramSumm() + ) + + def add_analyzer(self, case_analyzer: Analyzer, summary_analyzer: Analyzer | None) -> None: + """ + Add new analyzers to the engine so that the callable and summarize functions will + utilize the new analyzers for stats computations. + + Args: + case_analyzer: analyzer that works on each data. + summary_analyzer: analyzer that works on list of stats dict (output from case_analyzers). + + Examples: + + .. code-block:: python + + from monai.auto3dseg import Analyzer + from monai.auto3dseg.utils import concat_val_to_np + from monai.auto3dseg.analyzer_engine import SegSummarizer + + class UserAnalyzer(Analyzer): + def __init__(self, image_key="image", stats_name="user_stats"): + self.image_key = image_key + report_format = {"ndims": None} + super().__init__(stats_name, report_format) + + def __call__(self, data): + d = dict(data) + report = deepcopy(self.get_report_format()) + report["ndims"] = d[self.image_key].ndim + d[self.stats_name] = report + return d + + class UserSummaryAnalyzer(Analyzer): + def __init__(stats_name="user_stats"): + report_format = {"ndims": None} + super().__init__(stats_name, report_format) + self.update_ops("ndims", SampleOperations()) + + def __call__(self, data): + report = deepcopy(self.get_report_format()) + v_np = concat_val_to_np(data, [self.stats_name, "ndims"]) + report["ndims"] = self.ops["ndims"].evaluate(v_np) + return report + + summarizer = SegSummarizer() + summarizer.add_analyzer(UserAnalyzer, UserSummaryAnalyzer) + + """ + self.transforms += (case_analyzer,) + if summary_analyzer is not None: + self.summary_analyzers.append(summary_analyzer) + + def summarize(self, data: list[dict]) -> dict[str, dict]: + """ + Summarize the input list of data and generates a report ready for json/yaml export. + + Args: + data: a list of data dicts. + + Returns: + a dict that summarizes the stats across data samples. + + Examples: + stats_summary: + image_foreground_stats: + intensity: {...} + image_stats: + channels: {...} + cropped_shape: {...} + ... + label_stats: + image_intensity: {...} + label: + - image_intensity: {...} + - image_intensity: {...} + - image_intensity: {...} + - image_intensity: {...} + """ + if not isinstance(data, list): + raise ValueError(f"{self.__class__} summarize function needs input to be a list of dict") + + report: dict[str, dict] = {} + if len(data) == 0: + return report + + if not isinstance(data[0], dict): + raise ValueError(f"{self.__class__} summarize function needs a list of dict. Now we have {type(data[0])}") + + for analyzer in self.summary_analyzers: + if callable(analyzer): + report.update({analyzer.stats_name: analyzer(data)}) + + return report diff --git a/source_code/SegMamba/monai/auto3dseg/utils.py b/source_code/SegMamba/monai/auto3dseg/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..58b900d410c1d83c2eb49b9bb4f3b42b3ad45762 --- /dev/null +++ b/source_code/SegMamba/monai/auto3dseg/utils.py @@ -0,0 +1,524 @@ +# 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 +import pickle +import subprocess +import sys +from copy import deepcopy +from numbers import Number +from typing import Any, cast + +import numpy as np +import torch + +from monai.auto3dseg import Algo +from monai.bundle.config_parser import ConfigParser +from monai.bundle.utils import ID_SEP_KEY +from monai.config import PathLike +from monai.data.meta_tensor import MetaTensor +from monai.transforms import CropForeground, ToCupy +from monai.utils import min_version, optional_import, run_cmd + +__all__ = [ + "get_foreground_image", + "get_foreground_label", + "get_label_ccp", + "concat_val_to_np", + "concat_multikeys_to_dict", + "datafold_read", + "verify_report_format", + "algo_to_pickle", + "algo_from_pickle", +] + +measure_np, has_measure = optional_import("skimage.measure", "0.14.2", min_version) +cp, has_cp = optional_import("cupy") + + +def get_foreground_image(image: MetaTensor) -> np.ndarray: + """ + Get a foreground image by removing all-zero rectangles on the edges of the image + Note for the developer: update select_fn if the foreground is defined differently. + + Args: + image: ndarray image to segment. + + Returns: + ndarray of foreground image by removing all-zero edges. + + Notes: + the size of the output is smaller than the input. + """ + + copper = CropForeground(select_fn=lambda x: x > 0, allow_smaller=True) + image_foreground = copper(image) + return cast(np.ndarray, image_foreground) + + +def get_foreground_label(image: MetaTensor, label: MetaTensor) -> MetaTensor: + """ + Get foreground image pixel values and mask out the non-labeled area. + + Args + image: ndarray image to segment. + label: ndarray the image input and annotated with class IDs. + + Returns: + 1D array of foreground image with label > 0 + """ + + label_foreground = MetaTensor(image[label > 0]) + return label_foreground + + +def get_label_ccp(mask_index: MetaTensor, use_gpu: bool = True) -> tuple[list[Any], int]: + """ + Find all connected components and their bounding shape. Backend can be cuPy/cuCIM or Numpy + depending on the hardware. + + Args: + mask_index: a binary mask. + use_gpu: a switch to use GPU/CUDA or not. If GPU is unavailable, CPU will be used + regardless of this setting. + + """ + skimage, has_cucim = optional_import("cucim.skimage") + shape_list = [] + if mask_index.device.type == "cuda" and has_cp and has_cucim and use_gpu: + mask_cupy = ToCupy()(mask_index.short()) + labeled = skimage.measure.label(mask_cupy) + vals = cp.unique(labeled[cp.nonzero(labeled)]) + + for ncomp in vals: + comp_idx = cp.argwhere(labeled == ncomp) + comp_idx_min = cp.min(comp_idx, axis=0).tolist() + comp_idx_max = cp.max(comp_idx, axis=0).tolist() + bbox_shape = [comp_idx_max[i] - comp_idx_min[i] + 1 for i in range(len(comp_idx_max))] + shape_list.append(bbox_shape) + ncomponents = len(vals) + + del mask_cupy, labeled, vals, comp_idx, ncomp + cp.get_default_memory_pool().free_all_blocks() + + elif has_measure: + labeled, ncomponents = measure_np.label(mask_index.data.cpu().numpy(), background=-1, return_num=True) + for ncomp in range(1, ncomponents + 1): + comp_idx = np.argwhere(labeled == ncomp) + comp_idx_min = np.min(comp_idx, axis=0).tolist() + comp_idx_max = np.max(comp_idx, axis=0).tolist() + bbox_shape = [comp_idx_max[i] - comp_idx_min[i] + 1 for i in range(len(comp_idx_max))] + shape_list.append(bbox_shape) + else: + raise RuntimeError("Cannot find one of the following required dependencies: {cuPy+cuCIM} or {scikit-image}") + + return shape_list, ncomponents + + +def concat_val_to_np( + data_list: list[dict], + fixed_keys: list[str | int], + ragged: bool | None = False, + allow_missing: bool | None = False, + **kwargs: Any, +) -> np.ndarray: + """ + Get the nested value in a list of dictionary that shares the same structure. + + Args: + data_list: a list of dictionary {key1: {key2: np.ndarray}}. + fixed_keys: a list of keys that records to path to the value in the dict elements. + ragged: if True, numbers can be in list of lists or ragged format so concat mode needs change. + allow_missing: if True, it will return a None if the value cannot be found. + + Returns: + nd.array of concatenated array. + + """ + + np_list: list[np.ndarray | None] = [] + for data in data_list: + parser = ConfigParser(data) + for i, key in enumerate(fixed_keys): + fixed_keys[i] = str(key) + + val: Any + val = parser.get(ID_SEP_KEY.join(fixed_keys)) # type: ignore + + if val is None: + if allow_missing: + np_list.append(None) + else: + raise AttributeError(f"{fixed_keys} is not nested in the dictionary") + elif isinstance(val, list): + np_list.append(np.array(val)) + elif isinstance(val, (torch.Tensor, MetaTensor)): + np_list.append(val.cpu().numpy()) + elif isinstance(val, np.ndarray): + np_list.append(val) + elif isinstance(val, Number): + np_list.append(np.array(val)) + else: + raise NotImplementedError(f"{val.__class__} concat is not supported.") + + if allow_missing: + np_list = [x for x in np_list if x is not None] + + if len(np_list) == 0: + return np.array([0]) + elif ragged: + return np.concatenate(np_list, **kwargs) # type: ignore + else: + return np.concatenate([np_list], **kwargs) + + +def concat_multikeys_to_dict( + data_list: list[dict], fixed_keys: list[str | int], keys: list[str], zero_insert: bool = True, **kwargs: Any +) -> dict[str, np.ndarray]: + """ + Get the nested value in a list of dictionary that shares the same structure iteratively on all keys. + It returns a dictionary with keys with the found values in nd.ndarray. + + Args: + data_list: a list of dictionary {key1: {key2: np.ndarray}}. + fixed_keys: a list of keys that records to path to the value in the dict elements. + keys: a list of string keys that will be iterated to generate a dict output. + zero_insert: insert a zero in the list so that it can find the value in element 0 before getting the keys + flatten: if True, numbers are flattened before concat. + + Returns: + a dict with keys - nd.array of concatenated array pair. + """ + + ret_dict = {} + for key in keys: + addon: list[str | int] = [0, key] if zero_insert else [key] + val = concat_val_to_np(data_list, fixed_keys + addon, **kwargs) + ret_dict.update({key: val}) + + return ret_dict + + +def datafold_read(datalist: str | dict, basedir: str, fold: int = 0, key: str = "training") -> tuple[list, list]: + """ + Read a list of data dictionary `datalist` + + Args: + datalist: the name of a JSON file listing the data, or a dictionary. + basedir: directory of image files. + fold: which fold to use (0..1 if in training set). + key: usually 'training' , but can try 'validation' or 'testing' to get the list data without labels (used in challenges). + + Returns: + A tuple of two arrays (training, validation). + """ + + if isinstance(datalist, str): + json_data = ConfigParser.load_config_file(datalist) + else: + json_data = datalist + + dict_data = deepcopy(json_data[key]) + + for d in dict_data: + for k, _ in d.items(): + if isinstance(d[k], list): + d[k] = [os.path.join(basedir, iv) for iv in d[k]] + elif isinstance(d[k], str): + d[k] = os.path.join(basedir, d[k]) if len(d[k]) > 0 else d[k] + + tr = [] + val = [] + for d in dict_data: + if "fold" in d and d["fold"] == fold: + val.append(d) + else: + tr.append(d) + + return tr, val + + +def verify_report_format(report: dict, report_format: dict) -> bool: + """ + Compares the report and the report_format that has only keys. + + Args: + report: dict that has real values. + report_format: dict that only has keys and list-nested value. + """ + for k_fmt, v_fmt in report_format.items(): + if k_fmt not in report: + return False + + v = report[k_fmt] + + if isinstance(v_fmt, list) and isinstance(v, list): + if len(v_fmt) != 1: + raise UserWarning("list length in report_format is not 1") + if len(v_fmt) > 0 and len(v) > 0: + return verify_report_format(v[0], v_fmt[0]) + else: + return False + + return True + + +def algo_to_pickle(algo: Algo, template_path: PathLike | None = None, **algo_meta_data: Any) -> str: + """ + Export the Algo object to pickle file. + + Args: + algo: Algo-like object. + template_path: a str path that is needed to be added to the sys.path to instantiate the class. + algo_meta_data: additional keyword to save into the dictionary, for example, model training info + such as acc/best_metrics + + Returns: + filename of the pickled Algo object + """ + data = {"algo_bytes": pickle.dumps(algo), "template_path": str(template_path)} + pkl_filename = os.path.join(algo.get_output_path(), "algo_object.pkl") + for k, v in algo_meta_data.items(): + data.update({k: v}) + data_bytes = pickle.dumps(data) + with open(pkl_filename, "wb") as f_pi: + f_pi.write(data_bytes) + return pkl_filename + + +def algo_from_pickle(pkl_filename: str, template_path: PathLike | None = None, **kwargs: Any) -> Any: + """ + Import the Algo object from a pickle file. + + Args: + pkl_filename: the name of the pickle file. + template_path: a folder containing files to instantiate the Algo. Besides the `template_path`, + this function will also attempt to use the `template_path` saved in the pickle file and a directory + named `algorithm_templates` in the parent folder of the folder containing the pickle file. + + Returns: + algo: the Algo object saved in the pickle file. + algo_meta_data: additional keyword saved in the pickle file, for example, acc/best_metrics. + + Raises: + ValueError if the pkl_filename does not contain a dict, or the dict does not contain `algo_bytes`. + ModuleNotFoundError if it is unable to instantiate the Algo class. + + """ + with open(pkl_filename, "rb") as f_pi: + data_bytes = f_pi.read() + data = pickle.loads(data_bytes) + + if not isinstance(data, dict): + raise ValueError(f"the data object is {data.__class__}. Dict is expected.") + + if "algo_bytes" not in data: + raise ValueError(f"key [algo_bytes] not found in {data}. Unable to instantiate.") + + algo_bytes = data.pop("algo_bytes") + algo_template_path = data.pop("template_path", None) + + template_paths_candidates: list[str] = [] + + if os.path.isdir(str(template_path)): + template_paths_candidates.append(os.path.abspath(str(template_path))) + template_paths_candidates.append(os.path.abspath(os.path.join(str(template_path), ".."))) + + if os.path.isdir(str(algo_template_path)): + template_paths_candidates.append(os.path.abspath(algo_template_path)) + template_paths_candidates.append(os.path.abspath(os.path.join(algo_template_path, ".."))) + + pkl_dir = os.path.dirname(pkl_filename) + algo_template_path_fuzzy = os.path.join(pkl_dir, "..", "algorithm_templates") + + if os.path.isdir(algo_template_path_fuzzy): + template_paths_candidates.append(os.path.abspath(algo_template_path_fuzzy)) + + if len(template_paths_candidates) == 0: + # no template_path provided or needed + algo = pickle.loads(algo_bytes) + algo.template_path = None + else: + for i, p in enumerate(template_paths_candidates): + try: + sys.path.append(p) + algo = pickle.loads(algo_bytes) + break + except ModuleNotFoundError as not_found_err: + logging.debug(f"Folder {p} doesn't contain the Algo templates for Algo instantiation.") + sys.path.pop() + if i == len(template_paths_candidates) - 1: + raise ValueError( + f"Failed to instantiate {pkl_filename} with {template_paths_candidates}" + ) from not_found_err + algo.template_path = p + + if os.path.abspath(pkl_dir) != os.path.abspath(algo.get_output_path()): + logging.debug(f"{algo.get_output_path()} is changed. Now override the Algo output_path with: {pkl_dir}.") + algo.output_path = pkl_dir + + algo_meta_data = {} + for k, v in data.items(): + algo_meta_data.update({k: v}) + + return algo, algo_meta_data + + +def list_to_python_fire_arg_str(args: list) -> str: + """ + Convert a list of arguments to a string that can be used in python-fire. + + Args: + args: the list of arguments. + + Returns: + the string that can be used in python-fire. + """ + args_str = ",".join([str(arg) for arg in args]) + return f"'{args_str}'" + + +def check_and_set_optional_args(params: dict) -> str: + """convert `params` into '--key_1=value_1 --key_2=value_2 ...'""" + cmd_mod_opt = "" + for k, v in params.items(): + if isinstance(v, dict): + raise ValueError("Nested dict is not supported.") + elif isinstance(v, list): + v = list_to_python_fire_arg_str(v) + cmd_mod_opt += f" --{k}={v}" + return cmd_mod_opt + + +def _prepare_cmd_default(cmd: str, cmd_prefix: str | None = None, **kwargs: Any) -> str: + """ + Prepare the command for subprocess to run the script with the given arguments. + + Args: + cmd: the command or script to run in the distributed job. + cmd_prefix: the command prefix to run the script, e.g., "python", "python -m", "python3", "/opt/conda/bin/python3.8 ". + kwargs: the keyword arguments to be passed to the script. + + Returns: + the command to run with ``subprocess``. + + Examples: + To prepare a subprocess command + "python train.py run -k --config 'a,b'", the function can be called as + - _prepare_cmd_default("train.py run -k", config=['a','b']) + - _prepare_cmd_default("train.py run -k --config 'a,b'") + + """ + params = kwargs.copy() + + if not cmd_prefix or "None" in cmd_prefix: # defaulting to 'python' + cmd_prefix = "python" + + if not cmd_prefix.endswith(" "): + cmd_prefix += " " # ensure a space after the command prefix so that the script can be appended + + return cmd_prefix + cmd + check_and_set_optional_args(params) + + +def _prepare_cmd_torchrun(cmd: str, **kwargs: Any) -> str: + """ + Prepare the command for multi-gpu/multi-node job execution using torchrun. + + Args: + cmd: the command or script to run in the distributed job. + kwargs: the keyword arguments to be passed to the script. + + Returns: + the command to append to ``torchrun`` + + Examples: + For command "torchrun --nnodes=1 --nproc_per_node=8 train.py run -k --config 'a,b'", + it only prepares command after the torchrun arguments, i.e., "train.py run -k --config 'a,b'". + The function can be called as + - _prepare_cmd_torchrun("train.py run -k", config=['a','b']) + - _prepare_cmd_torchrun("train.py run -k --config 'a,b'") + """ + params = kwargs.copy() + return cmd + check_and_set_optional_args(params) + + +def _prepare_cmd_bcprun(cmd: str, cmd_prefix: str | None = None, **kwargs: Any) -> str: + """ + Prepare the command for distributed job running using bcprun. + + Args: + script: the script to run in the distributed job. + cmd_prefix: the command prefix to run the script, e.g., "python". + kwargs: the keyword arguments to be passed to the script. + + Returns: + The command to run the script in the distributed job. + + Examples: + For command "bcprun -n 2 -p 8 -c python train.py run -k --config 'a,b'", + it only prepares command after the bcprun arguments, i.e., "train.py run -k --config 'a,b'". + the function can be called as + - _prepare_cmd_bcprun("train.py run -k", config=['a','b'], n=2, p=8) + - _prepare_cmd_bcprun("train.py run -k --config 'a,b'", n=2, p=8) + """ + + return _prepare_cmd_default(cmd, cmd_prefix=cmd_prefix, **kwargs) + + +def _run_cmd_torchrun(cmd: str, **kwargs: Any) -> subprocess.CompletedProcess: + """ + Run the command with torchrun. + + Args: + cmd: the command to run. Typically it is prepared by ``_prepare_cmd_torchrun``. + kwargs: the keyword arguments to be passed to the ``torchrun``. + + Return: + the return code of the subprocess command. + """ + params = kwargs.copy() + + cmd_list = cmd.split() + + # append arguments to the command list + torchrun_list = ["torchrun"] + required_args = ["nnodes", "nproc_per_node"] + for arg in required_args: + if arg not in params: + raise ValueError(f"Missing required argument {arg} for torchrun.") + torchrun_list += [f"--{arg}", str(params.pop(arg))] + torchrun_list += cmd_list + return run_cmd(torchrun_list, run_cmd_verbose=True, **params) + + +def _run_cmd_bcprun(cmd: str, **kwargs: Any) -> subprocess.CompletedProcess: + """ + Run the command with bcprun. + + Args: + cmd: the command to run. Typically it is prepared by ``_prepare_cmd_bcprun``. + kwargs: the keyword arguments to be passed to the ``bcprun``. + + Returns: + the return code of the subprocess command. + """ + params = kwargs.copy() + cmd_list = ["bcprun"] + required_args = ["n", "p"] + for arg in required_args: + if arg not in params: + raise ValueError(f"Missing required argument {arg} for bcprun.") + cmd_list += [f"-{arg}", str(params.pop(arg))] + cmd_list.extend(["-c", cmd]) + return run_cmd(cmd_list, run_cmd_verbose=True, **params) diff --git a/source_code/SegMamba/monai/bundle/__init__.py b/source_code/SegMamba/monai/bundle/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a2176f14a72958465f15abb8fdd036705d91d8 --- /dev/null +++ b/source_code/SegMamba/monai/bundle/__init__.py @@ -0,0 +1,46 @@ +# 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 .config_item import ComponentLocator, ConfigComponent, ConfigExpression, ConfigItem, Instantiable +from .config_parser import ConfigParser +from .properties import InferProperties, MetaProperties, TrainProperties +from .reference_resolver import ReferenceResolver +from .scripts import ( + ckpt_export, + create_workflow, + download, + download_large_files, + get_all_bundles_list, + get_bundle_info, + get_bundle_versions, + init_bundle, + load, + onnx_export, + push_to_hf_hub, + run, + run_workflow, + trt_export, + update_kwargs, + verify_metadata, + verify_net_in_out, +) +from .utils import ( + DEFAULT_EXP_MGMT_SETTINGS, + DEFAULT_MLFLOW_SETTINGS, + EXPR_KEY, + ID_REF_KEY, + ID_SEP_KEY, + MACRO_KEY, + load_bundle_config, +) +from .workflows import BundleWorkflow, ConfigWorkflow diff --git a/source_code/SegMamba/monai/bundle/__main__.py b/source_code/SegMamba/monai/bundle/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..778c9ef2f0cf93477150b6b7b1c25a96c32c6409 --- /dev/null +++ b/source_code/SegMamba/monai/bundle/__main__.py @@ -0,0 +1,31 @@ +# 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 monai.bundle.scripts import ( + ckpt_export, + download, + download_large_files, + init_bundle, + onnx_export, + run, + run_workflow, + trt_export, + verify_metadata, + verify_net_in_out, +) + +if __name__ == "__main__": + from monai.utils import optional_import + + fire, _ = optional_import("fire") + fire.Fire() diff --git a/source_code/SegMamba/monai/bundle/config_item.py b/source_code/SegMamba/monai/bundle/config_item.py new file mode 100644 index 0000000000000000000000000000000000000000..e5122bf3de3a0526a8c33925d78f2cc23d724cf2 --- /dev/null +++ b/source_code/SegMamba/monai/bundle/config_item.py @@ -0,0 +1,412 @@ +# 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 ast +import inspect +import sys +import warnings +from abc import ABC, abstractmethod +from collections.abc import Mapping, Sequence +from importlib import import_module +from pprint import pformat +from typing import Any + +from monai.bundle.utils import EXPR_KEY +from monai.utils import CompInitMode, ensure_tuple, first, instantiate, optional_import, run_debug, run_eval + +__all__ = ["ComponentLocator", "ConfigItem", "ConfigExpression", "ConfigComponent", "Instantiable"] + + +class Instantiable(ABC): + """ + Base class for an instantiable object. + """ + + @abstractmethod + def is_disabled(self, *args: Any, **kwargs: Any) -> bool: + """ + Return a boolean flag to indicate whether the object should be instantiated. + """ + raise NotImplementedError(f"subclass {self.__class__.__name__} must implement this method.") + + @abstractmethod + def instantiate(self, *args: Any, **kwargs: Any) -> object: + """ + Instantiate the target component and return the instance. + """ + raise NotImplementedError(f"subclass {self.__class__.__name__} must implement this method.") + + +class ComponentLocator: + """ + Scan all the available classes and functions in the MONAI package and map them with the module paths in a table. + It's used to locate the module path for provided component name. + + Args: + excludes: if any string of the `excludes` exists in the full module name, don't import this module. + + """ + + MOD_START = "monai" + + def __init__(self, excludes: Sequence[str] | str | None = None): + self.excludes = [] if excludes is None else ensure_tuple(excludes) + self._components_table: dict[str, list] | None = None + + def _find_module_names(self) -> list[str]: + """ + Find all the modules start with MOD_START and don't contain any of `excludes`. + + """ + return [m for m in sys.modules if m.startswith(self.MOD_START) and all(s not in m for s in self.excludes)] + + def _find_classes_or_functions(self, modnames: Sequence[str] | str) -> dict[str, list]: + """ + Find all the classes and functions in the modules with specified `modnames`. + + Args: + modnames: names of the target modules to find all the classes and functions. + + """ + table: dict[str, list] = {} + # all the MONAI modules are already loaded by `load_submodules` + for modname in ensure_tuple(modnames): + try: + # scan all the classes and functions in the module + module = import_module(modname) + for name, obj in inspect.getmembers(module): + if (inspect.isclass(obj) or inspect.isfunction(obj)) and obj.__module__ == modname: + if name not in table: + table[name] = [] + table[name].append(modname) + except ModuleNotFoundError: + pass + return table + + def get_component_module_name(self, name: str) -> list[str] | str | None: + """ + Get the full module name of the class or function with specified ``name``. + If target component name exists in multiple packages or modules, return a list of full module names. + + Args: + name: name of the expected class or function. + + """ + if not isinstance(name, str): + raise ValueError(f"`name` must be a valid string, but got: {name}.") + if self._components_table is None: + # init component and module mapping table + self._components_table = self._find_classes_or_functions(self._find_module_names()) + + mods: list[str] | str | None = self._components_table.get(name) + if isinstance(mods, list) and len(mods) == 1: + mods = mods[0] + return mods + + +class ConfigItem: + """ + Basic data structure to represent a configuration item. + + A `ConfigItem` instance can optionally have a string id, so that other items can refer to it. + It has a build-in `config` property to store the configuration object. + + Args: + config: content of a config item, can be objects of any types, + a configuration resolver may interpret the content to generate a configuration object. + id: name of the current config item, defaults to empty string. + + """ + + def __init__(self, config: Any, id: str = "") -> None: + self.config = config + self.id = id + + def get_id(self) -> str: + """ + Get the ID name of current config item, useful to identify config items during parsing. + + """ + return self.id + + def update_config(self, config: Any) -> None: + """ + Replace the content of `self.config` with new `config`. + A typical usage is to modify the initial config content at runtime. + + Args: + config: content of a `ConfigItem`. + + """ + self.config = config + + def get_config(self): + """ + Get the config content of current config item. + + """ + return self.config + + def __repr__(self) -> str: + return f"{type(self).__name__}: \n{pformat(self.config)}" + + +class ConfigComponent(ConfigItem, Instantiable): + """ + Subclass of :py:class:`monai.bundle.ConfigItem`, this class uses a dictionary with string keys to + represent a component of `class` or `function` and supports instantiation. + + Currently, three special keys (strings surrounded by ``_``) are defined and interpreted beyond the regular literals: + + - class or function identifier of the python module, specified by ``"_target_"``, + indicating a monai built-in Python class or function such as ``"LoadImageDict"``, + or a full module name, e.g. ``"monai.transforms.LoadImageDict"``, or a callable, e.g. ``"$@model.forward"``. + - ``"_requires_"`` (optional): specifies reference IDs (string starts with ``"@"``) or ``ConfigExpression`` + of the dependencies for this ``ConfigComponent`` object. These dependencies will be + evaluated/instantiated before this object is instantiated. It is useful when the + component doesn't explicitly depend on the other `ConfigItems` via its arguments, + but requires the dependencies to be instantiated/evaluated beforehand. + - ``"_disabled_"`` (optional): a flag to indicate whether to skip the instantiation. + - ``"_desc_"`` (optional): free text descriptions of the component for code readability. + - ``"_mode_"`` (optional): operating mode for invoking the callable ``component`` defined by ``"_target_"``: + + - ``"default"``: returns ``component(**kwargs)`` + - ``"callable"``: returns ``component`` or, if ``kwargs`` are provided, ``functools.partial(component, **kwargs)`` + - ``"debug"``: returns ``pdb.runcall(component, **kwargs)`` + + Other fields in the config content are input arguments to the python module. + + .. code-block:: python + + from monai.bundle import ComponentLocator, ConfigComponent + + locator = ComponentLocator(excludes=["modules_to_exclude"]) + config = { + "_target_": "LoadImaged", + "keys": ["image", "label"] + } + + configer = ConfigComponent(config, id="test", locator=locator) + image_loader = configer.instantiate() + print(image_loader) # + + Args: + config: content of a config item. + id: name of the current config item, defaults to empty string. + locator: a ``ComponentLocator`` to convert a module name string into the actual python module. + if `None`, a ``ComponentLocator(excludes=excludes)`` will be used. + excludes: if ``locator`` is None, create a new ``ComponentLocator`` with ``excludes``. + See also: :py:class:`monai.bundle.ComponentLocator`. + + """ + + non_arg_keys = {"_target_", "_disabled_", "_requires_", "_desc_", "_mode_"} + + def __init__( + self, + config: Any, + id: str = "", + locator: ComponentLocator | None = None, + excludes: Sequence[str] | str | None = None, + ) -> None: + super().__init__(config=config, id=id) + self.locator = ComponentLocator(excludes=excludes) if locator is None else locator + + @staticmethod + def is_instantiable(config: Any) -> bool: + """ + Check whether this config represents a `class` or `function` that is to be instantiated. + + Args: + config: input config content to check. + + """ + return isinstance(config, Mapping) and "_target_" in config + + def resolve_module_name(self): + """ + Resolve the target module name from current config content. + The config content must have ``"_target_"`` key. + + """ + config = dict(self.get_config()) + target = config.get("_target_") + if not isinstance(target, str): + return target # for feature discussed in project-monai/monai#5852 + + module = self.locator.get_component_module_name(target) + if module is None: + # target is the full module name, no need to parse + return target + + if isinstance(module, list): + warnings.warn( + f"there are more than 1 component have name `{target}`: {module}, use the first one `{module[0]}." + f" if want to use others, please set its full module path in `_target_` directly." + ) + module = module[0] + return f"{module}.{target}" + + def resolve_args(self): + """ + Utility function used in `instantiate()` to resolve the arguments from current config content. + + """ + return {k: v for k, v in self.get_config().items() if k not in self.non_arg_keys} + + def is_disabled(self) -> bool: + """ + Utility function used in `instantiate()` to check whether to skip the instantiation. + + """ + _is_disabled = self.get_config().get("_disabled_", False) + return _is_disabled.lower().strip() == "true" if isinstance(_is_disabled, str) else bool(_is_disabled) + + def instantiate(self, **kwargs: Any) -> object: + """ + Instantiate component based on ``self.config`` content. + The target component must be a `class` or a `function`, otherwise, return `None`. + + Args: + kwargs: args to override / add the config args when instantiation. + + """ + if not self.is_instantiable(self.get_config()) or self.is_disabled(): + # if not a class or function or marked as `disabled`, skip parsing and return `None` + return None + + modname = self.resolve_module_name() + mode = self.get_config().get("_mode_", CompInitMode.DEFAULT) + args = self.resolve_args() + args.update(kwargs) + return instantiate(modname, mode, **args) + + +class ConfigExpression(ConfigItem): + """ + Subclass of :py:class:`monai.bundle.ConfigItem`, the `ConfigItem` represents an executable expression + (execute based on ``eval()``, or import the module to the `globals` if it's an import statement). + + See also: + + - https://docs.python.org/3/library/functions.html#eval. + + For example: + + .. code-block:: python + + import monai + from monai.bundle import ConfigExpression + + config = "$monai.__version__" + expression = ConfigExpression(config, id="test", globals={"monai": monai}) + print(expression.evaluate()) + + Args: + config: content of a config item. + id: name of current config item, defaults to empty string. + globals: additional global context to evaluate the string. + + """ + + prefix = EXPR_KEY + run_eval = run_eval + + def __init__(self, config: Any, id: str = "", globals: dict | None = None) -> None: + super().__init__(config=config, id=id) + self.globals = globals if globals is not None else {} + + def _parse_import_string(self, import_string: str) -> Any | None: + """parse single import statement such as "from monai.transforms import Resize""" + node = first(ast.iter_child_nodes(ast.parse(import_string))) + if not isinstance(node, (ast.Import, ast.ImportFrom)): + return None + if len(node.names) < 1: + return None + if len(node.names) > 1: + warnings.warn(f"ignoring multiple import alias '{import_string}'.") + name, asname = f"{node.names[0].name}", node.names[0].asname + asname = name if asname is None else f"{asname}" + if isinstance(node, ast.ImportFrom): + self.globals[asname], _ = optional_import(f"{node.module}", name=f"{name}") + return self.globals[asname] + if isinstance(node, ast.Import): + self.globals[asname], _ = optional_import(f"{name}") + return self.globals[asname] + return None + + def evaluate(self, globals: dict | None = None, locals: dict | None = None) -> str | Any | None: + """ + Execute the current config content and return the result if it is expression, based on Python `eval()`. + For more details: https://docs.python.org/3/library/functions.html#eval. + + Args: + globals: besides ``self.globals``, other global symbols used in the expression at runtime. + locals: besides ``globals``, may also have some local symbols used in the expression at runtime. + + """ + value = self.get_config() + if not ConfigExpression.is_expression(value): + return None + optional_module = self._parse_import_string(value[len(self.prefix) :]) + if optional_module is not None: + return optional_module + if not self.run_eval: + return f"{value[len(self.prefix) :]}" + globals_ = dict(self.globals) + if globals is not None: + for k, v in globals.items(): + if k in globals_: + warnings.warn(f"the new global variable `{k}` conflicts with `self.globals`, override it.") + globals_[k] = v + if not run_debug: + try: + return eval(value[len(self.prefix) :], globals_, locals) + except Exception as e: + raise RuntimeError(f"Failed to evaluate {self}") from e + warnings.warn( + f"\n\npdb: value={value}\n" + f"See also Debugger commands documentation: https://docs.python.org/3/library/pdb.html\n" + ) + import pdb + + pdb.run(value[len(self.prefix) :], globals_, locals) + return None + + @classmethod + def is_expression(cls, config: dict | list | str) -> bool: + """ + Check whether the config is an executable expression string. + Currently, a string starts with ``"$"`` character is interpreted as an expression. + + Args: + config: input config content to check. + + """ + return isinstance(config, str) and config.startswith(cls.prefix) + + @classmethod + def is_import_statement(cls, config: dict | list | str) -> bool: + """ + Check whether the config is an import statement (a special case of expression). + + Args: + config: input config content to check. + """ + if not cls.is_expression(config): + return False + if "import" not in config: + return False + return isinstance( + first(ast.iter_child_nodes(ast.parse(f"{config[len(cls.prefix) :]}"))), (ast.Import, ast.ImportFrom) + ) diff --git a/source_code/SegMamba/monai/bundle/config_parser.py b/source_code/SegMamba/monai/bundle/config_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..829036af6ff6a280814fac379f0b7ba81434a60e --- /dev/null +++ b/source_code/SegMamba/monai/bundle/config_parser.py @@ -0,0 +1,508 @@ +# 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 re +from collections.abc import Sequence +from copy import deepcopy +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from monai.bundle.config_item import ComponentLocator, ConfigComponent, ConfigExpression, ConfigItem +from monai.bundle.reference_resolver import ReferenceResolver +from monai.bundle.utils import ID_REF_KEY, ID_SEP_KEY, MACRO_KEY +from monai.config import PathLike +from monai.utils import ensure_tuple, look_up_option, optional_import +from monai.utils.misc import CheckKeyDuplicatesYamlLoader, check_key_duplicates + +if TYPE_CHECKING: + import yaml +else: + yaml, _ = optional_import("yaml") + +__all__ = ["ConfigParser"] + +_default_globals = {"monai": "monai", "torch": "torch", "np": "numpy", "numpy": "numpy"} + + +class ConfigParser: + """ + The primary configuration parser. It traverses a structured config (in the form of nested Python dict or list), + creates ``ConfigItem``, and assign unique IDs according to the structures. + + This class provides convenient access to the set of ``ConfigItem`` of the config by ID. + A typical workflow of config parsing is as follows: + + - Initialize ``ConfigParser`` with the ``config`` source. + - Call ``get_parsed_content()`` to get expected component with `id`. + + .. code-block:: python + + from monai.bundle import ConfigParser + + config = { + "my_dims": 2, + "dims_1": "$@my_dims + 1", + "my_xform": {"_target_": "LoadImage"}, + "my_net": {"_target_": "BasicUNet", "spatial_dims": "@dims_1", "in_channels": 1, "out_channels": 4}, + "trainer": {"_target_": "SupervisedTrainer", "network": "@my_net", "preprocessing": "@my_xform"} + } + # in the example $@my_dims + 1 is an expression, which adds 1 to the value of @my_dims + parser = ConfigParser(config) + + # get/set configuration content, the set method should happen before calling parse() + print(parser["my_net"]["in_channels"]) # original input channels 1 + parser["my_net"]["in_channels"] = 4 # change input channels to 4 + print(parser["my_net"]["in_channels"]) + + # instantiate the network component + parser.parse(True) + net = parser.get_parsed_content("my_net", instantiate=True) + print(net) + + # also support to get the configuration content of parsed `ConfigItem` + trainer = parser.get_parsed_content("trainer", instantiate=False) + print(trainer) + + Args: + config: input config source to parse. + excludes: when importing modules to instantiate components, + excluding components from modules specified in ``excludes``. + globals: pre-import packages as global variables to ``ConfigExpression``, + so that expressions, for example, ``"$monai.data.list_data_collate"`` can use ``monai`` modules. + The current supported globals and alias names are + ``{"monai": "monai", "torch": "torch", "np": "numpy", "numpy": "numpy"}``. + These are MONAI's minimal dependencies. Additional packages could be included with `globals={"itk": "itk"}`. + Set it to ``False`` to disable `self.globals` module importing. + + See also: + + - :py:class:`monai.bundle.ConfigItem` + - :py:class:`monai.bundle.scripts.run` + + """ + + suffixes = ("json", "yaml", "yml") + suffix_match = rf".*\.({'|'.join(suffixes)})" + path_match = rf"({suffix_match}$)" + # match relative id names, e.g. "@#data", "@##transform#1" + relative_id_prefix = re.compile(rf"(?:{ID_REF_KEY}|{MACRO_KEY}){ID_SEP_KEY}+") + meta_key = "_meta_" # field key to save metadata + + def __init__( + self, + config: Any = None, + excludes: Sequence[str] | str | None = None, + globals: dict[str, Any] | None | bool = None, + ): + self.config: ConfigItem | None = None + self.globals: dict[str, Any] = {} + _globals = _default_globals.copy() + if isinstance(_globals, dict) and globals not in (None, False): + _globals.update(globals) # type: ignore + if _globals is not None and globals is not False: + for k, v in _globals.items(): + self.globals[k] = optional_import(v)[0] if isinstance(v, str) else v + + self.locator = ComponentLocator(excludes=excludes) + self.ref_resolver = ReferenceResolver() + if config is None: + config = {self.meta_key: {}} + self.set(config=config) + + def __repr__(self): + return f"{self.config}" + + def __getattr__(self, id): + """ + Get the parsed result of ``ConfigItem`` with the specified ``id`` + with default arguments (e.g. ``lazy=True``, ``instantiate=True`` and ``eval_expr=True``). + + Args: + id: id of the ``ConfigItem``. + + See also: + :py:meth:`get_parsed_content` + """ + return self.get_parsed_content(id) + + def __getitem__(self, id: str | int) -> Any: + """ + Get the config by id. + + Args: + id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to + go one level further into the nested structures. + Use digits indexing from "0" for list or other strings for dict. + For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``. + + """ + if id == "": + return self.config + config = self.config + for k in ReferenceResolver.split_id(id): + if not isinstance(config, (dict, list)): + raise ValueError(f"config must be dict or list for key `{k}`, but got {type(config)}: {config}.") + try: + config = ( + look_up_option(k, config, print_all_options=False) if isinstance(config, dict) else config[int(k)] + ) + except ValueError as e: + raise KeyError(f"query key: {k}") from e + return config + + def __setitem__(self, id: str | int, config: Any) -> None: + """ + Set config by ``id``. Note that this method should be used before ``parse()`` or ``get_parsed_content()`` + to ensure the updates are included in the parsed content. + + Args: + id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to + go one level further into the nested structures. + Use digits indexing from "0" for list or other strings for dict. + For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``. + config: config to set at location ``id``. + + """ + if id == "": + self.config = config + self.ref_resolver.reset() + return + last_id, base_id = ReferenceResolver.split_id(id, last=True) + # get the last parent level config item and replace it + conf_ = self[last_id] + + indexing = base_id if isinstance(conf_, dict) else int(base_id) + conf_[indexing] = config + self.ref_resolver.reset() + return + + def get(self, id: str = "", default: Any | None = None) -> Any: + """ + Get the config by id. + + Args: + id: id to specify the expected position. See also :py:meth:`__getitem__`. + default: default value to return if the specified ``id`` is invalid. + + """ + try: + return self[id] + except (KeyError, IndexError, ValueError): # Index error for integer indexing + return default + + def set(self, config: Any, id: str = "", recursive: bool = True) -> None: + """ + Set config by ``id``. + + Args: + config: config to set at location ``id``. + id: id to specify the expected position. See also :py:meth:`__setitem__`. + recursive: if the nested id doesn't exist, whether to recursively create the nested items in the config. + default to `True`. for the nested id, only support `dict` for the missing section. + + """ + keys = ReferenceResolver.split_id(id) + conf_ = self.get() + if recursive: + if conf_ is None: + self.config = conf_ = {} # type: ignore + for k in keys[:-1]: + if isinstance(conf_, dict) and k not in conf_: + conf_[k] = {} + conf_ = conf_[k if isinstance(conf_, dict) else int(k)] + self[ReferenceResolver.normalize_id(id)] = config + + def update(self, pairs: dict[str, Any]) -> None: + """ + Set the ``id`` and the corresponding config content in pairs, see also :py:meth:`__setitem__`. + For example, ``parser.update({"train::epoch": 100, "train::lr": 0.02})`` + + Args: + pairs: dictionary of `id` and config pairs. + + """ + for k, v in pairs.items(): + self[k] = v + + def __contains__(self, id: str | int) -> bool: + """ + Returns True if `id` is stored in this configuration. + + Args: + id: id to specify the expected position. See also :py:meth:`__getitem__`. + """ + try: + _ = self[id] + return True + except (KeyError, IndexError, ValueError): # Index error for integer indexing + return False + + def parse(self, reset: bool = True) -> None: + """ + Recursively resolve `self.config` to replace the macro tokens with target content. + Then recursively parse the config source, add every item as ``ConfigItem`` to the reference resolver. + + Args: + reset: whether to reset the ``reference_resolver`` before parsing. Defaults to `True`. + + """ + if reset: + self.ref_resolver.reset() + self.resolve_macro_and_relative_ids() + self._do_parse(config=self.get()) + + def get_parsed_content(self, id: str = "", **kwargs: Any) -> Any: + """ + Get the parsed result of ``ConfigItem`` with the specified ``id``. + + - If the item is ``ConfigComponent`` and ``instantiate=True``, the result is the instance. + - If the item is ``ConfigExpression`` and ``eval_expr=True``, the result is the evaluated output. + - Else, the result is the configuration content of `ConfigItem`. + + Args: + id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to + go one level further into the nested structures. + Use digits indexing from "0" for list or other strings for dict. + For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``. + kwargs: additional keyword arguments to be passed to ``_resolve_one_item``. + Currently support ``lazy`` (whether to retain the current config cache, default to `True`), + ``instantiate`` (whether to instantiate the `ConfigComponent`, default to `True`) and + ``eval_expr`` (whether to evaluate the `ConfigExpression`, default to `True`), ``default`` + (the default config item if the `id` is not in the config content). + + """ + if not self.ref_resolver.is_resolved(): + # not parsed the config source yet, parse it + self.parse(reset=True) + elif not kwargs.get("lazy", True): + self.parse(reset=not kwargs.get("lazy", True)) + return self.ref_resolver.get_resolved_content(id=id, **kwargs) + + def read_meta(self, f: PathLike | Sequence[PathLike] | dict, **kwargs: Any) -> None: + """ + Read the metadata from specified JSON or YAML file. + The metadata as a dictionary will be stored at ``self.config["_meta_"]``. + + Args: + f: filepath of the metadata file, the content must be a dictionary, + if providing a list of files, will merge the content of them. + if providing a dictionary directly, use it as metadata. + kwargs: other arguments for ``json.load`` or ``yaml.safe_load``, depends on the file format. + + """ + self.set(self.load_config_files(f, **kwargs), self.meta_key) + + def read_config(self, f: PathLike | Sequence[PathLike] | dict, **kwargs: Any) -> None: + """ + Read the config from specified JSON/YAML file or a dictionary and + override the config content in the `self.config` dictionary. + + Args: + f: filepath of the config file, the content must be a dictionary, + if providing a list of files, wil merge the content of them. + if providing a dictionary directly, use it as config. + kwargs: other arguments for ``json.load`` or ``yaml.safe_load``, depends on the file format. + + """ + content = {self.meta_key: self.get(self.meta_key, {})} + content.update(self.load_config_files(f, **kwargs)) + self.set(config=content) + + def _do_resolve(self, config: Any, id: str = "") -> Any: + """ + Recursively resolve `self.config` to replace the relative ids with absolute ids, for example, + `@##A` means `A` in the upper level. and replace the macro tokens with target content, + The macro tokens start with "%", can be from another structured file, like: + ``"%default_net"``, ``"%/data/config.json#net"``. + Note that the macro replacement doesn't support recursive macro tokens. + + Args: + config: input config file to resolve. + id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to + go one level further into the nested structures. + Use digits indexing from "0" for list or other strings for dict. + For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``. + + """ + if isinstance(config, (dict, list)): + for k, sub_id, v in self.ref_resolver.iter_subconfigs(id=id, config=config): + config[k] = self._do_resolve(v, sub_id) # type: ignore + if isinstance(config, str): + config = self.resolve_relative_ids(id, config) + if config.startswith(MACRO_KEY): + path, ids = ConfigParser.split_path_id(config[len(MACRO_KEY) :]) + parser = ConfigParser(config=self.get() if not path else ConfigParser.load_config_file(path)) + # deepcopy to ensure the macro replacement is independent config content + return deepcopy(parser[ids]) + return config + + def resolve_macro_and_relative_ids(self): + """ + Recursively resolve `self.config` to replace the relative ids with absolute ids, for example, + `@##A` means `A` in the upper level. and replace the macro tokens with target content, + The macro tokens are marked as starting with "%", can be from another structured file, like: + ``"%default_net"``, ``"%/data/config.json::net"``. + + """ + self.set(self._do_resolve(config=self.get())) + + def _do_parse(self, config: Any, id: str = "") -> None: + """ + Recursively parse the nested data in config source, add every item as `ConfigItem` to the resolver. + + Args: + config: config source to parse. + id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to + go one level further into the nested structures. + Use digits indexing from "0" for list or other strings for dict. + For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``. + + """ + if isinstance(config, (dict, list)): + for _, sub_id, v in self.ref_resolver.iter_subconfigs(id=id, config=config): + self._do_parse(config=v, id=sub_id) + + if ConfigComponent.is_instantiable(config): + self.ref_resolver.add_item(ConfigComponent(config=config, id=id, locator=self.locator)) + elif ConfigExpression.is_expression(config): + self.ref_resolver.add_item(ConfigExpression(config=config, id=id, globals=self.globals)) + else: + self.ref_resolver.add_item(ConfigItem(config=config, id=id)) + + @classmethod + def load_config_file(cls, filepath: PathLike, **kwargs: Any) -> dict: + """ + Load a single config file with specified file path (currently support JSON and YAML files). + + Args: + filepath: path of target file to load, supported postfixes: `.json`, `.yml`, `.yaml`. + kwargs: other arguments for ``json.load`` or ```yaml.safe_load``, depends on the file format. + + """ + if not filepath: + return {} + _filepath: str = str(Path(filepath)) + if not re.compile(cls.path_match, re.IGNORECASE).findall(_filepath): + raise ValueError(f'unknown file input: "{filepath}"') + with open(_filepath) as f: + if _filepath.lower().endswith(cls.suffixes[0]): + return json.load(f, object_pairs_hook=check_key_duplicates, **kwargs) # type: ignore[no-any-return] + if _filepath.lower().endswith(cls.suffixes[1:]): + return yaml.load(f, CheckKeyDuplicatesYamlLoader, **kwargs) # type: ignore[no-any-return] + raise ValueError(f"only support JSON or YAML config file so far, got name {_filepath}.") + + @classmethod + def load_config_files(cls, files: PathLike | Sequence[PathLike] | dict, **kwargs: Any) -> dict: + """ + Load multiple config files into a single config dict. + The latter config file in the list will override or add the former config file. + ``"::"`` (or ``"#"``) in the config keys are interpreted as special characters to go one level + further into the nested structures. + + Args: + files: path of target files to load, supported postfixes: `.json`, `.yml`, `.yaml`. + if providing a list of files, will merge the content of them. + if providing a string with comma separated file paths, will merge the content of them. + if providing a dictionary, return it directly. + kwargs: other arguments for ``json.load`` or ```yaml.safe_load``, depends on the file format. + """ + if isinstance(files, dict): # already a config dict + return files + parser = ConfigParser(config={}) + if isinstance(files, str) and not Path(files).is_file() and "," in files: + files = files.split(",") + for i in ensure_tuple(files): + for k, v in (cls.load_config_file(i, **kwargs)).items(): + parser[k] = v + return parser.get() # type: ignore + + @classmethod + def export_config_file(cls, config: dict, filepath: PathLike, fmt: str = "json", **kwargs: Any) -> None: + """ + Export the config content to the specified file path (currently support JSON and YAML files). + + Args: + config: source config content to export. + filepath: target file path to save. + fmt: format of config content, currently support ``"json"`` and ``"yaml"``. + kwargs: other arguments for ``json.dump`` or ``yaml.safe_dump``, depends on the file format. + + """ + _filepath: str = str(Path(filepath)) + writer = look_up_option(fmt.lower(), {"json", "yaml", "yml"}) + with open(_filepath, "w") as f: + if writer == "json": + json.dump(config, f, **kwargs) + return + if writer == "yaml" or writer == "yml": + return yaml.safe_dump(config, f, **kwargs) + raise ValueError(f"only support JSON or YAML config file so far, got {writer}.") + + @classmethod + def split_path_id(cls, src: str) -> tuple[str, str]: + """ + Split `src` string into two parts: a config file path and component id. + The file path should end with `(json|yaml|yml)`. The component id should be separated by `::` if it exists. + If no path or no id, return "". + + Args: + src: source string to split. + + """ + src = ReferenceResolver.normalize_id(src) + result = re.compile(rf"({cls.suffix_match}(?=(?:{ID_SEP_KEY}.*)|$))", re.IGNORECASE).findall(src) + if not result: + return "", src # the src is a pure id + path_name = result[0][0] # at most one path_name + _, ids = src.rsplit(path_name, 1) + return path_name, ids[len(ID_SEP_KEY) :] if ids.startswith(ID_SEP_KEY) else "" + + @classmethod + def resolve_relative_ids(cls, id: str, value: str) -> str: + """ + To simplify the reference or macro tokens ID in the nested config content, it's available to use + relative ID name which starts with the `ID_SEP_KEY`, for example, "@#A" means `A` in the same level, + `@##A` means `A` in the upper level. + It resolves the relative ids to absolute ids. For example, if the input data is: + + .. code-block:: python + + { + "A": 1, + "B": {"key": "@##A", "value1": 2, "value2": "%#value1", "value3": [3, 4, "@#1"]}, + } + + It will resolve `B` to `{"key": "@A", "value1": 2, "value2": "%B#value1", "value3": [3, 4, "@B#value3#1"]}`. + + Args: + id: id name for current config item to compute relative id. + value: input value to resolve relative ids. + + """ + # get the prefixes like: "@####", "%###", "@#" + value = ReferenceResolver.normalize_id(value) + prefixes = sorted(set().union(cls.relative_id_prefix.findall(value)), reverse=True) + current_id = id.split(ID_SEP_KEY) + + for p in prefixes: + sym = ID_REF_KEY if ID_REF_KEY in p else MACRO_KEY + length = p[len(sym) :].count(ID_SEP_KEY) + if length > len(current_id): + raise ValueError(f"the relative id in `{value}` is out of the range of config content.") + if length == len(current_id): + new = "" # root id is `""` + else: + new = ID_SEP_KEY.join(current_id[:-length]) + ID_SEP_KEY + value = value.replace(p, sym + new) + return value diff --git a/source_code/SegMamba/monai/bundle/properties.py b/source_code/SegMamba/monai/bundle/properties.py new file mode 100644 index 0000000000000000000000000000000000000000..a75e862a8435e55325a96cf92134dd4f187b88c3 --- /dev/null +++ b/source_code/SegMamba/monai/bundle/properties.py @@ -0,0 +1,262 @@ +# 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. +""" +The predefined properties for a bundle workflow, other applications can leverage the properties +to interact with the bundle workflow. +Some properties are required and some are optional, optional properties mean: if some component of the +bundle workflow refer to the property, the property must be defined, otherwise, the property can be None. +Every item in this `TrainProperties` or `InferProperties` or `MetaProperties` dictionary is a property, +the key is the property name and the values include: +1. description. +2. whether it's a required property. +3. config item ID name (only applicable when the bundle workflow is defined in config). +4. reference config item ID name (only applicable when the bundle workflow is defined in config). + +""" + +from __future__ import annotations + +from monai.bundle.utils import ID_SEP_KEY +from monai.utils import BundleProperty, BundlePropertyConfig + +TrainProperties = { + "bundle_root": { + BundleProperty.DESC: "root path of the bundle.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "bundle_root", + }, + "device": { + BundleProperty.DESC: "target device to execute the bundle workflow.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "device", + }, + "dataset_dir": { + BundleProperty.DESC: "directory path of the dataset.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "dataset_dir", + }, + "trainer": { + BundleProperty.DESC: "training workflow engine.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}trainer", + }, + "network_def": { + BundleProperty.DESC: "network module for the training.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: "network_def", + }, + "max_epochs": { + BundleProperty.DESC: "max number of epochs to execute the training.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}max_epochs", + }, + "train_dataset": { + BundleProperty.DESC: "PyTorch dataset object for the training logic.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}dataset", + }, + "train_inferer": { + BundleProperty.DESC: "MONAI Inferer object to execute the model computation in training.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}inferer", + }, + "train_dataset_data": { + BundleProperty.DESC: "data source for the training dataset.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}dataset{ID_SEP_KEY}data", + BundlePropertyConfig.REF_ID: None, # no reference to this ID + }, + "train_handlers": { + BundleProperty.DESC: "event-handlers for the training logic.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}handlers", + BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}train_handlers", + }, + "train_preprocessing": { + BundleProperty.DESC: "preprocessing for the training input data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}preprocessing", + BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}dataset{ID_SEP_KEY}transform", + }, + "train_postprocessing": { + BundleProperty.DESC: "postprocessing for the training model output data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}postprocessing", + BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}postprocessing", + }, + "train_key_metric": { + BundleProperty.DESC: "key metric to compute on the training data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"train{ID_SEP_KEY}key_metric", + BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}key_train_metric", + }, + "evaluator": { + BundleProperty.DESC: "validation workflow engine.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}evaluator", + BundlePropertyConfig.REF_ID: "validator", # this REF_ID is the arg name of `ValidationHandler` + }, + "val_interval": { + BundleProperty.DESC: "validation interval during the training.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: "val_interval", + BundlePropertyConfig.REF_ID: "interval", # this REF_ID is the arg name of `ValidationHandler` + }, + "val_handlers": { + BundleProperty.DESC: "event-handlers for the validation logic.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}handlers", + BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}val_handlers", + }, + "val_dataset": { + BundleProperty.DESC: "PyTorch dataset object for the validation logic.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}dataset", + BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}dataloader{ID_SEP_KEY}dataset", + }, + "val_dataset_data": { + BundleProperty.DESC: "data source for the validation dataset.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}dataset{ID_SEP_KEY}data", + BundlePropertyConfig.REF_ID: None, # no reference to this ID + }, + "val_inferer": { + BundleProperty.DESC: "MONAI Inferer object to execute the model computation in validation.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}inferer", + BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}inferer", + }, + "val_preprocessing": { + BundleProperty.DESC: "preprocessing for the validation input data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}preprocessing", + BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}dataset{ID_SEP_KEY}transform", + }, + "val_postprocessing": { + BundleProperty.DESC: "postprocessing for the validation model output data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}postprocessing", + BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}postprocessing", + }, + "val_key_metric": { + BundleProperty.DESC: "key metric to compute on the validation data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}key_metric", + BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}key_val_metric", + }, +} + +InferProperties = { + "bundle_root": { + BundleProperty.DESC: "root path of the bundle.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "bundle_root", + }, + "device": { + BundleProperty.DESC: "target device to execute the bundle workflow.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "device", + }, + "dataset_dir": { + BundleProperty.DESC: "directory path of the dataset.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "dataset_dir", + }, + "dataset": { + BundleProperty.DESC: "PyTorch dataset object for the inference / evaluation logic.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "dataset", + }, + "evaluator": { + BundleProperty.DESC: "inference / evaluation workflow engine.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "evaluator", + }, + "network_def": { + BundleProperty.DESC: "network module for the inference.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "network_def", + }, + "inferer": { + BundleProperty.DESC: "MONAI Inferer object to execute the model computation in inference.", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: "inferer", + }, + "dataset_data": { + BundleProperty.DESC: "data source for the inference / evaluation dataset.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"dataset{ID_SEP_KEY}data", + BundlePropertyConfig.REF_ID: None, # no reference to this ID + }, + "handlers": { + BundleProperty.DESC: "event-handlers for the inference / evaluation logic.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: "handlers", + BundlePropertyConfig.REF_ID: f"evaluator{ID_SEP_KEY}val_handlers", + }, + "preprocessing": { + BundleProperty.DESC: "preprocessing for the input data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: "preprocessing", + BundlePropertyConfig.REF_ID: f"dataset{ID_SEP_KEY}transform", + }, + "postprocessing": { + BundleProperty.DESC: "postprocessing for the model output data.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: "postprocessing", + BundlePropertyConfig.REF_ID: f"evaluator{ID_SEP_KEY}postprocessing", + }, + "key_metric": { + BundleProperty.DESC: "the key metric during evaluation.", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: "key_metric", + BundlePropertyConfig.REF_ID: f"evaluator{ID_SEP_KEY}key_val_metric", + }, +} + +MetaProperties = { + "version": { + BundleProperty.DESC: "bundle version", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}version", + }, + "monai_version": { + BundleProperty.DESC: "required monai version used for bundle", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}monai_version", + }, + "pytorch_version": { + BundleProperty.DESC: "required pytorch version used for bundle", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}pytorch_version", + }, + "numpy_version": { + BundleProperty.DESC: "required numpy version used for bundle", + BundleProperty.REQUIRED: True, + BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}numpy_version", + }, + "description": { + BundleProperty.DESC: "description for bundle", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}description", + }, + "spatial_shape": { + BundleProperty.DESC: "spatial shape for the inputs", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}network_data_format{ID_SEP_KEY}inputs{ID_SEP_KEY}image" + f"{ID_SEP_KEY}spatial_shape", + }, + "channel_def": { + BundleProperty.DESC: "channel definition for the prediction", + BundleProperty.REQUIRED: False, + BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}network_data_format{ID_SEP_KEY}outputs{ID_SEP_KEY}pred{ID_SEP_KEY}channel_def", + }, +} diff --git a/source_code/SegMamba/monai/bundle/reference_resolver.py b/source_code/SegMamba/monai/bundle/reference_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..b36f2cc4a54552933a683833354019dbb0d459d2 --- /dev/null +++ b/source_code/SegMamba/monai/bundle/reference_resolver.py @@ -0,0 +1,345 @@ +# 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 re +import warnings +from collections.abc import Sequence +from typing import Any, Iterator + +from monai.bundle.config_item import ConfigComponent, ConfigExpression, ConfigItem +from monai.bundle.utils import ID_REF_KEY, ID_SEP_KEY +from monai.utils import allow_missing_reference, look_up_option + +__all__ = ["ReferenceResolver"] + + +class ReferenceResolver: + """ + Utility class to manage a set of ``ConfigItem`` and resolve the references between them. + + This class maintains a set of ``ConfigItem`` objects and their associated IDs. + The IDs must be unique within this set. A string in ``ConfigItem`` + starting with ``@`` will be treated as a reference to other ``ConfigItem`` objects by ID. + Since ``ConfigItem`` may have a nested dictionary or list structure, + the reference string may also contain the separator ``::`` to refer to a substructure by + key indexing for a dictionary or integer indexing for a list. + + In this class, resolving references is essentially substitution of the reference strings with the + corresponding python objects. A typical workflow of resolving references is as follows: + + - Add multiple ``ConfigItem`` objects to the ``ReferenceResolver`` by ``add_item()``. + - Call ``get_resolved_content()`` to automatically resolve the references. This is done (recursively) by: + - Convert the items to objects, for those do not have references to other items. + - If it is instantiable, instantiate it and cache the class instance in ``resolved_content``. + - If it is an expression, evaluate it and save the value in ``resolved_content``. + - Substitute the reference strings with the corresponding objects. + + Args: + items: ``ConfigItem``s to resolve, this could be added later with ``add_item()``. + + """ + + _vars = "__local_refs" + sep = ID_SEP_KEY # separator for key indexing + ref = ID_REF_KEY # reference prefix + # match a reference string, e.g. "@id::key", "@id::key::0", "@_target_::key" + id_matcher = re.compile(rf"{ref}(?:\w*)(?:{sep}\w*)*") + # if `allow_missing_reference` and can't find a reference ID, will just raise a warning and don't update the config + allow_missing_reference = allow_missing_reference + + def __init__(self, items: Sequence[ConfigItem] | None = None): + # save the items in a dictionary with the `ConfigItem.id` as key + self.items: dict[str, ConfigItem] = {} if items is None else {i.get_id(): i for i in items} + self.resolved_content: dict[str, ConfigExpression | str | Any | None] = {} + + def reset(self): + """ + Clear all the added `ConfigItem` and all the resolved content. + + """ + self.items = {} + self.resolved_content = {} + + def is_resolved(self) -> bool: + return bool(self.resolved_content) + + def add_item(self, item: ConfigItem) -> None: + """ + Add a ``ConfigItem`` to the resolver. + + Args: + item: a ``ConfigItem``. + + """ + id = item.get_id() + if id in self.items: + return + self.items[id] = item + + def get_item(self, id: str, resolve: bool = False, **kwargs: Any) -> ConfigItem | None: + """ + Get the ``ConfigItem`` by id. + + If ``resolve=True``, the returned item will be resolved, that is, + all the reference strings are substituted by the corresponding ``ConfigItem`` objects. + + Args: + id: id of the expected config item. + resolve: whether to resolve the item if it is not resolved, default to False. + kwargs: keyword arguments to pass to ``_resolve_one_item()``. + Currently support ``instantiate`` and ``eval_expr``. Both are defaulting to True. + """ + id = self.normalize_id(id) + if resolve and id not in self.resolved_content: + self._resolve_one_item(id=id, **kwargs) + return self.items.get(id) + + def _resolve_one_item( + self, id: str, waiting_list: set[str] | None = None, **kwargs: Any + ) -> ConfigExpression | str | Any | None: + """ + Resolve and return one ``ConfigItem`` of ``id``, cache the resolved result in ``resolved_content``. + If it has unresolved references, recursively resolve the referring items first. + + Args: + id: id name of ``ConfigItem`` to be resolved. + waiting_list: set of ids pending to be resolved. + It's used to detect circular references such as: + `{"name": "A", "dep": "@B"}` and `{"name": "B", "dep": "@A"}`. + kwargs: keyword arguments to pass to ``_resolve_one_item()``. + Currently support ``instantiate``, ``eval_expr`` and ``default``. + `instantiate` and `eval_expr` are defaulting to True, `default` is the target config item + if the `id` is not in the config content, must be a `ConfigItem` object. + + """ + id = self.normalize_id(id) + if id in self.resolved_content: + return self.resolved_content[id] + try: + item = look_up_option(id, self.items, print_all_options=False, default=kwargs.get("default", "no_default")) + except ValueError as err: + raise KeyError(f"id='{id}' is not found in the config resolver.") from err + if not isinstance(item, ConfigItem): + return item + item_config = item.get_config() + + if waiting_list is None: + waiting_list = set() + waiting_list.add(id) + + for t, v in self.items.items(): + if ( + t not in self.resolved_content + and isinstance(v, ConfigExpression) + and v.is_import_statement(v.get_config()) + ): + self.resolved_content[t] = v.evaluate() if kwargs.get("eval_expr", True) else v + for d in self.find_refs_in_config(config=item_config, id=id).keys(): + # if current item has reference already in the waiting list, that's circular references + if d in waiting_list: + raise ValueError(f"detected circular references '{d}' for id='{id}' in the config content.") + # check whether the component has any unresolved references + if d not in self.resolved_content: + # this referring item is not resolved + try: + look_up_option(d, self.items, print_all_options=False) + except ValueError as err: + msg = f"the referring item `@{d}` is not defined in the config content." + if not self.allow_missing_reference: + raise ValueError(msg) from err + warnings.warn(msg) + continue + # recursively resolve the reference first + self._resolve_one_item(id=d, waiting_list=waiting_list, **kwargs) + waiting_list.discard(d) + + # all references are resolved, then try to resolve current config item + new_config = self.update_config_with_refs(config=item_config, id=id, refs=self.resolved_content) + item.update_config(config=new_config) + # save the resolved result into `resolved_content` to recursively resolve others + if isinstance(item, ConfigComponent): + self.resolved_content[id] = item.instantiate() if kwargs.get("instantiate", True) else item + elif isinstance(item, ConfigExpression): + run_eval = kwargs.get("eval_expr", True) + self.resolved_content[id] = ( + item.evaluate(globals={f"{self._vars}": self.resolved_content}) if run_eval else item + ) + else: + self.resolved_content[id] = new_config + return self.resolved_content[id] + + def get_resolved_content(self, id: str, **kwargs: Any) -> ConfigExpression | str | Any | None: + """ + Get the resolved ``ConfigItem`` by id. + + Args: + id: id name of the expected item. + kwargs: keyword arguments to pass to ``_resolve_one_item()``. + Currently support ``instantiate``, ``eval_expr`` and ``default``. + `instantiate` and `eval_expr` are defaulting to True, `default` is the target config item + if the `id` is not in the config content, must be a `ConfigItem` object. + + """ + return self._resolve_one_item(id=id, **kwargs) + + @classmethod + def normalize_id(cls, id: str | int) -> str: + """ + Normalize the id string to consistently use `cls.sep`. + + Args: + id: id string to be normalized. + """ + return str(id).replace("#", cls.sep) # backward compatibility `#` is the old separator + + @classmethod + def split_id(cls, id: str | int, last: bool = False) -> list[str]: + """ + Split the id string into a list of strings by `cls.sep`. + + Args: + id: id string to be split. + last: whether to split the rightmost part of the id. default is False (split all parts). + """ + if not last: + return cls.normalize_id(id).split(cls.sep) + res = cls.normalize_id(id).rsplit(cls.sep, 1) + return ["".join(res[:-1]), res[-1]] + + @classmethod + def iter_subconfigs(cls, id: str, config: Any) -> Iterator[tuple[str, str, Any]]: + """ + Iterate over the sub-configs of the input config, the output `sub_id` uses `cls.sep` to denote substructure. + + Args: + id: id string of the current input config. + config: input config to be iterated. + """ + for k, v in config.items() if isinstance(config, dict) else enumerate(config): + sub_id = f"{id}{cls.sep}{k}" if id != "" else f"{k}" + yield k, sub_id, v + + @classmethod + def match_refs_pattern(cls, value: str) -> dict[str, int]: + """ + Match regular expression for the input string to find the references. + The reference string starts with ``"@"``, like: ``"@XXX::YYY::ZZZ"``. + + Args: + value: input value to match regular expression. + + """ + refs: dict[str, int] = {} + # regular expression pattern to match "@XXX" or "@XXX::YYY" + value = cls.normalize_id(value) + result = cls.id_matcher.findall(value) + value_is_expr = ConfigExpression.is_expression(value) + for item in result: + if value_is_expr or value == item: + # only check when string starts with "$" or the whole content is "@XXX" + id = item[len(cls.ref) :] + refs[id] = refs.get(id, 0) + 1 + return refs + + @classmethod + def update_refs_pattern(cls, value: str, refs: dict) -> str: + """ + Match regular expression for the input string to update content with the references. + The reference part starts with ``"@"``, like: ``"@XXX::YYY::ZZZ"``. + References dictionary must contain the referring IDs as keys. + + Args: + value: input value to match regular expression. + refs: all the referring components with ids as keys, default to `None`. + + """ + # regular expression pattern to match "@XXX" or "@XXX::YYY" + value = cls.normalize_id(value) + result = cls.id_matcher.findall(value) + # reversely sort the matched references by length + # and handle the longer first in case a reference item is substring of another longer item + result.sort(key=len, reverse=True) + value_is_expr = ConfigExpression.is_expression(value) + for item in result: + # only update reference when string starts with "$" or the whole content is "@XXX" + if value_is_expr or value == item: + ref_id = item[len(cls.ref) :] # remove the ref prefix "@" + if ref_id not in refs: + msg = f"can not find expected ID '{ref_id}' in the references." + if not cls.allow_missing_reference: + raise KeyError(msg) + warnings.warn(msg) + continue + if value_is_expr: + # replace with local code, `{"__local_refs": self.resolved_content}` will be added to + # the `globals` argument of python `eval` in the `evaluate` + value = value.replace(item, f"{cls._vars}['{ref_id}']") + elif value == item: + # the whole content is "@XXX", it will avoid the case that regular string contains "@" + value = refs[ref_id] + return value + + @classmethod + def find_refs_in_config(cls, config: Any, id: str, refs: dict[str, int] | None = None) -> dict[str, int]: + """ + Recursively search all the content of input config item to get the ids of references. + References mean: the IDs of other config items (``"@XXX"`` in this config item), or the + sub-item in the config is `instantiable`, or the sub-item in the config is `expression`. + For `dict` and `list`, recursively check the sub-items. + + Args: + config: input config content to search. + id: ID name for the input config item. + refs: dict of the ID name and count of found references, default to `None`. + + """ + refs_: dict[str, int] = refs or {} + if isinstance(config, str): + for id, count in cls.match_refs_pattern(value=config).items(): # ref count is not currently used + refs_[id] = refs_.get(id, 0) + count + if not isinstance(config, (list, dict)): + return refs_ + for _, sub_id, v in cls.iter_subconfigs(id, config): + if ConfigComponent.is_instantiable(v) or ConfigExpression.is_expression(v) and sub_id not in refs_: + refs_[sub_id] = 1 + refs_ = cls.find_refs_in_config(v, sub_id, refs_) + return refs_ + + @classmethod + def update_config_with_refs(cls, config: Any, id: str, refs: dict | None = None) -> Any: + """ + With all the references in ``refs``, update the input config content with references + and return the new config. + + Args: + config: input config content to update. + id: ID name for the input config. + refs: all the referring content with ids, default to `None`. + + """ + refs_: dict = refs or {} + if isinstance(config, str): + return cls.update_refs_pattern(config, refs_) + if not isinstance(config, (list, dict)): + return config + ret = type(config)() + for idx, sub_id, v in cls.iter_subconfigs(id, config): + if ConfigComponent.is_instantiable(v) or ConfigExpression.is_expression(v): + updated = refs_[sub_id] + if ConfigComponent.is_instantiable(v) and updated is None: + # the component is disabled + continue + else: + updated = cls.update_config_with_refs(v, sub_id, refs_) + ret.update({idx: updated}) if isinstance(ret, dict) else ret.append(updated) + return ret diff --git a/source_code/SegMamba/monai/bundle/scripts.py b/source_code/SegMamba/monai/bundle/scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..598d938cbdfe91e2565f90299ebfb5bce6bf67e1 --- /dev/null +++ b/source_code/SegMamba/monai/bundle/scripts.py @@ -0,0 +1,1806 @@ +# 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 ast +import json +import os +import re +import warnings +from collections.abc import Mapping, Sequence +from pathlib import Path +from pydoc import locate +from shutil import copyfile +from textwrap import dedent +from typing import Any, Callable + +import torch +from torch.cuda import is_available + +from monai.apps.mmars.mmars import _get_all_ngc_models +from monai.apps.utils import _basename, download_url, extractall, get_logger +from monai.bundle.config_item import ConfigComponent +from monai.bundle.config_parser import ConfigParser +from monai.bundle.utils import DEFAULT_INFERENCE, DEFAULT_METADATA +from monai.bundle.workflows import BundleWorkflow, ConfigWorkflow +from monai.config import IgniteInfo, PathLike +from monai.data import load_net_with_metadata, save_net_with_metadata +from monai.networks import ( + convert_to_onnx, + convert_to_torchscript, + convert_to_trt, + copy_model_state, + get_state_dict, + save_state, +) +from monai.utils import ( + check_parent_dir, + deprecated_arg, + ensure_tuple, + get_equivalent_dtype, + min_version, + optional_import, + pprint_edges, +) + +validate, _ = optional_import("jsonschema", name="validate") +ValidationError, _ = optional_import("jsonschema.exceptions", name="ValidationError") +Checkpoint, has_ignite = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Checkpoint") +requests_get, has_requests = optional_import("requests", name="get") +onnx, _ = optional_import("onnx") +huggingface_hub, _ = optional_import("huggingface_hub") + +logger = get_logger(module_name=__name__) + +# set BUNDLE_DOWNLOAD_SRC="ngc" to use NGC source in default for bundle download +# set BUNDLE_DOWNLOAD_SRC="github" to use github source in default for bundle download +DEFAULT_DOWNLOAD_SOURCE = os.environ.get("BUNDLE_DOWNLOAD_SRC", "monaihosting") +PPRINT_CONFIG_N = 5 + + +def update_kwargs(args: str | dict | None = None, ignore_none: bool = True, **kwargs: Any) -> dict: + """ + Update the `args` dictionary with the input `kwargs`. + For dict data, recursively update the content based on the keys. + + Example:: + + from monai.bundle import update_kwargs + update_kwargs({'exist': 1}, exist=2, new_arg=3) + # return {'exist': 2, 'new_arg': 3} + + Args: + args: source `args` dictionary (or a json/yaml filename to read as dictionary) to update. + ignore_none: whether to ignore input args with None value, default to `True`. + kwargs: key=value pairs to be merged into `args`. + + """ + args_: dict = args if isinstance(args, dict) else {} + if isinstance(args, str): + # args are defined in a structured file + args_ = ConfigParser.load_config_file(args) + if isinstance(args, (tuple, list)) and all(isinstance(x, str) for x in args): + primary, overrides = args + args_ = update_kwargs(primary, ignore_none, **update_kwargs(overrides, ignore_none, **kwargs)) + if not isinstance(args_, dict): + return args_ + # recursively update the default args with new args + for k, v in kwargs.items(): + if ignore_none and v is None: + continue + if isinstance(v, dict) and isinstance(args_.get(k), dict): + args_[k] = update_kwargs(args_[k], ignore_none, **v) + else: + args_[k] = v + return args_ + + +_update_args = update_kwargs # backward compatibility + + +def _pop_args(src: dict, *args: Any, **kwargs: Any) -> tuple: + """ + Pop args from the `src` dictionary based on specified keys in `args` and (key, default value) pairs in `kwargs`. + + """ + return tuple([src.pop(i) for i in args] + [src.pop(k, v) for k, v in kwargs.items()]) + + +def _log_input_summary(tag: str, args: dict) -> None: + logger.info(f"--- input summary of monai.bundle.scripts.{tag} ---") + for name, val in args.items(): + logger.info(f"> {name}: {pprint_edges(val, PPRINT_CONFIG_N)}") + logger.info("---\n\n") + + +def _get_var_names(expr: str) -> list[str]: + """ + Parse the expression and discover what variables are present in it based on ast module. + + Args: + expr: source expression to parse. + + """ + tree = ast.parse(expr) + return [m.id for m in ast.walk(tree) if isinstance(m, ast.Name)] + + +def _get_fake_spatial_shape(shape: Sequence[str | int], p: int = 1, n: int = 1, any: int = 1) -> tuple: + """ + Get spatial shape for fake data according to the specified shape pattern. + It supports `int` number and `string` with formats like: "32", "32 * n", "32 ** p", "32 ** p *n". + + Args: + shape: specified pattern for the spatial shape. + p: power factor to generate fake data shape if dim of expected shape is "x**p", default to 1. + p: multiply factor to generate fake data shape if dim of expected shape is "x*n", default to 1. + any: specified size to generate fake data shape if dim of expected shape is "*", default to 1. + + """ + ret = [] + for i in shape: + if isinstance(i, int): + ret.append(i) + elif isinstance(i, str): + if i == "*": + ret.append(any) + else: + for c in _get_var_names(i): + if c not in ["p", "n"]: + raise ValueError(f"only support variables 'p' and 'n' so far, but got: {c}.") + ret.append(eval(i, {"p": p, "n": n})) + else: + raise ValueError(f"spatial shape items must be int or string, but got: {type(i)} {i}.") + return tuple(ret) + + +def _get_git_release_url(repo_owner: str, repo_name: str, tag_name: str, filename: str) -> str: + return f"https://github.com/{repo_owner}/{repo_name}/releases/download/{tag_name}/{filename}" + + +def _get_ngc_bundle_url(model_name: str, version: str) -> str: + return f"https://api.ngc.nvidia.com/v2/models/nvidia/monaitoolkit/{model_name.lower()}/versions/{version}/zip" + + +def _get_monaihosting_bundle_url(model_name: str, version: str) -> str: + monaihosting_root_path = "https://api.ngc.nvidia.com/v2/models/nvidia/monaihosting" + return f"{monaihosting_root_path}/{model_name.lower()}/versions/{version}/files/{model_name}_v{version}.zip" + + +def _download_from_github(repo: str, download_path: Path, filename: str, progress: bool = True) -> None: + repo_owner, repo_name, tag_name = repo.split("/") + if ".zip" not in filename: + filename += ".zip" + url = _get_git_release_url(repo_owner, repo_name, tag_name=tag_name, filename=filename) + filepath = download_path / f"{filename}" + download_url(url=url, filepath=filepath, hash_val=None, progress=progress) + extractall(filepath=filepath, output_dir=download_path, has_base=True) + + +def _download_from_monaihosting(download_path: Path, filename: str, version: str, progress: bool) -> None: + url = _get_monaihosting_bundle_url(model_name=filename, version=version) + filepath = download_path / f"{filename}_v{version}.zip" + download_url(url=url, filepath=filepath, hash_val=None, progress=progress) + extractall(filepath=filepath, output_dir=download_path, has_base=True) + + +def _add_ngc_prefix(name: str, prefix: str = "monai_") -> str: + if name.startswith(prefix): + return name + return f"{prefix}{name}" + + +def _remove_ngc_prefix(name: str, prefix: str = "monai_") -> str: + if name.startswith(prefix): + return name[len(prefix) :] + return name + + +def _download_from_ngc( + download_path: Path, filename: str, version: str, remove_prefix: str | None, progress: bool +) -> None: + # ensure prefix is contained + filename = _add_ngc_prefix(filename) + url = _get_ngc_bundle_url(model_name=filename, version=version) + filepath = download_path / f"{filename}_v{version}.zip" + if remove_prefix: + filename = _remove_ngc_prefix(filename, prefix=remove_prefix) + extract_path = download_path / f"{filename}" + download_url(url=url, filepath=filepath, hash_val=None, progress=progress) + extractall(filepath=filepath, output_dir=extract_path, has_base=True) + + +def _get_latest_bundle_version_monaihosting(name): + url = "https://api.ngc.nvidia.com/v2/models/nvidia/monaihosting" + full_url = f"{url}/{name.lower()}" + requests_get, has_requests = optional_import("requests", name="get") + if has_requests: + resp = requests_get(full_url) + resp.raise_for_status() + else: + raise ValueError("NGC API requires requests package. Please install it.") + model_info = json.loads(resp.text) + return model_info["model"]["latestVersionIdStr"] + + +def _get_latest_bundle_version(source: str, name: str, repo: str) -> dict[str, list[str] | str] | Any | None: + if source == "ngc": + name = _add_ngc_prefix(name) + model_dict = _get_all_ngc_models(name) + for v in model_dict.values(): + if v["name"] == name: + return v["latest"] + return None + elif source == "monaihosting": + return _get_latest_bundle_version_monaihosting(name) + elif source == "github": + repo_owner, repo_name, tag_name = repo.split("/") + return get_bundle_versions(name, repo=f"{repo_owner}/{repo_name}", tag=tag_name)["latest_version"] + elif source == "huggingface_hub": + refs = huggingface_hub.list_repo_refs(repo_id=repo) + if len(refs.tags) > 0: + all_versions = [t.name for t in refs.tags] # git tags, not to be confused with `tag` + latest_version = ["latest_version" if "latest_version" in all_versions else all_versions[-1]][0] + else: + latest_version = [b.name for b in refs.branches][0] # use the branch that was last updated + return latest_version + else: + raise ValueError( + f"To get the latest bundle version, source should be 'github', 'monaihosting' or 'ngc', got {source}." + ) + + +def _process_bundle_dir(bundle_dir: PathLike | None = None) -> Path: + if bundle_dir is None: + get_dir, has_home = optional_import("torch.hub", name="get_dir") + if has_home: + bundle_dir = Path(get_dir()) / "bundle" + else: + raise ValueError("bundle_dir=None, but no suitable default directory computed. Upgrade Pytorch to 1.6+ ?") + return Path(bundle_dir) + + +def download( + name: str | None = None, + version: str | None = None, + bundle_dir: PathLike | None = None, + source: str = DEFAULT_DOWNLOAD_SOURCE, + repo: str | None = None, + url: str | None = None, + remove_prefix: str | None = "monai_", + progress: bool = True, + args_file: str | None = None, +) -> None: + """ + download bundle from the specified source or url. The bundle should be a zip file and it + will be extracted after downloading. + This function refers to: + https://pytorch.org/docs/stable/_modules/torch/hub.html + + Typical usage examples: + + .. code-block:: bash + + # Execute this module as a CLI entry, and download bundle from the model-zoo repo: + python -m monai.bundle download --name --version "0.1.0" --bundle_dir "./" + + # Execute this module as a CLI entry, and download bundle from specified github repo: + python -m monai.bundle download --name --source "github" --repo "repo_owner/repo_name/release_tag" + + # Execute this module as a CLI entry, and download bundle from ngc with latest version: + python -m monai.bundle download --name --source "ngc" --bundle_dir "./" + + # Execute this module as a CLI entry, and download bundle from monaihosting with latest version: + python -m monai.bundle download --name --source "monaihosting" --bundle_dir "./" + + # Execute this module as a CLI entry, and download bundle from Hugging Face Hub: + python -m monai.bundle download --name "bundle_name" --source "huggingface_hub" --repo "repo_owner/repo_name" + + # Execute this module as a CLI entry, and download bundle via URL: + python -m monai.bundle download --name --url + + # Set default args of `run` in a JSON / YAML file, help to record and simplify the command line. + # Other args still can override the default args at runtime. + # The content of the JSON / YAML file is a dictionary. For example: + # {"name": "spleen", "bundle_dir": "download", "source": ""} + # then do the following command for downloading: + python -m monai.bundle download --args_file "args.json" --source "github" + + Args: + name: bundle name. If `None` and `url` is `None`, it must be provided in `args_file`. + for example: + "spleen_ct_segmentation", "prostate_mri_anatomy" in model-zoo: + https://github.com/Project-MONAI/model-zoo/releases/tag/hosting_storage_v1. + "monai_brats_mri_segmentation" in ngc: + https://catalog.ngc.nvidia.com/models?filters=&orderBy=scoreDESC&query=monai. + version: version name of the target bundle to download, like: "0.1.0". If `None`, will download + the latest version (or the last commit to the `main` branch in the case of Hugging Face Hub). + bundle_dir: target directory to store the downloaded data. + Default is `bundle` subfolder under `torch.hub.get_dir()`. + source: storage location name. This argument is used when `url` is `None`. + In default, the value is achieved from the environment variable BUNDLE_DOWNLOAD_SRC, and + it should be "ngc", "monaihosting", "github", or "huggingface_hub". + repo: repo name. This argument is used when `url` is `None` and `source` is "github" or "huggingface_hub". + If `source` is "github", it should be in the form of "repo_owner/repo_name/release_tag". + If `source` is "huggingface_hub", it should be in the form of "repo_owner/repo_name". + url: url to download the data. If not `None`, data will be downloaded directly + and `source` will not be checked. + If `name` is `None`, filename is determined by `monai.apps.utils._basename(url)`. + remove_prefix: This argument is used when `source` is "ngc". Currently, all ngc bundles + have the ``monai_`` prefix, which is not existing in their model zoo contrasts. In order to + maintain the consistency between these two sources, remove prefix is necessary. + Therefore, if specified, downloaded folder name will remove the prefix. + progress: whether to display a progress bar. + args_file: a JSON or YAML file to provide default values for all the args in this function. + so that the command line inputs can be simplified. + + """ + _args = update_kwargs( + args=args_file, + name=name, + version=version, + bundle_dir=bundle_dir, + source=source, + repo=repo, + url=url, + remove_prefix=remove_prefix, + progress=progress, + ) + + _log_input_summary(tag="download", args=_args) + source_, progress_, remove_prefix_, repo_, name_, version_, bundle_dir_, url_ = _pop_args( + _args, "source", "progress", remove_prefix=None, repo=None, name=None, version=None, bundle_dir=None, url=None + ) + + bundle_dir_ = _process_bundle_dir(bundle_dir_) + if repo_ is None: + repo_ = "Project-MONAI/model-zoo/hosting_storage_v1" + if len(repo_.split("/")) != 3 and source_ != "huggingface_hub": + raise ValueError("repo should be in the form of `repo_owner/repo_name/release_tag`.") + elif len(repo_.split("/")) != 2 and source_ == "huggingface_hub": + raise ValueError("Hugging Face Hub repo should be in the form of `repo_owner/repo_name`") + if url_ is not None: + if name_ is not None: + filepath = bundle_dir_ / f"{name_}.zip" + else: + filepath = bundle_dir_ / f"{_basename(url_)}" + download_url(url=url_, filepath=filepath, hash_val=None, progress=progress_) + extractall(filepath=filepath, output_dir=bundle_dir_, has_base=True) + else: + if name_ is None: + raise ValueError(f"To download from source: {source_}, `name` must be provided.") + if version_ is None: + version_ = _get_latest_bundle_version(source=source_, name=name_, repo=repo_) + if source_ == "github": + if version_ is not None: + name_ = "_v".join([name_, version_]) + _download_from_github(repo=repo_, download_path=bundle_dir_, filename=name_, progress=progress_) + elif source_ == "monaihosting": + _download_from_monaihosting(download_path=bundle_dir_, filename=name_, version=version_, progress=progress_) + elif source_ == "ngc": + _download_from_ngc( + download_path=bundle_dir_, + filename=name_, + version=version_, + remove_prefix=remove_prefix_, + progress=progress_, + ) + elif source_ == "huggingface_hub": + extract_path = os.path.join(bundle_dir_, name_) + huggingface_hub.snapshot_download(repo_id=repo_, revision=version_, local_dir=extract_path) + else: + raise NotImplementedError( + "Currently only download from `url`, source 'github', 'monaihosting', 'huggingface_hub' or 'ngc' are implemented," + f"got source: {source_}." + ) + + +@deprecated_arg("net_name", since="1.2", removed="1.5", msg_suffix="please use ``model`` instead.") +@deprecated_arg("net_kwargs", since="1.2", removed="1.5", msg_suffix="please use ``model`` instead.") +@deprecated_arg("return_state_dict", since="1.2", removed="1.5") +def load( + name: str, + model: torch.nn.Module | None = None, + version: str | None = None, + workflow_type: str = "train", + model_file: str | None = None, + load_ts_module: bool = False, + bundle_dir: PathLike | None = None, + source: str = DEFAULT_DOWNLOAD_SOURCE, + repo: str | None = None, + remove_prefix: str | None = "monai_", + progress: bool = True, + device: str | None = None, + key_in_ckpt: str | None = None, + config_files: Sequence[str] = (), + workflow_name: str | BundleWorkflow | None = None, + args_file: str | None = None, + copy_model_args: dict | None = None, + return_state_dict: bool = True, + net_override: dict | None = None, + net_name: str | None = None, + **net_kwargs: Any, +) -> object | tuple[torch.nn.Module, dict, dict] | Any: + """ + Load model weights or TorchScript module of a bundle. + + Args: + name: bundle name. If `None` and `url` is `None`, it must be provided in `args_file`. + for example: + "spleen_ct_segmentation", "prostate_mri_anatomy" in model-zoo: + https://github.com/Project-MONAI/model-zoo/releases/tag/hosting_storage_v1. + "monai_brats_mri_segmentation" in ngc: + https://catalog.ngc.nvidia.com/models?filters=&orderBy=scoreDESC&query=monai. + "mednist_gan" in monaihosting: + https://api.ngc.nvidia.com/v2/models/nvidia/monaihosting/mednist_gan/versions/0.2.0/files/mednist_gan_v0.2.0.zip + model: a pytorch module to be updated. Default to None, using the "network_def" in the bundle. + version: version name of the target bundle to download, like: "0.1.0". If `None`, will download + the latest version. If `source` is "huggingface_hub", this argument is a Git revision id. + workflow_type: specifies the workflow type: "train" or "training" for a training workflow, + or "infer", "inference", "eval", "evaluation" for a inference workflow, + other unsupported string will raise a ValueError. + default to `train` for training workflow. + model_file: the relative path of the model weights or TorchScript module within bundle. + If `None`, "models/model.pt" or "models/model.ts" will be used. + load_ts_module: a flag to specify if loading the TorchScript module. + bundle_dir: directory the weights/TorchScript module will be loaded from. + Default is `bundle` subfolder under `torch.hub.get_dir()`. + source: storage location name. This argument is used when `model_file` is not existing locally and need to be + downloaded first. + In default, the value is achieved from the environment variable BUNDLE_DOWNLOAD_SRC, and + it should be "ngc", "monaihosting", "github", or "huggingface_hub". + repo: repo name. This argument is used when `url` is `None` and `source` is "github" or "huggingface_hub". + If `source` is "github", it should be in the form of "repo_owner/repo_name/release_tag". + If `source` is "huggingface_hub", it should be in the form of "repo_owner/repo_name". + remove_prefix: This argument is used when `source` is "ngc". Currently, all ngc bundles + have the ``monai_`` prefix, which is not existing in their model zoo contrasts. In order to + maintain the consistency between these three sources, remove prefix is necessary. + Therefore, if specified, downloaded folder name will remove the prefix. + progress: whether to display a progress bar when downloading. + device: target device of returned weights or module, if `None`, prefer to "cuda" if existing. + key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model + weights. if not nested checkpoint, no need to set. + config_files: extra filenames would be loaded. The argument only works when loading a TorchScript module, + see `_extra_files` in `torch.jit.load` for more details. + workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow". + args_file: a JSON or YAML file to provide default values for all the args in "download" function. + copy_model_args: other arguments for the `monai.networks.copy_model_state` function. + return_state_dict: whether to return state dict, if True, return state_dict, else a corresponding network + from `_workflow.network_def` will be instantiated and load the achieved weights. + net_override: id-value pairs to override the parameters in the network of the bundle, default to `None`. + net_name: if not `None`, a corresponding network will be instantiated and load the achieved weights. + This argument only works when loading weights. + net_kwargs: other arguments that are used to instantiate the network class defined by `net_name`. + + Returns: + 1. If `load_ts_module` is `False` and `model` is `None`, + return model weights if can't find "network_def" in the bundle, + else return an instantiated network that loaded the weights. + 2. If `load_ts_module` is `False` and `model` is not `None`, + return an instantiated network that loaded the weights. + 3. If `load_ts_module` is `True`, return a triple that include a TorchScript module, + the corresponding metadata dict, and extra files dict. + please check `monai.data.load_net_with_metadata` for more details. + 4. If `return_state_dict` is True, return model weights, only used for compatibility + when `model` and `net_name` are all `None`. + + """ + if return_state_dict and (model is not None or net_name is not None): + warnings.warn("Incompatible values: model and net_name are all specified, return state dict instead.") + + bundle_dir_ = _process_bundle_dir(bundle_dir) + net_override = {} if net_override is None else net_override + copy_model_args = {} if copy_model_args is None else copy_model_args + + if device is None: + device = "cuda:0" if is_available() else "cpu" + if model_file is None: + model_file = os.path.join("models", "model.ts" if load_ts_module is True else "model.pt") + if source == "ngc": + name = _add_ngc_prefix(name) + if remove_prefix: + name = _remove_ngc_prefix(name, prefix=remove_prefix) + full_path = os.path.join(bundle_dir_, name, model_file) + if not os.path.exists(full_path): + download( + name=name, + version=version, + bundle_dir=bundle_dir_, + source=source, + repo=repo, + remove_prefix=remove_prefix, + progress=progress, + args_file=args_file, + ) + + # loading with `torch.jit.load` + if load_ts_module is True: + return load_net_with_metadata(full_path, map_location=torch.device(device), more_extra_files=config_files) + # loading with `torch.load` + model_dict = torch.load(full_path, map_location=torch.device(device)) + + if not isinstance(model_dict, Mapping): + warnings.warn(f"the state dictionary from {full_path} should be a dictionary but got {type(model_dict)}.") + model_dict = get_state_dict(model_dict) + + if return_state_dict: + return model_dict + + _workflow = None + if model is None and net_name is None: + bundle_config_file = bundle_dir_ / name / "configs" / f"{workflow_type}.json" + if bundle_config_file.is_file(): + _net_override = {f"network_def#{key}": value for key, value in net_override.items()} + _workflow = create_workflow( + workflow_name=workflow_name, + args_file=args_file, + config_file=str(bundle_config_file), + workflow_type=workflow_type, + **_net_override, + ) + else: + warnings.warn(f"Cannot find the config file: {bundle_config_file}, return state dict instead.") + return model_dict + if _workflow is not None: + if not hasattr(_workflow, "network_def"): + warnings.warn("No available network definition in the bundle, return state dict instead.") + return model_dict + else: + model = _workflow.network_def + elif net_name is not None: + net_kwargs["_target_"] = net_name + configer = ConfigComponent(config=net_kwargs) + model = configer.instantiate() # type: ignore + + model.to(device) # type: ignore + + copy_model_state( + dst=model, src=model_dict if key_in_ckpt is None else model_dict[key_in_ckpt], **copy_model_args # type: ignore + ) + + return model + + +def _get_all_bundles_info( + repo: str = "Project-MONAI/model-zoo", tag: str = "dev", auth_token: str | None = None +) -> dict[str, dict[str, dict[str, Any]]]: + if has_requests: + if tag == "hosting_storage_v1": + request_url = f"https://api.github.com/repos/{repo}/releases" + else: + request_url = f"https://raw.githubusercontent.com/{repo}/{tag}/models/model_info.json" + + if auth_token is not None: + headers = {"Authorization": f"Bearer {auth_token}"} + resp = requests_get(request_url, headers=headers) + else: + resp = requests_get(request_url) + resp.raise_for_status() + else: + raise ValueError("requests package is required, please install it.") + releases_list = json.loads(resp.text) + bundle_name_pattern = re.compile(r"_v\d*.") + bundles_info: dict[str, dict[str, dict[str, Any]]] = {} + + if tag == "hosting_storage_v1": + for release in releases_list: + if release["tag_name"] == tag: + for asset in release["assets"]: + asset_name = bundle_name_pattern.split(asset["name"])[0] + if asset_name not in bundles_info: + bundles_info[asset_name] = {} + asset_version = asset["name"].split(f"{asset_name}_v")[-1].replace(".zip", "") + bundles_info[asset_name][asset_version] = dict(asset) + return bundles_info + else: + for asset in releases_list.keys(): + asset_name = bundle_name_pattern.split(asset)[0] + if asset_name not in bundles_info: + bundles_info[asset_name] = {} + asset_version = asset.split(f"{asset_name}_v")[-1] + bundles_info[asset_name][asset_version] = { + "name": asset, + "browser_download_url": releases_list[asset]["source"], + } + return bundles_info + + +def get_all_bundles_list( + repo: str = "Project-MONAI/model-zoo", tag: str = "dev", auth_token: str | None = None +) -> list[tuple[str, str]]: + """ + Get all bundles names (and the latest versions) that are stored in the release of specified repository + with the provided tag. If tag is "dev", will get model information from + https://raw.githubusercontent.com/repo_owner/repo_name/dev/models/model_info.json. + The default values of arguments correspond to the release of MONAI model zoo. In order to increase the + rate limits of calling Github APIs, you can input your personal access token. + Please check the following link for more details about rate limiting: + https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting + + The following link shows how to create your personal access token: + https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token + + Args: + repo: it should be in the form of "repo_owner/repo_name/". + tag: the tag name of the release. + auth_token: github personal access token. + + Returns: + a list of tuple in the form of (bundle name, latest version). + + """ + + bundles_info = _get_all_bundles_info(repo=repo, tag=tag, auth_token=auth_token) + bundles_list = [] + for bundle_name in bundles_info: + latest_version = sorted(bundles_info[bundle_name].keys())[-1] + bundles_list.append((bundle_name, latest_version)) + + return bundles_list + + +def get_bundle_versions( + bundle_name: str, repo: str = "Project-MONAI/model-zoo", tag: str = "dev", auth_token: str | None = None +) -> dict[str, list[str] | str]: + """ + Get the latest version, as well as all existing versions of a bundle that is stored in the release of specified + repository with the provided tag. If tag is "dev", will get model information from + https://raw.githubusercontent.com/repo_owner/repo_name/dev/models/model_info.json. + In order to increase the rate limits of calling Github APIs, you can input your personal access token. + Please check the following link for more details about rate limiting: + https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting + + The following link shows how to create your personal access token: + https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token + + Args: + bundle_name: bundle name. + repo: it should be in the form of "repo_owner/repo_name/". + tag: the tag name of the release. + auth_token: github personal access token. + + Returns: + a dictionary that contains the latest version and all versions of a bundle. + + """ + + bundles_info = _get_all_bundles_info(repo=repo, tag=tag, auth_token=auth_token) + if bundle_name not in bundles_info: + raise ValueError(f"bundle: {bundle_name} is not existing in repo: {repo}.") + bundle_info = bundles_info[bundle_name] + all_versions = sorted(bundle_info.keys()) + + return {"latest_version": all_versions[-1], "all_versions": all_versions} + + +def get_bundle_info( + bundle_name: str, + version: str | None = None, + repo: str = "Project-MONAI/model-zoo", + tag: str = "dev", + auth_token: str | None = None, +) -> dict[str, Any]: + """ + Get all information (include "name" and "browser_download_url") of a bundle + with the specified bundle name and version which is stored in the release of specified repository with the provided tag. + In order to increase the rate limits of calling Github APIs, you can input your personal access token. + Please check the following link for more details about rate limiting: + https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting + + The following link shows how to create your personal access token: + https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token + + Args: + bundle_name: bundle name. + version: version name of the target bundle, if None, the latest version will be used. + repo: it should be in the form of "repo_owner/repo_name/". + tag: the tag name of the release. + auth_token: github personal access token. + + Returns: + a dictionary that contains the bundle's information. + + """ + + bundles_info = _get_all_bundles_info(repo=repo, tag=tag, auth_token=auth_token) + if bundle_name not in bundles_info: + raise ValueError(f"bundle: {bundle_name} is not existing.") + bundle_info = bundles_info[bundle_name] + if version is None: + version = sorted(bundle_info.keys())[-1] + if version not in bundle_info: + raise ValueError(f"version: {version} of bundle: {bundle_name} is not existing.") + + return bundle_info[version] + + +def run( + run_id: str | None = None, + init_id: str | None = None, + final_id: str | None = None, + meta_file: str | Sequence[str] | None = None, + config_file: str | Sequence[str] | None = None, + logging_file: str | None = None, + tracking: str | dict | None = None, + args_file: str | None = None, + **override: Any, +) -> None: + """ + Specify `config_file` to run monai bundle components and workflows. + + Typical usage examples: + + .. code-block:: bash + + # Execute this module as a CLI entry: + python -m monai.bundle run --meta_file --config_file + + # Execute with specified `run_id=training`: + python -m monai.bundle run training --meta_file --config_file + + # Execute with all specified `run_id=runtest`, `init_id=inittest`, `final_id=finaltest`: + python -m monai.bundle run --run_id runtest --init_id inittest --final_id finaltest ... + + # Override config values at runtime by specifying the component id and its new value: + python -m monai.bundle run --net#input_chns 1 ... + + # Override config values with another config file `/path/to/another.json`: + python -m monai.bundle run --net %/path/to/another.json ... + + # Override config values with part content of another config file: + python -m monai.bundle run --net %/data/other.json#net_arg ... + + # Set default args of `run` in a JSON / YAML file, help to record and simplify the command line. + # Other args still can override the default args at runtime: + python -m monai.bundle run --args_file "/workspace/data/args.json" --config_file + + Args: + run_id: ID name of the expected config expression to run, default to "run". + to run the config, the target config must contain this ID. + init_id: ID name of the expected config expression to initialize before running, default to "initialize". + it's optional for both configs and this `run` function. + final_id: ID name of the expected config expression to finalize after running, default to "finalize". + it's optional for both configs and this `run` function. + meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged. + Default to None. + config_file: filepath of the config file, if `None`, must be provided in `args_file`. + if it is a list of file paths, the content of them will be merged. + logging_file: config file for `logging` module in the program. for more details: + https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig. + Default to None. + tracking: if not None, enable the experiment tracking at runtime with optionally configurable and extensible. + If "mlflow", will add `MLFlowHandler` to the parsed bundle with default tracking settings where a set of + common parameters shown below will be added and can be passed through the `override` parameter of this method. + + - ``"output_dir"``: the path to save mlflow tracking outputs locally, default to "/eval". + - ``"tracking_uri"``: uri to save mlflow tracking outputs, default to "/output_dir/mlruns". + - ``"experiment_name"``: experiment name for this run, default to "monai_experiment". + - ``"run_name"``: the name of current run. + - ``"save_execute_config"``: whether to save the executed config files. It can be `False`, `/path/to/artifacts` + or `True`. If set to `True`, will save to the default path "/eval". Default to `True`. + + If other string, treat it as file path to load the tracking settings. + If `dict`, treat it as tracking settings. + Will patch the target config content with `tracking handlers` and the top-level items of `configs`. + for detailed usage examples, please check the tutorial: + https://github.com/Project-MONAI/tutorials/blob/main/experiment_management/bundle_integrate_mlflow.ipynb. + args_file: a JSON or YAML file to provide default values for `run_id`, `meta_file`, + `config_file`, `logging`, and override pairs. so that the command line inputs can be simplified. + override: id-value pairs to override or add the corresponding config content. + e.g. ``--net#input_chns 42``, ``--net %/data/other.json#net_arg``. + + """ + + workflow = create_workflow( + config_file=config_file, + args_file=args_file, + meta_file=meta_file, + logging_file=logging_file, + init_id=init_id, + run_id=run_id, + final_id=final_id, + tracking=tracking, + **override, + ) + workflow.run() + workflow.finalize() + + +def run_workflow( + workflow_name: str | BundleWorkflow | None = None, args_file: str | None = None, **kwargs: Any +) -> None: + """ + Specify `bundle workflow` to run monai bundle components and workflows. + The workflow should be subclass of `BundleWorkflow` and be available to import. + It can be MONAI existing bundle workflows or user customized workflows. + + Typical usage examples: + + .. code-block:: bash + + # Execute this module as a CLI entry with default ConfigWorkflow: + python -m monai.bundle run_workflow --meta_file --config_file + + # Set the workflow to other customized BundleWorkflow subclass: + python -m monai.bundle run_workflow --workflow_name CustomizedWorkflow ... + + Args: + workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow". + args_file: a JSON or YAML file to provide default values for this API. + so that the command line inputs can be simplified. + kwargs: arguments to instantiate the workflow class. + + """ + + workflow_ = create_workflow(workflow_name=workflow_name, args_file=args_file, **kwargs) + workflow_.run() + workflow_.finalize() + + +def verify_metadata( + meta_file: str | Sequence[str] | None = None, + filepath: PathLike | None = None, + create_dir: bool | None = None, + hash_val: str | None = None, + hash_type: str | None = None, + args_file: str | None = None, + **kwargs: Any, +) -> None: + """ + Verify the provided `metadata` file based on the predefined `schema`. + `metadata` content must contain the `schema` field for the URL of schema file to download. + The schema standard follows: http://json-schema.org/. + + Args: + meta_file: filepath of the metadata file to verify, if `None`, must be provided in `args_file`. + if it is a list of file paths, the content of them will be merged. + filepath: file path to store the downloaded schema. + create_dir: whether to create directories if not existing, default to `True`. + hash_val: if not None, define the hash value to verify the downloaded schema file. + hash_type: if not None, define the hash type to verify the downloaded schema file. Defaults to "md5". + args_file: a JSON or YAML file to provide default values for all the args in this function. + so that the command line inputs can be simplified. + kwargs: other arguments for `jsonschema.validate()`. for more details: + https://python-jsonschema.readthedocs.io/en/stable/validate/#jsonschema.validate. + + """ + + _args = update_kwargs( + args=args_file, + meta_file=meta_file, + filepath=filepath, + create_dir=create_dir, + hash_val=hash_val, + hash_type=hash_type, + **kwargs, + ) + _log_input_summary(tag="verify_metadata", args=_args) + filepath_, meta_file_, create_dir_, hash_val_, hash_type_ = _pop_args( + _args, "filepath", "meta_file", create_dir=True, hash_val=None, hash_type="md5" + ) + + check_parent_dir(path=filepath_, create_dir=create_dir_) + metadata = ConfigParser.load_config_files(files=meta_file_) + url = metadata.get("schema") + if url is None: + raise ValueError("must provide the `schema` field in the metadata for the URL of schema file.") + download_url(url=url, filepath=filepath_, hash_val=hash_val_, hash_type=hash_type_, progress=True) + schema = ConfigParser.load_config_file(filepath=filepath_) + + try: + # the rest key-values in the _args are for `validate` API + validate(instance=metadata, schema=schema, **_args) + except ValidationError as e: # pylint: disable=E0712 + # as the error message is very long, only extract the key information + raise ValueError( + re.compile(r".*Failed validating", re.S).findall(str(e))[0] + f" against schema `{url}`." + ) from e + logger.info("metadata is verified with no error.") + + +def _get_net_io_info(parser: ConfigParser | None = None, prefix: str = "_meta_#network_data_format") -> tuple: + """ + Get the input and output information defined in the metadata. + + Args: + parser: a ConfigParser of the given bundle. + prefix: a prefix for the input and output ID, which will be combined as `prefix#inputs` and + `prefix#outputs` to parse the input and output information in the `metadata.json` file of + a bundle, default to `meta_#network_data_format`. + + Returns: + input_channels: the channel number of the `image` input. + input_spatial_shape: the spatial shape of the `image` input. + input_dtype: the data type of the `image` input. + output_channels: the channel number of the output. + output_dtype: the data type of the output. + """ + if not isinstance(parser, ConfigParser): + raise AttributeError(f"Parameter parser should be a ConfigParser, got {type(parser)}.") + + prefix_key = f"{prefix}#inputs" + key = f"{prefix_key}#image#num_channels" + input_channels = parser.get(key) + key = f"{prefix_key}#image#spatial_shape" + input_spatial_shape = tuple(parser.get(key)) + key = f"{prefix_key}#image#dtype" + input_dtype = get_equivalent_dtype(parser.get(key), torch.Tensor) + + prefix_key = f"{prefix}#outputs" + key = f"{prefix_key}#pred#num_channels" + output_channels = parser.get(key) + key = f"{prefix_key}#pred#dtype" + output_dtype = get_equivalent_dtype(parser.get(key), torch.Tensor) + + return input_channels, input_spatial_shape, input_dtype, output_channels, output_dtype + + +def _get_fake_input_shape(parser: ConfigParser) -> tuple: + """ + Get a fake input shape e.g. [N, C, H, W] or [N, C, H, W, D], whose batch size is 1, from the given parser. + + Args: + parser: a ConfigParser which contains the i/o information of a bundle. + """ + input_channels, input_spatial_shape, _, _, _ = _get_net_io_info(parser=parser) + spatial_shape = _get_fake_spatial_shape(input_spatial_shape) + input_shape = (1, input_channels, *spatial_shape) + return input_shape + + +def verify_net_in_out( + net_id: str | None = None, + meta_file: str | Sequence[str] | None = None, + config_file: str | Sequence[str] | None = None, + device: str | None = None, + p: int | None = None, + n: int | None = None, + any: int | None = None, + extra_forward_args: dict | None = None, + args_file: str | None = None, + **override: Any, +) -> None: + """ + Verify the input and output data shape and data type of network defined in the metadata. + Will test with fake Tensor data according to the required data shape in `metadata`. + + Typical usage examples: + + .. code-block:: bash + + python -m monai.bundle verify_net_in_out network --meta_file --config_file + + Args: + net_id: ID name of the network component to verify, it must be `torch.nn.Module`. + meta_file: filepath of the metadata file to get network args, if `None`, must be provided in `args_file`. + if it is a list of file paths, the content of them will be merged. + config_file: filepath of the config file to get network definition, if `None`, must be provided in `args_file`. + if it is a list of file paths, the content of them will be merged. + device: target device to run the network forward computation, if None, prefer to "cuda" if existing. + p: power factor to generate fake data shape if dim of expected shape is "x**p", default to 1. + n: multiply factor to generate fake data shape if dim of expected shape is "x*n", default to 1. + any: specified size to generate fake data shape if dim of expected shape is "*", default to 1. + extra_forward_args: a dictionary that contains other args for the forward function of the network. + Default to an empty dictionary. + args_file: a JSON or YAML file to provide default values for `net_id`, `meta_file`, `config_file`, + `device`, `p`, `n`, `any`, and override pairs. so that the command line inputs can be simplified. + override: id-value pairs to override or add the corresponding config content. + e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``. + + """ + + _args = update_kwargs( + args=args_file, + net_id=net_id, + meta_file=meta_file, + config_file=config_file, + device=device, + p=p, + n=n, + any=any, + extra_forward_args=extra_forward_args, + **override, + ) + _log_input_summary(tag="verify_net_in_out", args=_args) + config_file_, meta_file_, net_id_, device_, p_, n_, any_, extra_forward_args_ = _pop_args( + _args, + "config_file", + "meta_file", + net_id="", + device="cuda:0" if is_available() else "cpu", + p=1, + n=1, + any=1, + extra_forward_args={}, + ) + + parser = ConfigParser() + parser.read_config(f=config_file_) + parser.read_meta(f=meta_file_) + + # the rest key-values in the _args are to override config content + for k, v in _args.items(): + parser[k] = v + + input_channels, input_spatial_shape, input_dtype, output_channels, output_dtype = _get_net_io_info(parser=parser) + try: + key: str = net_id_ # mark the full id when KeyError + net = parser.get_parsed_content(key).to(device_) + except KeyError as e: + raise KeyError(f"Failed to verify due to missing expected key in the config: {key}.") from e + + net.eval() + with torch.no_grad(): + spatial_shape = _get_fake_spatial_shape(input_spatial_shape, p=p_, n=n_, any=any_) + test_data = torch.rand(*(1, input_channels, *spatial_shape), dtype=input_dtype, device=device_) + if input_dtype == torch.float16: + # fp16 can only be executed in gpu mode + net.to("cuda") + from torch.cuda.amp import autocast + + with autocast(): + output = net(test_data.cuda(), **extra_forward_args_) + net.to(device_) + else: + output = net(test_data, **extra_forward_args_) + if output.shape[1] != output_channels: + raise ValueError(f"output channel number `{output.shape[1]}` doesn't match: `{output_channels}`.") + if output.dtype != output_dtype: + raise ValueError(f"dtype of output data `{output.dtype}` doesn't match: {output_dtype}.") + logger.info("data shape of network is verified with no error.") + + +def _export( + converter: Callable, + parser: ConfigParser, + net_id: str, + filepath: str, + ckpt_file: str, + config_file: str, + key_in_ckpt: str, + **kwargs: Any, +) -> None: + """ + Export a model defined in the parser to a new one specified by the converter. + + Args: + converter: a callable object that takes a torch.nn.module and kwargs as input and + converts the module to another type. + parser: a ConfigParser of the bundle to be converted. + net_id: ID name of the network component in the parser, it must be `torch.nn.Module`. + filepath: filepath to export, if filename has no extension, it becomes `.ts`. + ckpt_file: filepath of the model checkpoint to load. + config_file: filepath of the config file to save in the converted model,the saved key in the converted + model is the config filename without extension, and the saved config value is always serialized in + JSON format no matter the original file format is JSON or YAML. it can be a single file or a list + of files. + key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model + weights. if not nested checkpoint, no need to set. + kwargs: key arguments for the converter. + + """ + net = parser.get_parsed_content(net_id) + if has_ignite: + # here we use ignite Checkpoint to support nested weights and be compatible with MONAI CheckpointSaver + Checkpoint.load_objects(to_load={key_in_ckpt: net}, checkpoint=ckpt_file) + else: + ckpt = torch.load(ckpt_file) + copy_model_state(dst=net, src=ckpt if key_in_ckpt == "" else ckpt[key_in_ckpt]) + + # Use the given converter to convert a model and save with metadata, config content + net = converter(model=net, **kwargs) + + extra_files: dict = {} + for i in ensure_tuple(config_file): + # split the filename and directory + filename = os.path.basename(i) + # remove extension + filename, _ = os.path.splitext(filename) + # because all files are stored as JSON their name parts without extension must be unique + if filename in extra_files: + raise ValueError(f"Filename part '{filename}' is given multiple times in config file list.") + # the file may be JSON or YAML but will get loaded and dumped out again as JSON + extra_files[filename] = json.dumps(ConfigParser.load_config_file(i)).encode() + + # add .json extension to all extra files which are always encoded as JSON + extra_files = {k + ".json": v for k, v in extra_files.items()} + + save_net_with_metadata( + jit_obj=net, + filename_prefix_or_stream=filepath, + include_config_vals=False, + append_timestamp=False, + meta_values=parser.get().pop("_meta_", None), + more_extra_files=extra_files, + ) + logger.info(f"exported to file: {filepath}.") + + +def onnx_export( + net_id: str | None = None, + filepath: PathLike | None = None, + ckpt_file: str | None = None, + meta_file: str | Sequence[str] | None = None, + config_file: str | Sequence[str] | None = None, + key_in_ckpt: str | None = None, + use_trace: bool | None = None, + input_shape: Sequence[int] | None = None, + args_file: str | None = None, + converter_kwargs: Mapping | None = None, + **override: Any, +) -> None: + """ + Export the model checkpoint to an onnx model. + + Typical usage examples: + + .. code-block:: bash + + python -m monai.bundle onnx_export network --filepath --ckpt_file ... + + Args: + net_id: ID name of the network component in the config, it must be `torch.nn.Module`. + filepath: filepath where the onnx model is saved to. + ckpt_file: filepath of the model checkpoint to load. + meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged. + config_file: filepath of the config file that contains extract network information, + key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model + weights. if not nested checkpoint, no need to set. + use_trace: whether using `torch.jit.trace` to convert the pytorch model to torchscript model. + input_shape: a shape used to generate the random input of the network, when converting the model to an + onnx model. Should be a list like [N, C, H, W] or [N, C, H, W, D]. If not given, will try to parse from + the `metadata` config. + args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that + the command line inputs can be simplified. + converter_kwargs: extra arguments that are needed by `convert_to_onnx`, except ones that already exist in the + input parameters. + override: id-value pairs to override or add the corresponding config content. + e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``. + + """ + _args = update_kwargs( + args=args_file, + net_id=net_id, + filepath=filepath, + meta_file=meta_file, + config_file=config_file, + ckpt_file=ckpt_file, + key_in_ckpt=key_in_ckpt, + use_trace=use_trace, + input_shape=input_shape, + converter_kwargs=converter_kwargs, + **override, + ) + _log_input_summary(tag="onnx_export", args=_args) + ( + filepath_, + ckpt_file_, + config_file_, + net_id_, + meta_file_, + key_in_ckpt_, + use_trace_, + input_shape_, + converter_kwargs_, + ) = _pop_args( + _args, + "filepath", + "ckpt_file", + "config_file", + net_id="", + meta_file=None, + key_in_ckpt="", + use_trace=False, + input_shape=None, + converter_kwargs={}, + ) + + parser = ConfigParser() + + parser.read_config(f=config_file_) + if meta_file_ is not None: + parser.read_meta(f=meta_file_) + + # the rest key-values in the _args are to override config content + for k, v in _args.items(): + parser[k] = v + + # The convert_to_onnx must have an `inputs` as input, no matter what the `use_trace` is. + # If the `input_shape` is not provided, will try to parse it from the parser to generate a random `inputs`. + if not input_shape_: + input_shape_ = _get_fake_input_shape(parser=parser) + + inputs_ = [torch.rand(input_shape_)] + net = parser.get_parsed_content(net_id_) + if has_ignite: + # here we use ignite Checkpoint to support nested weights and be compatible with MONAI CheckpointSaver + Checkpoint.load_objects(to_load={key_in_ckpt_: net}, checkpoint=ckpt_file_) + else: + ckpt = torch.load(ckpt_file_) + copy_model_state(dst=net, src=ckpt if key_in_ckpt_ == "" else ckpt[key_in_ckpt_]) + + converter_kwargs_.update({"inputs": inputs_, "use_trace": use_trace_}) + onnx_model = convert_to_onnx(model=net, **converter_kwargs_) + onnx.save(onnx_model, filepath_) + + +def ckpt_export( + net_id: str | None = None, + filepath: PathLike | None = None, + ckpt_file: str | None = None, + meta_file: str | Sequence[str] | None = None, + config_file: str | Sequence[str] | None = None, + key_in_ckpt: str | None = None, + use_trace: bool | None = None, + input_shape: Sequence[int] | None = None, + args_file: str | None = None, + converter_kwargs: Mapping | None = None, + **override: Any, +) -> None: + """ + Export the model checkpoint to the given filepath with metadata and config included as JSON files. + + Typical usage examples: + + .. code-block:: bash + + python -m monai.bundle ckpt_export network --filepath --ckpt_file ... + + Args: + net_id: ID name of the network component in the config, it must be `torch.nn.Module`. + Default to "network_def". + filepath: filepath to export, if filename has no extension it becomes `.ts`. + Default to "models/model.ts" under "os.getcwd()" if `bundle_root` is not specified. + ckpt_file: filepath of the model checkpoint to load. + Default to "models/model.pt" under "os.getcwd()" if `bundle_root` is not specified. + meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged. + Default to "configs/metadata.json" under "os.getcwd()" if `bundle_root` is not specified. + config_file: filepath of the config file to save in TorchScript model and extract network information, + the saved key in the TorchScript model is the config filename without extension, and the saved config + value is always serialized in JSON format no matter the original file format is JSON or YAML. + it can be a single file or a list of files. if `None`, must be provided in `args_file`. + key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model + weights. if not nested checkpoint, no need to set. + use_trace: whether using `torch.jit.trace` to convert the PyTorch model to TorchScript model. + input_shape: a shape used to generate the random input of the network, when converting the model to a + TorchScript model. Should be a list like [N, C, H, W] or [N, C, H, W, D]. If not given, will try to + parse from the `metadata` config. + args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that + the command line inputs can be simplified. + converter_kwargs: extra arguments that are needed by `convert_to_torchscript`, except ones that already exist + in the input parameters. + override: id-value pairs to override or add the corresponding config content. + e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``. + + """ + _args = update_kwargs( + args=args_file, + net_id=net_id, + filepath=filepath, + meta_file=meta_file, + config_file=config_file, + ckpt_file=ckpt_file, + key_in_ckpt=key_in_ckpt, + use_trace=use_trace, + input_shape=input_shape, + converter_kwargs=converter_kwargs, + **override, + ) + _log_input_summary(tag="ckpt_export", args=_args) + ( + config_file_, + filepath_, + ckpt_file_, + net_id_, + meta_file_, + key_in_ckpt_, + use_trace_, + input_shape_, + converter_kwargs_, + ) = _pop_args( + _args, + "config_file", + filepath=None, + ckpt_file=None, + net_id=None, + meta_file=None, + key_in_ckpt="", + use_trace=False, + input_shape=None, + converter_kwargs={}, + ) + bundle_root = _args.get("bundle_root", os.getcwd()) + + parser = ConfigParser() + parser.read_config(f=config_file_) + meta_file_ = os.path.join(bundle_root, "configs", "metadata.json") if meta_file_ is None else meta_file_ + if os.path.exists(meta_file_): + parser.read_meta(f=meta_file_) + + # the rest key-values in the _args are to override config content + for k, v in _args.items(): + parser[k] = v + + filepath_ = os.path.join(bundle_root, "models", "model.ts") if filepath_ is None else filepath_ + ckpt_file_ = os.path.join(bundle_root, "models", "model.pt") if ckpt_file_ is None else ckpt_file_ + if not os.path.exists(ckpt_file_): + raise FileNotFoundError(f'Checkpoint file "{ckpt_file_}" not found, please specify it in argument "ckpt_file".') + + net_id_ = "network_def" if net_id_ is None else net_id_ + try: + parser.get_parsed_content(net_id_) + except ValueError as e: + raise ValueError( + f'Network definition "{net_id_}" cannot be found in "{config_file_}", specify name with argument "net_id".' + ) from e + + # When export through torch.jit.trace without providing input_shape, will try to parse one from the parser. + if (not input_shape_) and use_trace: + input_shape_ = _get_fake_input_shape(parser=parser) + + inputs_: Sequence[Any] | None = [torch.rand(input_shape_)] if input_shape_ else None + + converter_kwargs_.update({"inputs": inputs_, "use_trace": use_trace_}) + # Use the given converter to convert a model and save with metadata, config content + _export( + convert_to_torchscript, + parser, + net_id=net_id_, + filepath=filepath_, + ckpt_file=ckpt_file_, + config_file=config_file_, + key_in_ckpt=key_in_ckpt_, + **converter_kwargs_, + ) + + +def trt_export( + net_id: str | None = None, + filepath: PathLike | None = None, + ckpt_file: str | None = None, + meta_file: str | Sequence[str] | None = None, + config_file: str | Sequence[str] | None = None, + key_in_ckpt: str | None = None, + precision: str | None = None, + input_shape: Sequence[int] | None = None, + use_trace: bool | None = None, + dynamic_batchsize: Sequence[int] | None = None, + device: int | None = None, + use_onnx: bool | None = None, + onnx_input_names: Sequence[str] | None = None, + onnx_output_names: Sequence[str] | None = None, + args_file: str | None = None, + converter_kwargs: Mapping | None = None, + **override: Any, +) -> None: + """ + Export the model checkpoint to the given filepath as a TensorRT engine-based TorchScript. + Currently, this API only supports converting models whose inputs are all tensors. + + There are two ways to export a model: + 1, Torch-TensorRT way: PyTorch module ---> TorchScript module ---> TensorRT engine-based TorchScript. + 2, ONNX-TensorRT way: PyTorch module ---> TorchScript module ---> ONNX model ---> TensorRT engine ---> + TensorRT engine-based TorchScript. + + When exporting through the first way, some models suffer from the slowdown problem, since Torch-TensorRT + may only convert a little part of the PyTorch model to the TensorRT engine. However when exporting through + the second way, some Python data structures like `dict` are not supported. And some TorchScript models are + not supported by the ONNX if exported through `torch.jit.script`. + + Typical usage examples: + + .. code-block:: bash + + python -m monai.bundle trt_export --net_id --filepath \ + --ckpt_file --input_shape --dynamic_batchsize ... + + Args: + net_id: ID name of the network component in the config, it must be `torch.nn.Module`. + filepath: filepath to export, if filename has no extension, it becomes `.ts`. + ckpt_file: filepath of the model checkpoint to load. + meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged. + config_file: filepath of the config file to save in the TensorRT based TorchScript model and extract network + information, the saved key in the model is the config filename without extension, and the saved config + value is always serialized in JSON format no matter the original file format is JSON or YAML. + it can be a single file or a list of files. if `None`, must be provided in `args_file`. + key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model + weights. if not nested checkpoint, no need to set. + precision: the weight precision of the converted TensorRT engine based TorchScript models. Should be 'fp32' or 'fp16'. + input_shape: the input shape that is used to convert the model. Should be a list like [N, C, H, W] or + [N, C, H, W, D]. If not given, will try to parse from the `metadata` config. + use_trace: whether using `torch.jit.trace` to convert the PyTorch model to a TorchScript model and then convert to + a TensorRT engine based TorchScript model or an ONNX model (if `use_onnx` is True). + dynamic_batchsize: a sequence with three elements to define the batch size range of the input for the model to be + converted. Should be a sequence like [MIN_BATCH, OPT_BATCH, MAX_BATCH]. After converted, the batchsize of + model input should between `MIN_BATCH` and `MAX_BATCH` and the `OPT_BATCH` is the best performance batchsize + that the TensorRT tries to fit. The `OPT_BATCH` should be the most frequently used input batchsize in + the application. + device: the target GPU index to convert and verify the model. + use_onnx: whether using the ONNX-TensorRT way to export the TensorRT engine-based TorchScript model. + onnx_input_names: optional input names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be + a sequence like `['input_0', 'input_1', ..., 'input_N']` where N equals to the number of the model inputs. If not + given, will use `['input_0']`, which supposes the model only has one input. + onnx_output_names: optional output names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be + a sequence like `['output_0', 'output_1', ..., 'output_N']` where N equals to the number of the model outputs. If + not given, will use `['output_0']`, which supposes the model only has one output. + args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that + the command line inputs can be simplified. + converter_kwargs: extra arguments that are needed by `convert_to_trt`, except ones that already exist in the + input parameters. + override: id-value pairs to override or add the corresponding config content. + e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``. + + """ + _args = update_kwargs( + args=args_file, + net_id=net_id, + filepath=filepath, + meta_file=meta_file, + config_file=config_file, + ckpt_file=ckpt_file, + key_in_ckpt=key_in_ckpt, + precision=precision, + input_shape=input_shape, + use_trace=use_trace, + dynamic_batchsize=dynamic_batchsize, + device=device, + use_onnx=use_onnx, + onnx_input_names=onnx_input_names, + onnx_output_names=onnx_output_names, + converter_kwargs=converter_kwargs, + **override, + ) + _log_input_summary(tag="trt_export", args=_args) + ( + filepath_, + ckpt_file_, + config_file_, + net_id_, + meta_file_, + key_in_ckpt_, + precision_, + input_shape_, + use_trace_, + dynamic_batchsize_, + device_, + use_onnx_, + onnx_input_names_, + onnx_output_names_, + converter_kwargs_, + ) = _pop_args( + _args, + "filepath", + "ckpt_file", + "config_file", + net_id="", + meta_file=None, + key_in_ckpt="", + precision="fp32", + input_shape=[], + use_trace=False, + dynamic_batchsize=None, + device=None, + use_onnx=False, + onnx_input_names=["input_0"], + onnx_output_names=["output_0"], + converter_kwargs={}, + ) + + parser = ConfigParser() + + parser.read_config(f=config_file_) + if meta_file_ is not None: + parser.read_meta(f=meta_file_) + + # the rest key-values in the _args are to override config content + for k, v in _args.items(): + parser[k] = v + + # The convert_to_trt must have an `input_shape_` as input, no matter what the `use_trace` is. + # If the `input_shape` is not provided, will try to parse it from the parser`. + if not input_shape_: + input_shape_ = _get_fake_input_shape(parser=parser) + + trt_api_parameters = { + "precision": precision_, + "input_shape": input_shape_, + "dynamic_batchsize": dynamic_batchsize_, + "use_trace": use_trace_, + "device": device_, + "use_onnx": use_onnx_, + "onnx_input_names": onnx_input_names_, + "onnx_output_names": onnx_output_names_, + } + converter_kwargs_.update(trt_api_parameters) + + _export( + convert_to_trt, + parser, + net_id=net_id_, + filepath=filepath_, + ckpt_file=ckpt_file_, + config_file=config_file_, + key_in_ckpt=key_in_ckpt_, + **converter_kwargs_, + ) + + +def init_bundle( + bundle_dir: PathLike, + ckpt_file: PathLike | None = None, + network: torch.nn.Module | None = None, + dataset_license: bool = False, + metadata_str: dict | str | None = None, + inference_str: dict | str | None = None, +) -> None: + """ + Initialise a new bundle directory with some default configuration files and optionally network weights. + + Typical usage example: + + .. code-block:: bash + + python -m monai.bundle init_bundle /path/to/bundle_dir network_ckpt.pt + + Args: + bundle_dir: directory name to create, must not exist but parent direct must exist + ckpt_file: optional checkpoint file to copy into bundle + network: if given instead of ckpt_file this network's weights will be stored in bundle + dataset_license: if `True`, a default license file called "data_license.txt" will be produced. This + file is required if there are any license conditions stated for data your bundle uses. + metadata_str: optional metadata string to write to bundle, if not given a default will be used. + inference_str: optional inference string to write to bundle, if not given a default will be used. + """ + if metadata_str is None: + metadata_str = DEFAULT_METADATA + if inference_str is None: + inference_str = DEFAULT_INFERENCE + + bundle_dir = Path(bundle_dir).absolute() + + if bundle_dir.exists(): + raise ValueError(f"Specified bundle directory '{str(bundle_dir)}' already exists") + + if not bundle_dir.parent.is_dir(): + raise ValueError(f"Parent directory of specified bundle directory '{str(bundle_dir)}' does not exist") + + configs_dir = bundle_dir / "configs" + models_dir = bundle_dir / "models" + docs_dir = bundle_dir / "docs" + + bundle_dir.mkdir() + configs_dir.mkdir() + models_dir.mkdir() + docs_dir.mkdir() + + if isinstance(metadata_str, dict): + metadata_str = json.dumps(metadata_str, indent=4) + + if isinstance(inference_str, dict): + inference_str = json.dumps(inference_str, indent=4) + + with open(str(configs_dir / "metadata.json"), "w") as o: + o.write(metadata_str) + + with open(str(configs_dir / "inference.json"), "w") as o: + o.write(inference_str) + + with open(str(docs_dir / "README.md"), "w") as o: + readme = """ + # Your Model Name + + Describe your model here and how to run it, for example using `inference.json`: + + ``` + python -m monai.bundle run \ + --meta_file /path/to/bundle/configs/metadata.json \ + --config_file /path/to/bundle/configs/inference.json \ + --dataset_dir ./input \ + --bundle_root /path/to/bundle + ``` + """ + + o.write(dedent(readme)) + + with open(str(bundle_dir / "LICENSE"), "w") as o: + o.write("Select a license and place its terms here\n") + + if dataset_license is True: + with open(str(docs_dir / "data_license.txt"), "w") as o: + o.write("Select a license for dataset and place its terms here\n") + + if ckpt_file is not None: + copyfile(str(ckpt_file), str(models_dir / "model.pt")) + elif network is not None: + save_state(network, str(models_dir / "model.pt")) + + +def _add_model_card_metadata(new_modelcard_path): + # Extract license from LICENSE file + license_name = "unknown" + license_path = os.path.join(os.path.dirname(new_modelcard_path), "LICENSE") + if os.path.exists(license_path): + with open(license_path) as file: + content = file.read() + if "Apache License" in content and "Version 2.0" in content: + license_name = "apache-2.0" + elif "MIT License" in content: + license_name = "mit" + # Add relevant tags + tags = "- monai\n- medical\nlibrary_name: monai\n" + # Create tag section + tag_content = f"---\ntags:\n{tags}license: {license_name}\n---" + + # Update model card + with open(new_modelcard_path) as file: + content = file.read() + new_content = tag_content + "\n" + content + with open(new_modelcard_path, "w") as file: + file.write(new_content) + + +def push_to_hf_hub( + repo: str, + name: str, + bundle_dir: str, + token: str | None = None, + private: bool | None = True, + version: str | None = None, + tag_as_latest_version: bool | None = False, + **upload_folder_kwargs: Any, +) -> Any: + """ + Push a MONAI bundle to the Hugging Face Hub. + + Typical usage examples: + + .. code-block:: bash + + python -m monai.bundle push_to_hf_hub --repo --name \ + --bundle_dir --version ... + + Args: + repo: namespace (user or organization) and a repo name separated by a /, e.g. `hf_username/bundle_name` + bundle_name: name of the bundle directory to push. + bundle_dir: path to the bundle directory. + token: Hugging Face authentication token. Default is `None` (will default to the stored token). + private: Private visibility of the repository on Hugging Face. Default is `True`. + version_name: Name of the version tag to create. Default is `None` (no version tag is created). + tag_as_latest_version: Whether to tag the commit as `latest_version`. + This version will downloaded by default when using `bundle.download()`. Default is `False`. + upload_folder_kwargs: Keyword arguments to pass to `HfApi.upload_folder`. + + Returns: + repo_url: URL of the Hugging Face repo + """ + # Connect to API and create repo + hf_api = huggingface_hub.HfApi(token=token) + hf_api.create_repo(repo_id=repo, private=private, exist_ok=True) + + # Create model card in bundle directory + new_modelcard_path = os.path.join(bundle_dir, name, "README.md") + modelcard_path = os.path.join(bundle_dir, name, "docs", "README.md") + if os.path.exists(modelcard_path): + # Copy README from old path if it exists + copyfile(modelcard_path, new_modelcard_path) + _add_model_card_metadata(new_modelcard_path) + + # Upload bundle folder to repo + repo_url = hf_api.upload_folder(repo_id=repo, folder_path=os.path.join(bundle_dir, name), **upload_folder_kwargs) + + # Create version tag if specified + if version is not None: + hf_api.create_tag(repo_id=repo, tag=version, exist_ok=True) + + # Optionally tag as `latest_version` + if tag_as_latest_version: + hf_api.create_tag(repo_id=repo, tag="latest_version", exist_ok=True) + + return repo_url + + +def create_workflow( + workflow_name: str | BundleWorkflow | None = None, + config_file: str | Sequence[str] | None = None, + args_file: str | None = None, + **kwargs: Any, +) -> Any: + """ + Specify `bundle workflow` to create monai bundle workflows. + The workflow should be subclass of `BundleWorkflow` and be available to import. + It can be MONAI existing bundle workflows or user customized workflows. + + Typical usage examples: + + .. code-block:: python + + # Specify config_file path to create workflow: + workflow = create_workflow(config_file="/workspace/spleen_ct_segmentation/configs/train.json", workflow_type="train") + + # Set the workflow to other customized BundleWorkflow subclass to create workflow: + workflow = create_workflow(workflow_name=CustomizedWorkflow) + + Args: + workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow". + config_file: filepath of the config file, if it is a list of file paths, the content of them will be merged. + args_file: a JSON or YAML file to provide default values for this API. + so that the command line inputs can be simplified. + kwargs: arguments to instantiate the workflow class. + + """ + _args = update_kwargs(args=args_file, workflow_name=workflow_name, config_file=config_file, **kwargs) + _log_input_summary(tag="run", args=_args) + (workflow_name, config_file) = _pop_args( + _args, workflow_name=ConfigWorkflow, config_file=None + ) # the default workflow name is "ConfigWorkflow" + if isinstance(workflow_name, str): + workflow_class, has_built_in = optional_import("monai.bundle", name=str(workflow_name)) # search built-in + if not has_built_in: + workflow_class = locate(str(workflow_name)) # search dotted path + if workflow_class is None: + raise ValueError(f"cannot locate specified workflow class: {workflow_name}.") + elif issubclass(workflow_name, BundleWorkflow): # type: ignore + workflow_class = workflow_name + else: + raise ValueError( + "Argument `workflow_name` must be a bundle workflow class name" + f"or subclass of BundleWorkflow, got: {workflow_name}." + ) + + if config_file is not None: + workflow_ = workflow_class(config_file=config_file, **_args) + else: + workflow_ = workflow_class(**_args) + + workflow_.initialize() + + return workflow_ + + +def download_large_files(bundle_path: str | None = None, large_file_name: str | None = None) -> None: + """ + This utility allows you to download large files from a bundle. It supports file suffixes like ".yml", ".yaml", and ".json". + If you don't specify a `large_file_name`, it will automatically search for large files among the supported suffixes. + + Typical usage examples: + .. code-block:: bash + + # Execute this module as a CLI entry to download large files from a bundle path: + python -m monai.bundle download_large_files --bundle_path + + # Execute this module as a CLI entry to download large files from the bundle path with a specified `large_file_name`: + python -m monai.bundle download_large_files --bundle_path --large_file_name large_files.yaml + + Args: + bundle_path: (Optional) The path to the bundle where the files are located. Default is `os.getcwd()`. + large_file_name: (Optional) The name of the large file to be downloaded. + + """ + bundle_path = os.getcwd() if bundle_path is None else bundle_path + if large_file_name is None: + large_file_path = list(Path(bundle_path).glob("large_files*")) + large_file_path = list(filter(lambda x: x.suffix in [".yml", ".yaml", ".json"], large_file_path)) + if len(large_file_path) == 0: + raise FileNotFoundError(f"Cannot find the large_files.yml/yaml/json under {bundle_path}.") + + parser = ConfigParser() + parser.read_config(large_file_path) + large_files_list = parser.get()["large_files"] + for lf_data in large_files_list: + lf_data["fuzzy"] = True + if "hash_val" in lf_data and lf_data.get("hash_val", "") == "": + lf_data.pop("hash_val") + if "hash_type" in lf_data and lf_data.get("hash_type", "") == "": + lf_data.pop("hash_type") + lf_data["filepath"] = os.path.join(bundle_path, lf_data["path"]) + lf_data.pop("path") + download_url(**lf_data) diff --git a/source_code/SegMamba/monai/bundle/utils.py b/source_code/SegMamba/monai/bundle/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f39d236f95e14c6feae4eab7a227f805c591ff --- /dev/null +++ b/source_code/SegMamba/monai/bundle/utils.py @@ -0,0 +1,232 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import json +import os +import zipfile +from typing import Any + +from monai.config.deviceconfig import get_config_values +from monai.utils import optional_import + +yaml, _ = optional_import("yaml") + +__all__ = ["ID_REF_KEY", "ID_SEP_KEY", "EXPR_KEY", "MACRO_KEY", "DEFAULT_MLFLOW_SETTINGS", "DEFAULT_EXP_MGMT_SETTINGS"] + +ID_REF_KEY = "@" # start of a reference to a ConfigItem +ID_SEP_KEY = "::" # separator for the ID of a ConfigItem +EXPR_KEY = "$" # start of a ConfigExpression +MACRO_KEY = "%" # start of a macro of a config + +_conf_values = get_config_values() + +DEFAULT_METADATA = { + "version": "0.0.1", + "changelog": {"0.0.1": "Initial version"}, + "monai_version": _conf_values["MONAI"], + "pytorch_version": str(_conf_values["Pytorch"]).split("+")[0].split("a")[0], # 1.9.0a0+df837d0 or 1.13.0+cu117 + "numpy_version": _conf_values["Numpy"], + "optional_packages_version": {}, + "task": "Describe what the network predicts", + "description": "A longer description of what the network does, use context, inputs, outputs, etc.", + "authors": "Your Name Here", + "copyright": "Copyright (c) Your Name Here", + "network_data_format": {"inputs": {}, "outputs": {}}, +} + +DEFAULT_INFERENCE = { + "imports": ["$import glob"], + "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", + "ckpt_path": "$@bundle_root + '/models/model.pt'", + "dataset_dir": "/workspace/data", + "datalist": "$list(sorted(glob.glob(@dataset_dir + '/*.jpeg')))", + "network_def": {"_target_": "???", "spatial_dims": 2}, + "network": "$@network_def.to(@device)", + "preprocessing": { + "_target_": "Compose", + "transforms": [ + {"_target_": "LoadImaged", "keys": "image"}, + {"_target_": "EnsureChannelFirstd", "keys": "image"}, + {"_target_": "ScaleIntensityd", "keys": "image"}, + {"_target_": "EnsureTyped", "keys": "image", "device": "@device"}, + ], + }, + "dataset": {"_target_": "Dataset", "data": "$[{'image': i} for i in @datalist]", "transform": "@preprocessing"}, + "dataloader": { + "_target_": "DataLoader", + "dataset": "@dataset", + "batch_size": 1, + "shuffle": False, + "num_workers": 0, + }, + "inferer": {"_target_": "SimpleInferer"}, + "postprocessing": { + "_target_": "Compose", + "transforms": [ + {"_target_": "Activationsd", "keys": "pred", "softmax": True}, + {"_target_": "AsDiscreted", "keys": "pred", "argmax": True}, + ], + }, + "handlers": [ + { + "_target_": "CheckpointLoader", + "_disabled_": "$not os.path.exists(@ckpt_path)", + "load_path": "@ckpt_path", + "load_dict": {"model": "@network"}, + } + ], + "evaluator": { + "_target_": "SupervisedEvaluator", + "device": "@device", + "val_data_loader": "@dataloader", + "network": "@network", + "inferer": "@inferer", + "postprocessing": "@postprocessing", + "val_handlers": "@handlers", + }, + "evaluating": ["$@evaluator.run()"], +} + +DEFAULT_HANDLERS_ID = { + "trainer": {"id": "train#trainer", "handlers": "train#handlers"}, + "validator": {"id": "validate#evaluator", "handlers": "validate#handlers"}, + "evaluator": {"id": "evaluator", "handlers": "handlers"}, +} + +DEFAULT_MLFLOW_SETTINGS = { + "handlers_id": DEFAULT_HANDLERS_ID, + "configs": { + # if no "output_dir" in the bundle config, default to "/eval" + "output_dir": "$@bundle_root + '/eval'", + # use URI to support linux, mac and windows os + "tracking_uri": "$monai.utils.path_to_uri(@output_dir) + '/mlruns'", + "experiment_name": "monai_experiment", + "run_name": None, + # may fill it at runtime + "save_execute_config": True, + "is_not_rank0": ( + "$torch.distributed.is_available() \ + and torch.distributed.is_initialized() and torch.distributed.get_rank() > 0" + ), + # MLFlowHandler config for the trainer + "trainer": { + "_target_": "MLFlowHandler", + "_disabled_": "@is_not_rank0", + "tracking_uri": "@tracking_uri", + "experiment_name": "@experiment_name", + "run_name": "@run_name", + "artifacts": "@save_execute_config", + "iteration_log": True, + "epoch_log": True, + "tag_name": "train_loss", + "output_transform": "$monai.handlers.from_engine(['loss'], first=True)", + "close_on_complete": True, + }, + # MLFlowHandler config for the validator + "validator": { + "_target_": "MLFlowHandler", + "_disabled_": "@is_not_rank0", + "tracking_uri": "@tracking_uri", + "experiment_name": "@experiment_name", + "run_name": "@run_name", + "iteration_log": False, + }, + # MLFlowHandler config for the evaluator + "evaluator": { + "_target_": "MLFlowHandler", + "_disabled_": "@is_not_rank0", + "tracking_uri": "@tracking_uri", + "experiment_name": "@experiment_name", + "run_name": "@run_name", + "artifacts": "@save_execute_config", + "iteration_log": False, + "close_on_complete": True, + }, + }, +} + +DEFAULT_EXP_MGMT_SETTINGS = {"mlflow": DEFAULT_MLFLOW_SETTINGS} # default experiment management settings + + +def load_bundle_config(bundle_path: str, *config_names: str, **load_kw_args: Any) -> Any: + """ + Load the metadata and nominated configuration files from a MONAI bundle without loading the network itself. + + This function will load the information from the bundle, which can be a directory or a zip file containing a + directory or a Torchscript bundle, and return the parser object with the information. This saves having to load + the model if only the information is wanted, and can work on any sort of bundle format. + + Args: + bundle_path: path to the bundle directory or zip file + config_names: names of configuration files with extensions to load, should not be full paths but just name+ext + load_kw_args: keyword arguments to pass to the ConfigParser object when loading + + Returns: + ConfigParser object containing the parsed information + """ + + from monai.bundle.config_parser import ConfigParser # avoids circular import + + parser = ConfigParser() + + if not os.path.exists(bundle_path): + raise ValueError(f"Cannot find bundle file/directory '{bundle_path}'") + + # bundle is a directory, read files directly + if os.path.isdir(bundle_path): + conf_data = [] + parser.read_meta(f=os.path.join(bundle_path, "configs", "metadata.json"), **load_kw_args) + + for cname in config_names: + cpath = os.path.join(bundle_path, "configs", cname) + if not os.path.exists(cpath): + raise ValueError(f"Cannot find config file '{cpath}'") + + conf_data.append(cpath) + + parser.read_config(f=conf_data, **load_kw_args) + else: + # bundle is a zip file which is either a zipped directory or a Torchscript archive + + name, _ = os.path.splitext(os.path.basename(bundle_path)) + + archive = zipfile.ZipFile(bundle_path, "r") + + all_files = archive.namelist() + + zip_meta_name = f"{name}/configs/metadata.json" + + if zip_meta_name in all_files: + prefix = f"{name}/configs/" # zipped directory location for files + else: + zip_meta_name = f"{name}/extra/metadata.json" + prefix = f"{name}/extra/" # Torchscript location for files + + meta_json = json.loads(archive.read(zip_meta_name)) + parser.read_meta(f=meta_json) + + for cname in config_names: + full_cname = prefix + cname + if full_cname not in all_files: + raise ValueError(f"Cannot find config file '{full_cname}'") + + ardata = archive.read(full_cname) + + if full_cname.lower().endswith("json"): + cdata = json.loads(ardata, **load_kw_args) + elif full_cname.lower().endswith(("yaml", "yml")): + cdata = yaml.safe_load(ardata, **load_kw_args) + + parser.read_config(f=cdata) + + return parser diff --git a/source_code/SegMamba/monai/bundle/workflows.py b/source_code/SegMamba/monai/bundle/workflows.py new file mode 100644 index 0000000000000000000000000000000000000000..471088994b4ea42f140d531672220a3f144b98c6 --- /dev/null +++ b/source_code/SegMamba/monai/bundle/workflows.py @@ -0,0 +1,524 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import json +import os +import sys +import time +from abc import ABC, abstractmethod +from copy import copy +from logging.config import fileConfig +from pathlib import Path +from typing import Any, Sequence + +from monai.apps.utils import get_logger +from monai.bundle.config_parser import ConfigParser +from monai.bundle.properties import InferProperties, MetaProperties, TrainProperties +from monai.bundle.utils import DEFAULT_EXP_MGMT_SETTINGS, EXPR_KEY, ID_REF_KEY, ID_SEP_KEY +from monai.config import PathLike +from monai.utils import BundleProperty, BundlePropertyConfig, deprecated_arg, deprecated_arg_default, ensure_tuple + +__all__ = ["BundleWorkflow", "ConfigWorkflow"] + +logger = get_logger(module_name=__name__) + + +class BundleWorkflow(ABC): + """ + Base class for the workflow specification in bundle, it can be a training, evaluation or inference workflow. + It defines the basic interfaces for the bundle workflow behavior: `initialize`, `run`, `finalize`, etc. + And also provides the interface to get / set public properties to interact with a bundle workflow. + + Args: + workflow_type: specifies the workflow type: "train" or "training" for a training workflow, + or "infer", "inference", "eval", "evaluation" for a inference workflow, + other unsupported string will raise a ValueError. + default to `None` for common workflow. + workflow: specifies the workflow type: "train" or "training" for a training workflow, + or "infer", "inference", "eval", "evaluation" for a inference workflow, + other unsupported string will raise a ValueError. + default to `None` for common workflow. + properties_path: the path to the JSON file of properties. + meta_file: filepath of the metadata file, if this is a list of file paths, their contents will be merged in order. + logging_file: config file for `logging` module in the program. for more details: + https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig. + + """ + + supported_train_type: tuple = ("train", "training") + supported_infer_type: tuple = ("infer", "inference", "eval", "evaluation") + + @deprecated_arg( + "workflow", + since="1.2", + removed="1.5", + new_name="workflow_type", + msg_suffix="please use `workflow_type` instead.", + ) + def __init__( + self, + workflow_type: str | None = None, + workflow: str | None = None, + properties_path: PathLike | None = None, + meta_file: str | Sequence[str] | None = None, + logging_file: str | None = None, + ): + if logging_file is not None: + if not os.path.isfile(logging_file): + raise FileNotFoundError(f"Cannot find the logging config file: {logging_file}.") + logger.info(f"Setting logging properties based on config: {logging_file}.") + fileConfig(logging_file, disable_existing_loggers=False) + + if meta_file is not None: + if isinstance(meta_file, str) and not os.path.isfile(meta_file): + logger.error( + f"Cannot find the metadata config file: {meta_file}. " + "Please see: https://docs.monai.io/en/stable/mb_specification.html" + ) + meta_file = None + if isinstance(meta_file, list): + for f in meta_file: + if not os.path.isfile(f): + logger.error( + f"Cannot find the metadata config file: {f}. " + "Please see: https://docs.monai.io/en/stable/mb_specification.html" + ) + meta_file = None + + workflow_type = workflow if workflow is not None else workflow_type + if workflow_type is None and properties_path is None: + self.properties = copy(MetaProperties) + self.workflow_type = None + self.meta_file = meta_file + return + if properties_path is not None: + properties_path = Path(properties_path) + if not properties_path.is_file(): + raise ValueError(f"Property file {properties_path} does not exist.") + with open(properties_path) as json_file: + self.properties = json.load(json_file) + self.workflow_type = None + self.meta_file = meta_file + return + if workflow_type.lower() in self.supported_train_type: # type: ignore[union-attr] + self.properties = {**TrainProperties, **MetaProperties} + self.workflow_type = "train" + elif workflow_type.lower() in self.supported_infer_type: # type: ignore[union-attr] + self.properties = {**InferProperties, **MetaProperties} + self.workflow_type = "infer" + else: + raise ValueError(f"Unsupported workflow type: '{workflow_type}'.") + + self.meta_file = meta_file + + @abstractmethod + def initialize(self, *args: Any, **kwargs: Any) -> Any: + """ + Initialize the bundle workflow before running. + + """ + raise NotImplementedError() + + @abstractmethod + def run(self, *args: Any, **kwargs: Any) -> Any: + """ + Run the bundle workflow, it can be a training, evaluation or inference. + + """ + raise NotImplementedError() + + @abstractmethod + def finalize(self, *args: Any, **kwargs: Any) -> Any: + """ + Finalize step after the running of bundle workflow. + + """ + raise NotImplementedError() + + @abstractmethod + def _get_property(self, name: str, property: dict) -> Any: + """ + With specified property name and information, get the expected property value. + + Args: + name: the name of target property. + property: other information for the target property, defined in `TrainProperties` or `InferProperties`. + + """ + raise NotImplementedError() + + @abstractmethod + def _set_property(self, name: str, property: dict, value: Any) -> Any: + """ + With specified property name and information, set value for the expected property. + + Args: + name: the name of target property. + property: other information for the target property, defined in `TrainProperties` or `InferProperties`. + value: value to set for the property. + + """ + raise NotImplementedError() + + def __getattr__(self, name): + if self.properties is not None and name in self.properties: + return self._get_property(name=name, property=self.properties[name]) + else: + return self.__getattribute__(name) # getting regular attribute + + def __setattr__(self, name, value): + if name != "properties" and self.properties is not None and name in self.properties: + self._set_property(name=name, property=self.properties[name], value=value) + else: + super().__setattr__(name, value) # setting regular attribute + + def get_workflow_type(self): + """ + Get the workflow type, it can be `None`, "train", or "infer". + + """ + return self.workflow_type + + def get_meta_file(self): + """ + Get the meta file. + + """ + return self.meta_file + + def add_property(self, name: str, required: str, desc: str | None = None) -> None: + """ + Besides the default predefined properties, some 3rd party applications may need the bundle + definition to provide additional properties for the specific use cases, if the bundle can't + provide the property, means it can't work with the application. + This utility adds the property for the application requirements check and access. + + Args: + name: the name of target property. + required: whether the property is "must-have". + desc: descriptions for the property. + """ + if self.properties is None: + self.properties = {} + if name in self.properties: + logger.warn(f"property '{name}' already exists in the properties list, overriding it.") + self.properties[name] = {BundleProperty.DESC: desc, BundleProperty.REQUIRED: required} + + def check_properties(self) -> list[str] | None: + """ + Check whether the required properties are existing in the bundle workflow. + If no workflow type specified, return None, otherwise, return a list of required but missing properties. + + """ + if self.properties is None: + return None + return [n for n, p in self.properties.items() if p.get(BundleProperty.REQUIRED, False) and not hasattr(self, n)] + + +class ConfigWorkflow(BundleWorkflow): + """ + Specification for the config-based bundle workflow. + Standardized the `initialize`, `run`, `finalize` behavior in a config-based training, evaluation, or inference. + Before `run`, we add bundle root directory to Python search directories automatically. + For more information: https://docs.monai.io/en/latest/mb_specification.html. + + Args: + config_file: filepath of the config file, if this is a list of file paths, their contents will be merged in order. + meta_file: filepath of the metadata file, if this is a list of file paths, their contents will be merged in order. + If None, default to "configs/metadata.json", which is commonly used for bundles in MONAI model zoo. + logging_file: config file for `logging` module in the program. for more details: + https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig. + If None, default to "configs/logging.conf", which is commonly used for bundles in MONAI model zoo. + init_id: ID name of the expected config expression to initialize before running, default to "initialize". + allow a config to have no `initialize` logic and the ID. + run_id: ID name of the expected config expression to run, default to "run". + to run the config, the target config must contain this ID. + final_id: ID name of the expected config expression to finalize after running, default to "finalize". + allow a config to have no `finalize` logic and the ID. + tracking: if not None, enable the experiment tracking at runtime with optionally configurable and extensible. + if "mlflow", will add `MLFlowHandler` to the parsed bundle with default tracking settings, + if other string, treat it as file path to load the tracking settings. + if `dict`, treat it as tracking settings. + will patch the target config content with `tracking handlers` and the top-level items of `configs`. + for detailed usage examples, please check the tutorial: + https://github.com/Project-MONAI/tutorials/blob/main/experiment_management/bundle_integrate_mlflow.ipynb. + workflow_type: specifies the workflow type: "train" or "training" for a training workflow, + or "infer", "inference", "eval", "evaluation" for a inference workflow, + other unsupported string will raise a ValueError. + default to `None` for common workflow. + workflow: specifies the workflow type: "train" or "training" for a training workflow, + or "infer", "inference", "eval", "evaluation" for a inference workflow, + other unsupported string will raise a ValueError. + default to `None` for common workflow. + properties_path: the path to the JSON file of properties. + override: id-value pairs to override or add the corresponding config content. + e.g. ``--net#input_chns 42``, ``--net %/data/other.json#net_arg`` + + """ + + @deprecated_arg( + "workflow", + since="1.2", + removed="1.5", + new_name="workflow_type", + msg_suffix="please use `workflow_type` instead.", + ) + @deprecated_arg_default("workflow_type", None, "train", since="1.2", replaced="1.4") + def __init__( + self, + config_file: str | Sequence[str], + meta_file: str | Sequence[str] | None = None, + logging_file: str | None = None, + init_id: str = "initialize", + run_id: str = "run", + final_id: str = "finalize", + tracking: str | dict | None = None, + workflow_type: str | None = None, + workflow: str | None = None, + properties_path: PathLike | None = None, + **override: Any, + ) -> None: + workflow_type = workflow if workflow is not None else workflow_type + if config_file is not None: + _config_files = ensure_tuple(config_file) + config_root_path = Path(_config_files[0]).parent + for _config_file in _config_files: + _config_file = Path(_config_file) + if _config_file.parent != config_root_path: + logger.warn( + f"Not all config files are in {config_root_path}. If logging_file and meta_file are" + f"not specified, {config_root_path} will be used as the default config root directory." + ) + if not _config_file.is_file(): + raise FileNotFoundError(f"Cannot find the config file: {_config_file}.") + else: + config_root_path = Path("configs") + meta_file = str(config_root_path / "metadata.json") if meta_file is None else meta_file + super().__init__(workflow_type=workflow_type, meta_file=meta_file, properties_path=properties_path) + self.config_root_path = config_root_path + logging_file = str(self.config_root_path / "logging.conf") if logging_file is None else logging_file + if logging_file is not None: + if not os.path.isfile(logging_file): + if logging_file == str(self.config_root_path / "logging.conf"): + logger.warn(f"Default logging file in {logging_file} does not exist, skipping logging.") + else: + raise FileNotFoundError(f"Cannot find the logging config file: {logging_file}.") + else: + logger.info(f"Setting logging properties based on config: {logging_file}.") + fileConfig(logging_file, disable_existing_loggers=False) + + self.parser = ConfigParser() + self.parser.read_config(f=config_file) + if self.meta_file is not None: + self.parser.read_meta(f=self.meta_file) + + # the rest key-values in the _args are to override config content + self.parser.update(pairs=override) + self.init_id = init_id + self.run_id = run_id + self.final_id = final_id + # set tracking configs for experiment management + if tracking is not None: + if isinstance(tracking, str) and tracking in DEFAULT_EXP_MGMT_SETTINGS: + settings_ = DEFAULT_EXP_MGMT_SETTINGS[tracking] + else: + settings_ = ConfigParser.load_config_files(tracking) + self.patch_bundle_tracking(parser=self.parser, settings=settings_) + self._is_initialized: bool = False + + def initialize(self) -> Any: + """ + Initialize the bundle workflow before running. + + """ + # reset the "reference_resolver" buffer at initialization stage + self.parser.parse(reset=True) + self._is_initialized = True + return self._run_expr(id=self.init_id) + + def run(self) -> Any: + """ + Run the bundle workflow, it can be a training, evaluation or inference. + Before run, we add bundle root directory to Python search directories automatically. + + """ + _bundle_root_path = ( + self.config_root_path.parent if self.config_root_path.name == "configs" else self.config_root_path + ) + sys.path.insert(1, str(_bundle_root_path)) + if self.run_id not in self.parser: + raise ValueError(f"run ID '{self.run_id}' doesn't exist in the config file.") + return self._run_expr(id=self.run_id) + + def finalize(self) -> Any: + """ + Finalize step after the running of bundle workflow. + + """ + return self._run_expr(id=self.final_id) + + def check_properties(self) -> list[str] | None: + """ + Check whether the required properties are existing in the bundle workflow. + If the optional properties have reference in the config, will also check whether the properties are existing. + If no workflow type specified, return None, otherwise, return a list of required but missing properties. + + """ + ret = super().check_properties() + if self.properties is None: + logger.warn("No available properties had been set, skipping check.") + return None + if ret: + logger.warn(f"Loaded bundle does not contain the following required properties: {ret}") + # also check whether the optional properties use correct ID name if existing + wrong_props = [] + for n, p in self.properties.items(): + if not p.get(BundleProperty.REQUIRED, False) and not self._check_optional_id(name=n, property=p): + wrong_props.append(n) + if wrong_props: + logger.warn(f"Loaded bundle defines the following optional properties with wrong ID: {wrong_props}") + if ret is not None: + ret.extend(wrong_props) + return ret + + def _run_expr(self, id: str, **kwargs: dict) -> Any: + return self.parser.get_parsed_content(id, **kwargs) if id in self.parser else None + + def _get_prop_id(self, name: str, property: dict) -> Any: + prop_id = property[BundlePropertyConfig.ID] + if prop_id not in self.parser: + if not property.get(BundleProperty.REQUIRED, False): + return None + else: + raise KeyError(f"Property '{name}' with config ID '{prop_id}' not in the config.") + return prop_id + + def _get_property(self, name: str, property: dict) -> Any: + """ + With specified property name and information, get the parsed property value from config. + + Args: + name: the name of target property. + property: other information for the target property, defined in `TrainProperties` or `InferProperties`. + + """ + if not self._is_initialized: + raise RuntimeError("Please execute 'initialize' before getting any parsed content.") + prop_id = self._get_prop_id(name, property) + return self.parser.get_parsed_content(id=prop_id) if prop_id is not None else None + + def _set_property(self, name: str, property: dict, value: Any) -> None: + """ + With specified property name and information, set value for the expected property. + + Args: + name: the name of target property. + property: other information for the target property, defined in `TrainProperties` or `InferProperties`. + value: value to set for the property. + + """ + prop_id = self._get_prop_id(name, property) + if prop_id is not None: + self.parser[prop_id] = value + # must parse the config again after changing the content + self._is_initialized = False + self.parser.ref_resolver.reset() + + def add_property( # type: ignore[override] + self, name: str, required: str, config_id: str, desc: str | None = None + ) -> None: + """ + Besides the default predefined properties, some 3rd party applications may need the bundle + definition to provide additional properties for the specific use cases, if the bundle can't + provide the property, means it can't work with the application. + This utility adds the property for the application requirements check and access. + + Args: + name: the name of target property. + required: whether the property is "must-have". + config_id: the config ID of target property in the bundle definition. + desc: descriptions for the property. + + """ + super().add_property(name=name, required=required, desc=desc) + self.properties[name][BundlePropertyConfig.ID] = config_id + + def _check_optional_id(self, name: str, property: dict) -> bool: + """ + If an optional property has reference in the config, check whether the property is existing. + If `ValidationHandler` is defined for a training workflow, will check whether the optional properties + "evaluator" and "val_interval" are existing. + + Args: + name: the name of target property. + property: other information for the target property, defined in `TrainProperties` or `InferProperties`. + + """ + id = property.get(BundlePropertyConfig.ID, None) + ref_id = property.get(BundlePropertyConfig.REF_ID, None) + if ref_id is None: + # no ID of reference config item, skipping check for this optional property + return True + # check validation `validator` and `interval` properties as the handler index of ValidationHandler is unknown + ref: str | None = None + if name in ("evaluator", "val_interval"): + if f"train{ID_SEP_KEY}handlers" in self.parser: + for h in self.parser[f"train{ID_SEP_KEY}handlers"]: + if h["_target_"] == "ValidationHandler": + ref = h.get(ref_id, None) + else: + ref = self.parser.get(ref_id, None) + # for reference IDs that not refer to a property directly but using expressions, skip the check + if ref is not None and not ref.startswith(EXPR_KEY) and ref != ID_REF_KEY + id: + return False + return True + + @staticmethod + def patch_bundle_tracking(parser: ConfigParser, settings: dict) -> None: + """ + Patch the loaded bundle config with a new handler logic to enable experiment tracking features. + + Args: + parser: loaded config content to patch the handler. + settings: settings for the experiment tracking, should follow the pattern of default settings. + + """ + for k, v in settings["configs"].items(): + if k in settings["handlers_id"]: + engine = parser.get(settings["handlers_id"][k]["id"]) + if engine is not None: + handlers = parser.get(settings["handlers_id"][k]["handlers"]) + if handlers is None: + engine["train_handlers" if k == "trainer" else "val_handlers"] = [v] + else: + handlers.append(v) + elif k not in parser: + parser[k] = v + # save the executed config into file + default_name = f"config_{time.strftime('%Y%m%d_%H%M%S')}.json" + # Users can set the `save_execute_config` to `False`, `/path/to/artifacts` or `True`. + # If set to False, nothing will be recorded. If set to True, the default path will be logged. + # If set to a file path, the given path will be logged. + filepath = parser.get("save_execute_config", True) + if filepath: + if isinstance(filepath, bool): + if "output_dir" not in parser: + # if no "output_dir" in the bundle config, default to "/eval" + parser["output_dir"] = f"{EXPR_KEY}{ID_REF_KEY}bundle_root + '/eval'" + # experiment management tools can refer to this config item to track the config info + parser["save_execute_config"] = parser["output_dir"] + f" + '/{default_name}'" + filepath = os.path.join(parser.get_parsed_content("output_dir"), default_name) + Path(filepath).parent.mkdir(parents=True, exist_ok=True) + parser.export_config_file(parser.get(), filepath) + else: + parser["save_execute_config"] = None diff --git a/source_code/SegMamba/monai/config/__init__.py b/source_code/SegMamba/monai/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c814e1f8ebc9206f27b0f0454ab968b8074a625b --- /dev/null +++ b/source_code/SegMamba/monai/config/__init__.py @@ -0,0 +1,36 @@ +# 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 .deviceconfig import ( + USE_COMPILED, + USE_META_DICT, + IgniteInfo, + get_config_values, + get_gpu_info, + get_optional_config_values, + get_system_info, + print_config, + print_debug_info, + print_gpu_info, + print_system_info, +) +from .type_definitions import ( + DtypeLike, + IndexSelection, + KeysCollection, + NdarrayOrTensor, + NdarrayTensor, + PathLike, + SequenceStr, + TensorOrList, +) diff --git a/source_code/SegMamba/monai/config/deviceconfig.py b/source_code/SegMamba/monai/config/deviceconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..a4580c741bc36a1f35cff048e18c5159ddc8fe92 --- /dev/null +++ b/source_code/SegMamba/monai/config/deviceconfig.py @@ -0,0 +1,274 @@ +# 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 getpass +import os +import platform +import re +import sys +from collections import OrderedDict +from typing import TextIO + +import numpy as np +import torch + +import monai +from monai.utils.module import OptionalImportError, get_package_version, optional_import + +try: + _, HAS_EXT = optional_import("monai._C") + USE_COMPILED = HAS_EXT and os.getenv("BUILD_MONAI", "0") == "1" +except (OptionalImportError, ImportError, AttributeError): + HAS_EXT = USE_COMPILED = False + +USE_META_DICT = os.environ.get("USE_META_DICT", "0") == "1" # set to True for compatibility, use meta dict. + +psutil, has_psutil = optional_import("psutil") +psutil_version = psutil.__version__ if has_psutil else "NOT INSTALLED or UNKNOWN VERSION." + +__all__ = [ + "print_config", + "get_system_info", + "print_system_info", + "get_gpu_info", + "print_gpu_info", + "print_debug_info", + "USE_COMPILED", + "USE_META_DICT", + "IgniteInfo", +] + + +def get_config_values(): + """ + Read the package versions into a dictionary. + """ + output = OrderedDict() + + output["MONAI"] = monai.__version__ + output["Numpy"] = np.version.full_version + output["Pytorch"] = torch.__version__ + + return output + + +def get_optional_config_values(): + """ + Read the optional package versions into a dictionary. + """ + output = OrderedDict() + + output["Pytorch Ignite"] = get_package_version("ignite") + output["ITK"] = get_package_version("itk") + output["Nibabel"] = get_package_version("nibabel") + output["scikit-image"] = get_package_version("skimage") + output["scipy"] = get_package_version("scipy") + output["Pillow"] = get_package_version("PIL") + output["Tensorboard"] = get_package_version("tensorboard") + output["gdown"] = get_package_version("gdown") + output["TorchVision"] = get_package_version("torchvision") + output["tqdm"] = get_package_version("tqdm") + output["lmdb"] = get_package_version("lmdb") + output["psutil"] = psutil_version + output["pandas"] = get_package_version("pandas") + output["einops"] = get_package_version("einops") + output["transformers"] = get_package_version("transformers") + output["mlflow"] = get_package_version("mlflow") + output["pynrrd"] = get_package_version("nrrd") + output["clearml"] = get_package_version("clearml") + + return output + + +def print_config(file=sys.stdout): + """ + Print the package versions to `file`. + + Args: + file: `print()` text stream file. Defaults to `sys.stdout`. + """ + for k, v in get_config_values().items(): + print(f"{k} version: {v}", file=file, flush=True) + print(f"MONAI flags: HAS_EXT = {HAS_EXT}, USE_COMPILED = {USE_COMPILED}, USE_META_DICT = {USE_META_DICT}") + print(f"MONAI rev id: {monai.__revision_id__}") + username = getpass.getuser() + masked_file_path = re.sub(username, "", monai.__file__) + print(f"MONAI __file__: {masked_file_path}", file=file, flush=True) + print("\nOptional dependencies:", file=file, flush=True) + for k, v in get_optional_config_values().items(): + print(f"{k} version: {v}", file=file, flush=True) + print("\nFor details about installing the optional dependencies, please visit:", file=file, flush=True) + print( + " https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n", + file=file, + flush=True, + ) + + +def _dict_append(in_dict, key, fn): + try: + in_dict[key] = fn() if callable(fn) else fn + except BaseException: + in_dict[key] = "UNKNOWN for given OS" + + +def get_system_info() -> OrderedDict: + """ + Get system info as an ordered dictionary. + """ + output: OrderedDict = OrderedDict() + + _dict_append(output, "System", platform.system) + if output["System"] == "Windows": + _dict_append(output, "Win32 version", platform.win32_ver) + if hasattr(platform, "win32_edition"): + _dict_append(output, "Win32 edition", platform.win32_edition) + + elif output["System"] == "Darwin": + _dict_append(output, "Mac version", lambda: platform.mac_ver()[0]) + else: + with open("/etc/os-release") as rel_f: + linux_ver = re.search(r'PRETTY_NAME="(.*)"', rel_f.read()) + if linux_ver: + _dict_append(output, "Linux version", lambda: linux_ver.group(1)) + + _dict_append(output, "Platform", platform.platform) + _dict_append(output, "Processor", platform.processor) + _dict_append(output, "Machine", platform.machine) + _dict_append(output, "Python version", platform.python_version) + + if not has_psutil: + _dict_append(output, "`psutil` missing", lambda: "run `pip install monai[psutil]`") + else: + p = psutil.Process() + with p.oneshot(): + _dict_append(output, "Process name", p.name) + _dict_append(output, "Command", p.cmdline) + _dict_append(output, "Open files", p.open_files) + _dict_append(output, "Num physical CPUs", lambda: psutil.cpu_count(logical=False)) + _dict_append(output, "Num logical CPUs", lambda: psutil.cpu_count(logical=True)) + _dict_append(output, "Num usable CPUs", lambda: len(psutil.Process().cpu_affinity())) + _dict_append(output, "CPU usage (%)", lambda: psutil.cpu_percent(percpu=True)) + _dict_append(output, "CPU freq. (MHz)", lambda: round(psutil.cpu_freq(percpu=False)[0])) + _dict_append( + output, + "Load avg. in last 1, 5, 15 mins (%)", + lambda: [round(x / psutil.cpu_count() * 100, 1) for x in psutil.getloadavg()], + ) + _dict_append(output, "Disk usage (%)", lambda: psutil.disk_usage(os.getcwd()).percent) + _dict_append( + output, + "Avg. sensor temp. (Celsius)", + lambda: np.round( + np.mean([item.current for sublist in psutil.sensors_temperatures().values() for item in sublist], 1) + ), + ) + mem = psutil.virtual_memory() + _dict_append(output, "Total physical memory (GB)", lambda: round(mem.total / 1024**3, 1)) + _dict_append(output, "Available memory (GB)", lambda: round(mem.available / 1024**3, 1)) + _dict_append(output, "Used memory (GB)", lambda: round(mem.used / 1024**3, 1)) + + return output + + +def print_system_info(file: TextIO = sys.stdout) -> None: + """ + Print system info to `file`. Requires the optional library, `psutil`. + + Args: + file: `print()` text stream file. Defaults to `sys.stdout`. + """ + if not has_psutil: + print("`psutil` required for `print_system_info`", file=file, flush=True) + else: + for k, v in get_system_info().items(): + print(f"{k}: {v}", file=file, flush=True) + + +def get_gpu_info() -> OrderedDict: + output: OrderedDict = OrderedDict() + + num_gpus = torch.cuda.device_count() + _dict_append(output, "Num GPUs", lambda: num_gpus) + + _dict_append(output, "Has CUDA", lambda: bool(torch.cuda.is_available())) + + if output["Has CUDA"]: + _dict_append(output, "CUDA version", lambda: torch.version.cuda) + cudnn_ver = torch.backends.cudnn.version() + _dict_append(output, "cuDNN enabled", lambda: bool(cudnn_ver)) + _dict_append(output, "NVIDIA_TF32_OVERRIDE", os.environ.get("NVIDIA_TF32_OVERRIDE")) + _dict_append(output, "TORCH_ALLOW_TF32_CUBLAS_OVERRIDE", os.environ.get("TORCH_ALLOW_TF32_CUBLAS_OVERRIDE")) + + if cudnn_ver: + _dict_append(output, "cuDNN version", lambda: cudnn_ver) + + if num_gpus > 0: + _dict_append(output, "Current device", torch.cuda.current_device) + _dict_append(output, "Library compiled for CUDA architectures", torch.cuda.get_arch_list) + + for gpu in range(num_gpus): + gpu_info = torch.cuda.get_device_properties(gpu) + _dict_append(output, f"GPU {gpu} Name", gpu_info.name) + _dict_append(output, f"GPU {gpu} Is integrated", bool(gpu_info.is_integrated)) + _dict_append(output, f"GPU {gpu} Is multi GPU board", bool(gpu_info.is_multi_gpu_board)) + _dict_append(output, f"GPU {gpu} Multi processor count", gpu_info.multi_processor_count) + _dict_append(output, f"GPU {gpu} Total memory (GB)", round(gpu_info.total_memory / 1024**3, 1)) + _dict_append(output, f"GPU {gpu} CUDA capability (maj.min)", f"{gpu_info.major}.{gpu_info.minor}") + + return output + + +def print_gpu_info(file: TextIO = sys.stdout) -> None: + """ + Print GPU info to `file`. + + Args: + file: `print()` text stream file. Defaults to `sys.stdout`. + """ + for k, v in get_gpu_info().items(): + print(f"{k}: {v}", file=file, flush=True) + + +def print_debug_info(file: TextIO = sys.stdout) -> None: + """ + Print config (installed dependencies, etc.) and system info for debugging. + + Args: + file: `print()` text stream file. Defaults to `sys.stdout`. + """ + print("================================", file=file, flush=True) + print("Printing MONAI config...", file=file, flush=True) + print("================================", file=file, flush=True) + print_config(file) + print("\n================================", file=file, flush=True) + print("Printing system config...") + print("================================", file=file, flush=True) + print_system_info(file) + print("\n================================", file=file, flush=True) + print("Printing GPU config...") + print("================================", file=file, flush=True) + print_gpu_info(file) + + +class IgniteInfo: + """ + Config information of the PyTorch ignite package. + + """ + + OPT_IMPORT_VERSION = "0.4.4" + + +if __name__ == "__main__": + print_debug_info() diff --git a/source_code/SegMamba/monai/config/type_definitions.py b/source_code/SegMamba/monai/config/type_definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..57454a94e1e69f2daf74a74a510411ba737c8eb8 --- /dev/null +++ b/source_code/SegMamba/monai/config/type_definitions.py @@ -0,0 +1,85 @@ +# 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 typing import Collection, Hashable, Iterable, Sequence, TypeVar, Union + +import numpy as np +import torch + +# Commonly used concepts +# This module provides naming and type specifications for commonly used concepts +# within the MONAI package. The intent is to explicitly identify information +# that should be used consistently throughout the entire MONAI package. +# +# A type would be named as type_definitions.KeysCollection +# which includes a meaningful name for the consent in the name itself. The +# definitions in this file map context meaningful names to the underlying +# object properties that define the expected API. +# +# A conceptual type is represented by a new type name but is also one which +# can be different depending on an environment (i.e. differences for python 3.6 vs 3.9 +# may be implemented). Consistent use of the concept and recorded documentation of +# the rationale and convention behind it lowers the learning curve for new +# developers. For readability, short names are preferred. +__all__ = [ + "KeysCollection", + "IndexSelection", + "DtypeLike", + "NdarrayTensor", + "NdarrayOrTensor", + "TensorOrList", + "PathLike", + "SequenceStr", +] + +#: KeysCollection +# +# The KeyCollection type is used to for defining variables +# that store a subset of keys to select items from a dictionary. +# The container of keys must contain hashable elements. +# NOTE: `Hashable` is not a collection, but is provided as a +# convenience to end-users. All supplied values will be +# internally converted to a tuple of `Hashable`'s before +# use +KeysCollection = Union[Collection[Hashable], Hashable] + +#: IndexSelection +# +# The IndexSelection type is used to for defining variables +# that store a subset of indices to select items from a List or Array like objects. +# The indices must be integers, and if a container of indices is specified, the +# container must be iterable. +IndexSelection = Union[Iterable[int], int] + +#: Type of datatypes: Adapted from https://github.com/numpy/numpy/blob/v1.21.4/numpy/typing/_dtype_like.py#L121 +DtypeLike = Union[np.dtype, type, str, None] + +#: NdarrayOrTensor: Union of numpy.ndarray and torch.Tensor to be used for typing +NdarrayOrTensor = Union[np.ndarray, torch.Tensor] + +#: NdarrayTensor +# +# Generic type which can represent either a numpy.ndarray or a torch.Tensor +# Unlike Union can create a dependence between parameter(s) / return(s) +NdarrayTensor = TypeVar("NdarrayTensor", bound=NdarrayOrTensor) + +#: TensorOrList: The TensorOrList type is used for defining `batch-first Tensor` or `list of channel-first Tensor`. +TensorOrList = Union[torch.Tensor, Sequence[torch.Tensor]] + +#: PathLike: The PathLike type is used for defining a file path. +PathLike = Union[str, os.PathLike] + +#: SequenceStr +# string or a sequence of strings for `mode` types. +SequenceStr = Union[Sequence[str], str] diff --git a/source_code/SegMamba/monai/csrc/ext.cpp b/source_code/SegMamba/monai/csrc/ext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b56a7454c75e381164a6cad2c813f632a3a39997 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/ext.cpp @@ -0,0 +1,75 @@ +/* +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 "filtering/filtering.h" +#include "lltm/lltm.h" +#include "resample/pushpull.h" +#include "utils/resample_utils.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + // filtering + m.def("bilateral_filter", &BilateralFilter, "Bilateral Filter"); + m.def("phl_filter", &PermutohedralFilter, "Permutohedral Filter"); + m.def("tbf_forward", &TrainableBilateralFilterForward, "Trainable Bilateral Filter Forward"); + m.def("tbf_backward", &TrainableBilateralFilterBackward, "Trainable Bilateral Filter Backward"); + m.def("tjbf_forward", &TrainableJointBilateralFilterForward, "Trainable Joint Bilateral Filter Forward"); + m.def("tjbf_backward", &TrainableJointBilateralFilterBackward, "Trainable Joint Bilateral Filter Backward"); + + // lltm + m.def("lltm_forward", &lltm_forward, "LLTM forward"); + m.def("lltm_backward", &lltm_backward, "LLTM backward"); + + // resample bound mode + py::enum_(m, "BoundType") + .value("replicate", monai::BoundType::Replicate, "a a a | a b c d | d d d") + .value("nearest", monai::BoundType::Replicate, "a a a | a b c d | d d d") + .value("border", monai::BoundType::Replicate, "a a a | a b c d | d d d") + .value("dct1", monai::BoundType::DCT1, "d c b | a b c d | c b a") + .value("mirror", monai::BoundType::DCT1, "d c b | a b c d | c b a") + .value("dct2", monai::BoundType::DCT2, "c b a | a b c d | d c b") + .value("reflect", monai::BoundType::DCT2, "c b a | a b c d | d c b") + .value("dst1", monai::BoundType::DST1, "-b -a 0 | a b c d | 0 -d -c") + .value("antimirror", monai::BoundType::DST1, "-b -a 0 | a b c d | 0 -d -c") + .value("dst2", monai::BoundType::DST2, "-c -b -a | a b c d | -d -c -b") + .value("antireflect", monai::BoundType::DST2, "-c -b -a | a b c d | -d -c -b") + .value("dft", monai::BoundType::DFT, "b c d | a b c d | a b c") + .value("wrap", monai::BoundType::DFT, "b c d | a b c d | a b c") + // .value("sliding", monai::BoundType::Sliding) + .value("zero", monai::BoundType::Zero, "0 0 0 | a b c d | 0 0 0") + .value("zeros", monai::BoundType::Zero, "0 0 0 | a b c d | 0 0 0") + .export_values(); + + // resample interpolation mode + py::enum_(m, "InterpolationType") + .value("nearest", monai::InterpolationType::Nearest) + .value("linear", monai::InterpolationType::Linear) + .value("quadratic", monai::InterpolationType::Quadratic) + .value("cubic", monai::InterpolationType::Cubic) + .value("fourth", monai::InterpolationType::FourthOrder) + .value("fifth", monai::InterpolationType::FifthOrder) + .value("sixth", monai::InterpolationType::SixthOrder) + .value("seventh", monai::InterpolationType::SeventhOrder) + .export_values(); + + // resample + m.def("grid_pull", &monai::grid_pull, "GridPull"); + m.def("grid_pull_backward", &monai::grid_pull_backward, "GridPull backward"); + m.def("grid_push", &monai::grid_push, "GridPush"); + m.def("grid_push_backward", &monai::grid_push_backward, "GridPush backward"); + m.def("grid_count", &monai::grid_count, "GridCount"); + m.def("grid_count_backward", &monai::grid_count_backward, "GridCount backward"); + m.def("grid_grad", &monai::grid_grad, "GridGrad"); + m.def("grid_grad_backward", &monai::grid_grad_backward, "GridGrad backward"); +} diff --git a/source_code/SegMamba/monai/engines/__init__.py b/source_code/SegMamba/monai/engines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8dc51f620a535d0fe0bb486c99cb80a1f544ccd --- /dev/null +++ b/source_code/SegMamba/monai/engines/__init__.py @@ -0,0 +1,27 @@ +# 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 .evaluator import EnsembleEvaluator, Evaluator, SupervisedEvaluator +from .trainer import GanTrainer, SupervisedTrainer, Trainer +from .utils import ( + IterationEvents, + PrepareBatch, + PrepareBatchDefault, + PrepareBatchExtraInput, + default_make_latent, + default_metric_cmp_fn, + default_prepare_batch, + engine_apply_transform, + get_devices_spec, +) +from .workflow import Workflow diff --git a/source_code/SegMamba/monai/engines/evaluator.py b/source_code/SegMamba/monai/engines/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..2c8dfe6b85a4a6c7e8e2fbf028d3dfd1dc88bb4a --- /dev/null +++ b/source_code/SegMamba/monai/engines/evaluator.py @@ -0,0 +1,507 @@ +# 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 typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence + +import torch +from torch.utils.data import DataLoader + +from monai.config import IgniteInfo, KeysCollection +from monai.data import MetaTensor +from monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batch +from monai.engines.workflow import Workflow +from monai.inferers import Inferer, SimpleInferer +from monai.networks.utils import eval_mode, train_mode +from monai.transforms import Transform +from monai.utils import ForwardMode, ensure_tuple, min_version, optional_import +from monai.utils.enums import CommonKeys as Keys +from monai.utils.enums import EngineStatsKeys as ESKeys +from monai.utils.module import look_up_option, pytorch_after + +if TYPE_CHECKING: + from ignite.engine import Engine, EventEnum + from ignite.metrics import Metric +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric") + EventEnum, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum") + +__all__ = ["Evaluator", "SupervisedEvaluator", "EnsembleEvaluator"] + + +class Evaluator(Workflow): + """ + Base class for all kinds of evaluators, inherits from Workflow. + + Args: + device: an object representing the device on which to run. + val_data_loader: Ignite engine use data_loader to run, must be Iterable or torch.DataLoader. + epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`. + non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously + with respect to the host. For other cases, this argument has no effect. + prepare_batch: function to parse expected data (usually `image`, `label` and other network args) + from `engine.state.batch` for every iteration, for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. + iteration_update: the callable function for every iteration, expect to accept `engine` + and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. + if not provided, use `self._iteration()` instead. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. + postprocessing: execute additional transformation for the model output data. + Typically, several Tensor based transforms composed by `Compose`. + key_val_metric: compute metric when every iteration completed, and save average value to + engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the + checkpoint into files. + additional_metrics: more Ignite metrics that also attach to Ignite Engine. + metric_cmp_fn: function to compare current key metric with previous best key metric value, + it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update + `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. + val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: + CheckpointHandler, StatsHandler, etc. + amp: whether to enable auto-mixed-precision evaluation, default is False. + mode: model forward mode during evaluation, should be 'eval' or 'train', + which maps to `model.eval()` or `model.train()`, default to 'eval'. + event_names: additional custom ignite events that will register to the engine. + new events can be a list of str or `ignite.engine.events.EventEnum`. + event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`. + for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html + #ignite.engine.engine.Engine.register_events. + decollate: whether to decollate the batch-first data to a list of data after model computation, + recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. + default to `True`. + to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for + `device`, `non_blocking`. + amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: + https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. + + """ + + def __init__( + self, + device: torch.device | str, + val_data_loader: Iterable | DataLoader, + epoch_length: int | None = None, + non_blocking: bool = False, + prepare_batch: Callable = default_prepare_batch, + iteration_update: Callable[[Engine, Any], Any] | None = None, + postprocessing: Transform | None = None, + key_val_metric: dict[str, Metric] | None = None, + additional_metrics: dict[str, Metric] | None = None, + metric_cmp_fn: Callable = default_metric_cmp_fn, + val_handlers: Sequence | None = None, + amp: bool = False, + mode: ForwardMode | str = ForwardMode.EVAL, + event_names: list[str | EventEnum | type[EventEnum]] | None = None, + event_to_attr: dict | None = None, + decollate: bool = True, + to_kwargs: dict | None = None, + amp_kwargs: dict | None = None, + ) -> None: + super().__init__( + device=device, + max_epochs=1, + data_loader=val_data_loader, + epoch_length=epoch_length, + non_blocking=non_blocking, + prepare_batch=prepare_batch, + iteration_update=iteration_update, + postprocessing=postprocessing, + key_metric=key_val_metric, + additional_metrics=additional_metrics, + metric_cmp_fn=metric_cmp_fn, + handlers=val_handlers, + amp=amp, + event_names=event_names, + event_to_attr=event_to_attr, + decollate=decollate, + to_kwargs=to_kwargs, + amp_kwargs=amp_kwargs, + ) + mode = look_up_option(mode, ForwardMode) + if mode == ForwardMode.EVAL: + self.mode = eval_mode + elif mode == ForwardMode.TRAIN: + self.mode = train_mode + else: + raise ValueError(f"unsupported mode: {mode}, should be 'eval' or 'train'.") + + def run(self, global_epoch: int = 1) -> None: # type: ignore[override] + """ + Execute validation/evaluation based on Ignite Engine. + + Args: + global_epoch: the overall epoch if during a training. evaluator engine can get it from trainer. + + """ + # init env value for current validation process + self.state.max_epochs = max(global_epoch, 1) # at least one epoch of validation + self.state.epoch = global_epoch - 1 + self.state.iteration = 0 + super().run() + + def get_stats(self, *vars): + """ + Get the statistics information of the validation process. + Default to return the `rank`, `best_validation_epoch` and `best_validation_metric`. + + Args: + vars: except for the default stats, other variables name in the `self.state` to return, + will use the variable name as the key and the state content as the value. + if the variable doesn't exist, default value is `None`. + + """ + stats = { + ESKeys.RANK: self.state.rank, + ESKeys.BEST_VALIDATION_EPOCH: self.state.best_metric_epoch, + ESKeys.BEST_VALIDATION_METRIC: self.state.best_metric, + } + for k in vars: + stats[k] = getattr(self.state, k, None) + return stats + + +class SupervisedEvaluator(Evaluator): + """ + Standard supervised evaluation method with image and label(optional), inherits from evaluator and Workflow. + + Args: + device: an object representing the device on which to run. + val_data_loader: Ignite engine use data_loader to run, must be Iterable, typically be torch.DataLoader. + network: network to evaluate in the evaluator, should be regular PyTorch `torch.nn.Module`. + epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`. + non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously + with respect to the host. For other cases, this argument has no effect. + prepare_batch: function to parse expected data (usually `image`, `label` and other network args) + from `engine.state.batch` for every iteration, for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. + iteration_update: the callable function for every iteration, expect to accept `engine` + and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. + if not provided, use `self._iteration()` instead. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. + inferer: inference method that execute model forward on input data, like: SlidingWindow, etc. + postprocessing: execute additional transformation for the model output data. + Typically, several Tensor based transforms composed by `Compose`. + key_val_metric: compute metric when every iteration completed, and save average value to + engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the + checkpoint into files. + additional_metrics: more Ignite metrics that also attach to Ignite Engine. + metric_cmp_fn: function to compare current key metric with previous best key metric value, + it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update + `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. + val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: + CheckpointHandler, StatsHandler, etc. + amp: whether to enable auto-mixed-precision evaluation, default is False. + mode: model forward mode during evaluation, should be 'eval' or 'train', + which maps to `model.eval()` or `model.train()`, default to 'eval'. + event_names: additional custom ignite events that will register to the engine. + new events can be a list of str or `ignite.engine.events.EventEnum`. + event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`. + for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html + #ignite.engine.engine.Engine.register_events. + decollate: whether to decollate the batch-first data to a list of data after model computation, + recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. + default to `True`. + to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for + `device`, `non_blocking`. + amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: + https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. + compile: whether to use `torch.compile`, default is False. If True, MetaTensor inputs will be converted to + `torch.Tensor` before forward pass, then converted back afterward with copied meta information. + compile_kwargs: dict of the args for `torch.compile()` API, for more details: + https://pytorch.org/docs/stable/generated/torch.compile.html#torch-compile. + + """ + + def __init__( + self, + device: torch.device, + val_data_loader: Iterable | DataLoader, + network: torch.nn.Module, + epoch_length: int | None = None, + non_blocking: bool = False, + prepare_batch: Callable = default_prepare_batch, + iteration_update: Callable[[Engine, Any], Any] | None = None, + inferer: Inferer | None = None, + postprocessing: Transform | None = None, + key_val_metric: dict[str, Metric] | None = None, + additional_metrics: dict[str, Metric] | None = None, + metric_cmp_fn: Callable = default_metric_cmp_fn, + val_handlers: Sequence | None = None, + amp: bool = False, + mode: ForwardMode | str = ForwardMode.EVAL, + event_names: list[str | EventEnum | type[EventEnum]] | None = None, + event_to_attr: dict | None = None, + decollate: bool = True, + to_kwargs: dict | None = None, + amp_kwargs: dict | None = None, + compile: bool = False, + compile_kwargs: dict | None = None, + ) -> None: + super().__init__( + device=device, + val_data_loader=val_data_loader, + epoch_length=epoch_length, + non_blocking=non_blocking, + prepare_batch=prepare_batch, + iteration_update=iteration_update, + postprocessing=postprocessing, + key_val_metric=key_val_metric, + additional_metrics=additional_metrics, + metric_cmp_fn=metric_cmp_fn, + val_handlers=val_handlers, + amp=amp, + mode=mode, + event_names=event_names, + event_to_attr=event_to_attr, + decollate=decollate, + to_kwargs=to_kwargs, + amp_kwargs=amp_kwargs, + ) + if compile: + if pytorch_after(2, 1): + compile_kwargs = {} if compile_kwargs is None else compile_kwargs + network = torch.compile(network, **compile_kwargs) # type: ignore[assignment] + else: + warnings.warn( + "Network compilation (compile=True) not supported for Pytorch versions before 2.1, no compilation done" + ) + self.network = network + self.compile = compile + self.inferer = SimpleInferer() if inferer is None else inferer + + def _iteration(self, engine: SupervisedEvaluator, batchdata: dict[str, torch.Tensor]) -> dict: + """ + callback function for the Supervised Evaluation processing logic of 1 iteration in Ignite Engine. + Return below items in a dictionary: + - IMAGE: image Tensor data for model input, already moved to device. + - LABEL: label Tensor data corresponding to the image, already moved to device. + - PRED: prediction result of model. + + Args: + engine: `SupervisedEvaluator` to execute operation for an iteration. + batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data. + + Raises: + ValueError: When ``batchdata`` is None. + + """ + if batchdata is None: + raise ValueError("Must provide batch data for current iteration.") + batch = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs) + if len(batch) == 2: + inputs, targets = batch + args: tuple = () + kwargs: dict = {} + else: + inputs, targets, args, kwargs = batch + # FIXME: workaround for https://github.com/pytorch/pytorch/issues/117026 + if self.compile: + inputs_meta, targets_meta, inputs_applied_operations, targets_applied_operations = None, None, None, None + if isinstance(inputs, MetaTensor): + warnings.warn( + "Will convert to PyTorch Tensor if using compile, and casting back to MetaTensor after the forward pass." + ) + inputs, inputs_meta, inputs_applied_operations = ( + inputs.as_tensor(), + inputs.meta, + inputs.applied_operations, + ) + if isinstance(targets, MetaTensor): + targets, targets_meta, targets_applied_operations = ( + targets.as_tensor(), + targets.meta, + targets.applied_operations, + ) + + # put iteration outputs into engine.state + engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: targets} + # execute forward computation + with engine.mode(engine.network): + if engine.amp: + with torch.cuda.amp.autocast(**engine.amp_kwargs): + engine.state.output[Keys.PRED] = engine.inferer(inputs, engine.network, *args, **kwargs) + else: + engine.state.output[Keys.PRED] = engine.inferer(inputs, engine.network, *args, **kwargs) + # copy back meta info + if self.compile: + if inputs_meta is not None: + engine.state.output[Keys.IMAGE] = MetaTensor( + inputs, meta=inputs_meta, applied_operations=inputs_applied_operations + ) + engine.state.output[Keys.PRED] = MetaTensor( + engine.state.output[Keys.PRED], meta=inputs_meta, applied_operations=inputs_applied_operations + ) + if targets_meta is not None: + engine.state.output[Keys.LABEL] = MetaTensor( + targets, meta=targets_meta, applied_operations=targets_applied_operations + ) + engine.fire_event(IterationEvents.FORWARD_COMPLETED) + engine.fire_event(IterationEvents.MODEL_COMPLETED) + + return engine.state.output + + +class EnsembleEvaluator(Evaluator): + """ + Ensemble evaluation for multiple models, inherits from evaluator and Workflow. + It accepts a list of models for inference and outputs a list of predictions for further operations. + + Args: + device: an object representing the device on which to run. + val_data_loader: Ignite engine use data_loader to run, must be Iterable, typically be torch.DataLoader. + epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`. + networks: networks to evaluate in order in the evaluator, should be regular PyTorch `torch.nn.Module`. + pred_keys: the keys to store every prediction data. + the length must exactly match the number of networks. + if None, use "pred_{index}" as key corresponding to N networks, index from `0` to `N-1`. + non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously + with respect to the host. For other cases, this argument has no effect. + prepare_batch: function to parse expected data (usually `image`, `label` and other network args) + from `engine.state.batch` for every iteration, for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. + iteration_update: the callable function for every iteration, expect to accept `engine` + and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. + if not provided, use `self._iteration()` instead. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. + inferer: inference method that execute model forward on input data, like: SlidingWindow, etc. + postprocessing: execute additional transformation for the model output data. + Typically, several Tensor based transforms composed by `Compose`. + key_val_metric: compute metric when every iteration completed, and save average value to + engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the + checkpoint into files. + additional_metrics: more Ignite metrics that also attach to Ignite Engine. + metric_cmp_fn: function to compare current key metric with previous best key metric value, + it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update + `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. + val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: + CheckpointHandler, StatsHandler, etc. + amp: whether to enable auto-mixed-precision evaluation, default is False. + mode: model forward mode during evaluation, should be 'eval' or 'train', + which maps to `model.eval()` or `model.train()`, default to 'eval'. + event_names: additional custom ignite events that will register to the engine. + new events can be a list of str or `ignite.engine.events.EventEnum`. + event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`. + for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html + #ignite.engine.engine.Engine.register_events. + decollate: whether to decollate the batch-first data to a list of data after model computation, + recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. + default to `True`. + to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for + `device`, `non_blocking`. + amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: + https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. + + """ + + def __init__( + self, + device: torch.device, + val_data_loader: Iterable | DataLoader, + networks: Sequence[torch.nn.Module], + pred_keys: KeysCollection | None = None, + epoch_length: int | None = None, + non_blocking: bool = False, + prepare_batch: Callable = default_prepare_batch, + iteration_update: Callable[[Engine, Any], Any] | None = None, + inferer: Inferer | None = None, + postprocessing: Transform | None = None, + key_val_metric: dict[str, Metric] | None = None, + additional_metrics: dict[str, Metric] | None = None, + metric_cmp_fn: Callable = default_metric_cmp_fn, + val_handlers: Sequence | None = None, + amp: bool = False, + mode: ForwardMode | str = ForwardMode.EVAL, + event_names: list[str | EventEnum | type[EventEnum]] | None = None, + event_to_attr: dict | None = None, + decollate: bool = True, + to_kwargs: dict | None = None, + amp_kwargs: dict | None = None, + ) -> None: + super().__init__( + device=device, + val_data_loader=val_data_loader, + epoch_length=epoch_length, + non_blocking=non_blocking, + prepare_batch=prepare_batch, + iteration_update=iteration_update, + postprocessing=postprocessing, + key_val_metric=key_val_metric, + additional_metrics=additional_metrics, + metric_cmp_fn=metric_cmp_fn, + val_handlers=val_handlers, + amp=amp, + mode=mode, + event_names=event_names, + event_to_attr=event_to_attr, + decollate=decollate, + to_kwargs=to_kwargs, + amp_kwargs=amp_kwargs, + ) + + self.networks = ensure_tuple(networks) + self.pred_keys = ( + [f"{Keys.PRED}_{i}" for i in range(len(self.networks))] if pred_keys is None else ensure_tuple(pred_keys) + ) + if len(self.pred_keys) != len(self.networks): + raise ValueError("length of `pred_keys` must be same as the length of `networks`.") + self.inferer = SimpleInferer() if inferer is None else inferer + + def _iteration(self, engine: EnsembleEvaluator, batchdata: dict[str, torch.Tensor]) -> dict: + """ + callback function for the Supervised Evaluation processing logic of 1 iteration in Ignite Engine. + Return below items in a dictionary: + - IMAGE: image Tensor data for model input, already moved to device. + - LABEL: label Tensor data corresponding to the image, already moved to device. + - pred_keys[0]: prediction result of network 0. + - pred_keys[1]: prediction result of network 1. + - ... ... + - pred_keys[N]: prediction result of network N. + + Args: + engine: `EnsembleEvaluator` to execute operation for an iteration. + batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data. + + Raises: + ValueError: When ``batchdata`` is None. + + """ + if batchdata is None: + raise ValueError("Must provide batch data for current iteration.") + batch = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs) + if len(batch) == 2: + inputs, targets = batch + args: tuple = () + kwargs: dict = {} + else: + inputs, targets, args, kwargs = batch + + # put iteration outputs into engine.state + engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: targets} + + for idx, network in enumerate(engine.networks): + with engine.mode(network): + if engine.amp: + with torch.cuda.amp.autocast(**engine.amp_kwargs): + if isinstance(engine.state.output, dict): + engine.state.output.update( + {engine.pred_keys[idx]: engine.inferer(inputs, network, *args, **kwargs)} + ) + else: + if isinstance(engine.state.output, dict): + engine.state.output.update( + {engine.pred_keys[idx]: engine.inferer(inputs, network, *args, **kwargs)} + ) + engine.fire_event(IterationEvents.FORWARD_COMPLETED) + engine.fire_event(IterationEvents.MODEL_COMPLETED) + + return engine.state.output diff --git a/source_code/SegMamba/monai/engines/trainer.py b/source_code/SegMamba/monai/engines/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f1513ea73bd1ba36fdb57c871708d1937ab69585 --- /dev/null +++ b/source_code/SegMamba/monai/engines/trainer.py @@ -0,0 +1,473 @@ +# 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 typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence + +import torch +from torch.optim.optimizer import Optimizer +from torch.utils.data import DataLoader + +from monai.config import IgniteInfo +from monai.data import MetaTensor +from monai.engines.utils import IterationEvents, default_make_latent, default_metric_cmp_fn, default_prepare_batch +from monai.engines.workflow import Workflow +from monai.inferers import Inferer, SimpleInferer +from monai.transforms import Transform +from monai.utils import GanKeys, min_version, optional_import +from monai.utils.enums import CommonKeys as Keys +from monai.utils.enums import EngineStatsKeys as ESKeys +from monai.utils.module import pytorch_after + +if TYPE_CHECKING: + from ignite.engine import Engine, EventEnum + from ignite.metrics import Metric +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric") + EventEnum, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum") + +__all__ = ["Trainer", "SupervisedTrainer", "GanTrainer"] + + +class Trainer(Workflow): + """ + Base class for all kinds of trainers, inherits from Workflow. + + """ + + def run(self) -> None: # type: ignore[override] + """ + Execute training based on Ignite Engine. + If call this function multiple times, it will continuously run from the previous state. + + """ + self.scaler = torch.cuda.amp.GradScaler() if self.amp else None + super().run() + + def get_stats(self, *vars): + """ + Get the statistics information of the training process. + Default to return the `rank`, `current_epoch`, `current_iteration`, `total_epochs`, `total_iterations`. + + Args: + vars: except for the default stats, other variables name in the `self.state` to return, + will use the variable name as the key and the state content as the value. + if the variable doesn't exist, default value is `None`. + + """ + stats = { + ESKeys.RANK: self.state.rank, + ESKeys.CURRENT_EPOCH: self.state.epoch, + ESKeys.CURRENT_ITERATION: self.state.iteration, + ESKeys.TOTAL_EPOCHS: self.state.max_epochs, + ESKeys.TOTAL_ITERATIONS: self.state.epoch_length, + } + for k in vars: + stats[k] = getattr(self.state, k, None) + return stats + + +class SupervisedTrainer(Trainer): + """ + Standard supervised training method with image and label, inherits from ``Trainer`` and ``Workflow``. + + Args: + device: an object representing the device on which to run. + max_epochs: the total epoch number for trainer to run. + train_data_loader: Ignite engine use data_loader to run, must be Iterable or torch.DataLoader. + network: network to train in the trainer, should be regular PyTorch `torch.nn.Module`. + optimizer: the optimizer associated to the network, should be regular PyTorch optimizer from `torch.optim` + or its subclass. + loss_function: the loss function associated to the optimizer, should be regular PyTorch loss, + which inherit from `torch.nn.modules.loss`. + epoch_length: number of iterations for one epoch, default to `len(train_data_loader)`. + non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously + with respect to the host. For other cases, this argument has no effect. + prepare_batch: function to parse expected data (usually `image`, `label` and other network args) + from `engine.state.batch` for every iteration, for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. + iteration_update: the callable function for every iteration, expect to accept `engine` + and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. + if not provided, use `self._iteration()` instead. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. + inferer: inference method that execute model forward on input data, like: SlidingWindow, etc. + postprocessing: execute additional transformation for the model output data. + Typically, several Tensor based transforms composed by `Compose`. + key_train_metric: compute metric when every iteration completed, and save average value to + engine.state.metrics when epoch completed. key_train_metric is the main metric to compare and save the + checkpoint into files. + additional_metrics: more Ignite metrics that also attach to Ignite Engine. + metric_cmp_fn: function to compare current key metric with previous best key metric value, + it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update + `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. + train_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: + CheckpointHandler, StatsHandler, etc. + amp: whether to enable auto-mixed-precision training, default is False. + event_names: additional custom ignite events that will register to the engine. + new events can be a list of str or `ignite.engine.events.EventEnum`. + event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`. + for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html + #ignite.engine.engine.Engine.register_events. + decollate: whether to decollate the batch-first data to a list of data after model computation, + recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. + default to `True`. + optim_set_to_none: when calling `optimizer.zero_grad()`, instead of setting to zero, set the grads to None. + more details: https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html. + to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for + `device`, `non_blocking`. + amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: + https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. + compile: whether to use `torch.compile`, default is False. If True, MetaTensor inputs will be converted to + `torch.Tensor` before forward pass, then converted back afterward with copied meta information. + compile_kwargs: dict of the args for `torch.compile()` API, for more details: + https://pytorch.org/docs/stable/generated/torch.compile.html#torch-compile. + """ + + def __init__( + self, + device: str | torch.device, + max_epochs: int, + train_data_loader: Iterable | DataLoader, + network: torch.nn.Module, + optimizer: Optimizer, + loss_function: Callable, + epoch_length: int | None = None, + non_blocking: bool = False, + prepare_batch: Callable = default_prepare_batch, + iteration_update: Callable[[Engine, Any], Any] | None = None, + inferer: Inferer | None = None, + postprocessing: Transform | None = None, + key_train_metric: dict[str, Metric] | None = None, + additional_metrics: dict[str, Metric] | None = None, + metric_cmp_fn: Callable = default_metric_cmp_fn, + train_handlers: Sequence | None = None, + amp: bool = False, + event_names: list[str | EventEnum | type[EventEnum]] | None = None, + event_to_attr: dict | None = None, + decollate: bool = True, + optim_set_to_none: bool = False, + to_kwargs: dict | None = None, + amp_kwargs: dict | None = None, + compile: bool = False, + compile_kwargs: dict | None = None, + ) -> None: + super().__init__( + device=device, + max_epochs=max_epochs, + data_loader=train_data_loader, + epoch_length=epoch_length, + non_blocking=non_blocking, + prepare_batch=prepare_batch, + iteration_update=iteration_update, + postprocessing=postprocessing, + key_metric=key_train_metric, + additional_metrics=additional_metrics, + metric_cmp_fn=metric_cmp_fn, + handlers=train_handlers, + amp=amp, + event_names=event_names, + event_to_attr=event_to_attr, + decollate=decollate, + to_kwargs=to_kwargs, + amp_kwargs=amp_kwargs, + ) + if compile: + if pytorch_after(2, 1): + compile_kwargs = {} if compile_kwargs is None else compile_kwargs + network = torch.compile(network, **compile_kwargs) # type: ignore[assignment] + else: + warnings.warn( + "Network compilation (compile=True) not supported for Pytorch versions before 2.1, no compilation done" + ) + self.network = network + self.compile = compile + self.optimizer = optimizer + self.loss_function = loss_function + self.inferer = SimpleInferer() if inferer is None else inferer + self.optim_set_to_none = optim_set_to_none + + def _iteration(self, engine: SupervisedTrainer, batchdata: dict[str, torch.Tensor]) -> dict: + """ + Callback function for the Supervised Training processing logic of 1 iteration in Ignite Engine. + Return below items in a dictionary: + - IMAGE: image Tensor data for model input, already moved to device. + - LABEL: label Tensor data corresponding to the image, already moved to device. + - PRED: prediction result of model. + - LOSS: loss value computed by loss function. + + Args: + engine: `SupervisedTrainer` to execute operation for an iteration. + batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data. + + Raises: + ValueError: When ``batchdata`` is None. + + """ + if batchdata is None: + raise ValueError("Must provide batch data for current iteration.") + batch = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs) + if len(batch) == 2: + inputs, targets = batch + args: tuple = () + kwargs: dict = {} + else: + inputs, targets, args, kwargs = batch + # FIXME: workaround for https://github.com/pytorch/pytorch/issues/117026 + if self.compile: + inputs_meta, targets_meta, inputs_applied_operations, targets_applied_operations = None, None, None, None + if isinstance(inputs, MetaTensor): + warnings.warn( + "Will convert to PyTorch Tensor if using compile, and casting back to MetaTensor after the forward pass." + ) + inputs, inputs_meta, inputs_applied_operations = ( + inputs.as_tensor(), + inputs.meta, + inputs.applied_operations, + ) + if isinstance(targets, MetaTensor): + targets, targets_meta, targets_applied_operations = ( + targets.as_tensor(), + targets.meta, + targets.applied_operations, + ) + + # put iteration outputs into engine.state + engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: targets} + + def _compute_pred_loss(): + engine.state.output[Keys.PRED] = engine.inferer(inputs, engine.network, *args, **kwargs) + engine.fire_event(IterationEvents.FORWARD_COMPLETED) + engine.state.output[Keys.LOSS] = engine.loss_function(engine.state.output[Keys.PRED], targets).mean() + engine.fire_event(IterationEvents.LOSS_COMPLETED) + + engine.network.train() + engine.optimizer.zero_grad(set_to_none=engine.optim_set_to_none) + + if engine.amp and engine.scaler is not None: + with torch.cuda.amp.autocast(**engine.amp_kwargs): + _compute_pred_loss() + engine.scaler.scale(engine.state.output[Keys.LOSS]).backward() + engine.fire_event(IterationEvents.BACKWARD_COMPLETED) + engine.scaler.step(engine.optimizer) + engine.scaler.update() + else: + _compute_pred_loss() + engine.state.output[Keys.LOSS].backward() + engine.fire_event(IterationEvents.BACKWARD_COMPLETED) + engine.optimizer.step() + # copy back meta info + if self.compile: + if inputs_meta is not None: + engine.state.output[Keys.IMAGE] = MetaTensor( + inputs, meta=inputs_meta, applied_operations=inputs_applied_operations + ) + engine.state.output[Keys.PRED] = MetaTensor( + engine.state.output[Keys.PRED], meta=inputs_meta, applied_operations=inputs_applied_operations + ) + if targets_meta is not None: + engine.state.output[Keys.LABEL] = MetaTensor( + targets, meta=targets_meta, applied_operations=targets_applied_operations + ) + engine.fire_event(IterationEvents.MODEL_COMPLETED) + + return engine.state.output + + +class GanTrainer(Trainer): + """ + Generative adversarial network training based on Goodfellow et al. 2014 https://arxiv.org/abs/1406.266, + inherits from ``Trainer`` and ``Workflow``. + + Training Loop: for each batch of data size `m` + 1. Generate `m` fakes from random latent codes. + 2. Update discriminator with these fakes and current batch reals, repeated d_train_steps times. + 3. If g_update_latents, generate `m` fakes from new random latent codes. + 4. Update generator with these fakes using discriminator feedback. + + Args: + device: an object representing the device on which to run. + max_epochs: the total epoch number for engine to run. + train_data_loader: Core ignite engines uses `DataLoader` for training loop batchdata. + g_network: generator (G) network architecture. + g_optimizer: G optimizer function. + g_loss_function: G loss function for optimizer. + d_network: discriminator (D) network architecture. + d_optimizer: D optimizer function. + d_loss_function: D loss function for optimizer. + epoch_length: number of iterations for one epoch, default to `len(train_data_loader)`. + g_inferer: inference method to execute G model forward. Defaults to ``SimpleInferer()``. + d_inferer: inference method to execute D model forward. Defaults to ``SimpleInferer()``. + d_train_steps: number of times to update D with real data minibatch. Defaults to ``1``. + latent_shape: size of G input latent code. Defaults to ``64``. + non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously + with respect to the host. For other cases, this argument has no effect. + d_prepare_batch: callback function to prepare batchdata for D inferer. + Defaults to return ``GanKeys.REALS`` in batchdata dict. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. + g_prepare_batch: callback function to create batch of latent input for G inferer. + Defaults to return random latents. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. + g_update_latents: Calculate G loss with new latent codes. Defaults to ``True``. + iteration_update: the callable function for every iteration, expect to accept `engine` + and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. + if not provided, use `self._iteration()` instead. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. + postprocessing: execute additional transformation for the model output data. + Typically, several Tensor based transforms composed by `Compose`. + key_train_metric: compute metric when every iteration completed, and save average value to + engine.state.metrics when epoch completed. key_train_metric is the main metric to compare and save the + checkpoint into files. + additional_metrics: more Ignite metrics that also attach to Ignite Engine. + metric_cmp_fn: function to compare current key metric with previous best key metric value, + it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update + `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. + train_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: + CheckpointHandler, StatsHandler, etc. + decollate: whether to decollate the batch-first data to a list of data after model computation, + recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. + default to `True`. + optim_set_to_none: when calling `optimizer.zero_grad()`, instead of setting to zero, set the grads to None. + more details: https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html. + to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for + `device`, `non_blocking`. + amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: + https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. + + """ + + def __init__( + self, + device: str | torch.device, + max_epochs: int, + train_data_loader: DataLoader, + g_network: torch.nn.Module, + g_optimizer: Optimizer, + g_loss_function: Callable, + d_network: torch.nn.Module, + d_optimizer: Optimizer, + d_loss_function: Callable, + epoch_length: int | None = None, + g_inferer: Inferer | None = None, + d_inferer: Inferer | None = None, + d_train_steps: int = 1, + latent_shape: int = 64, + non_blocking: bool = False, + d_prepare_batch: Callable = default_prepare_batch, + g_prepare_batch: Callable = default_make_latent, + g_update_latents: bool = True, + iteration_update: Callable[[Engine, Any], Any] | None = None, + postprocessing: Transform | None = None, + key_train_metric: dict[str, Metric] | None = None, + additional_metrics: dict[str, Metric] | None = None, + metric_cmp_fn: Callable = default_metric_cmp_fn, + train_handlers: Sequence | None = None, + decollate: bool = True, + optim_set_to_none: bool = False, + to_kwargs: dict | None = None, + amp_kwargs: dict | None = None, + ): + if not isinstance(train_data_loader, DataLoader): + raise ValueError("train_data_loader must be PyTorch DataLoader.") + + # set up Ignite engine and environments + super().__init__( + device=device, + max_epochs=max_epochs, + data_loader=train_data_loader, + epoch_length=epoch_length, + non_blocking=non_blocking, + prepare_batch=d_prepare_batch, + iteration_update=iteration_update, + key_metric=key_train_metric, + additional_metrics=additional_metrics, + metric_cmp_fn=metric_cmp_fn, + handlers=train_handlers, + postprocessing=postprocessing, + decollate=decollate, + to_kwargs=to_kwargs, + amp_kwargs=amp_kwargs, + ) + self.g_network = g_network + self.g_optimizer = g_optimizer + self.g_loss_function = g_loss_function + self.g_inferer = SimpleInferer() if g_inferer is None else g_inferer + self.d_network = d_network + self.d_optimizer = d_optimizer + self.d_loss_function = d_loss_function + self.d_inferer = SimpleInferer() if d_inferer is None else d_inferer + self.d_train_steps = d_train_steps + self.latent_shape = latent_shape + self.g_prepare_batch = g_prepare_batch + self.g_update_latents = g_update_latents + self.optim_set_to_none = optim_set_to_none + + def _iteration( + self, engine: GanTrainer, batchdata: dict | Sequence + ) -> dict[str, torch.Tensor | int | float | bool]: + """ + Callback function for Adversarial Training processing logic of 1 iteration in Ignite Engine. + + Args: + engine: `GanTrainer` to execute operation for an iteration. + batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data. + + Raises: + ValueError: must provide batch data for current iteration. + + """ + if batchdata is None: + raise ValueError("must provide batch data for current iteration.") + + d_input = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs) + batch_size = engine.data_loader.batch_size # type: ignore + g_input = engine.g_prepare_batch( + num_latents=batch_size, + latent_size=engine.latent_shape, + device=engine.state.device, + non_blocking=engine.non_blocking, + **engine.to_kwargs, + ) + g_output = engine.g_inferer(g_input, engine.g_network) + + # Train Discriminator + d_total_loss = torch.zeros(1) + for _ in range(engine.d_train_steps): + engine.d_optimizer.zero_grad(set_to_none=engine.optim_set_to_none) + dloss = engine.d_loss_function(g_output, d_input) + dloss.backward() + engine.d_optimizer.step() + d_total_loss += dloss.item() + + # Train Generator + if engine.g_update_latents: + g_input = engine.g_prepare_batch( + num_latents=batch_size, + latent_size=engine.latent_shape, + device=engine.state.device, + non_blocking=engine.non_blocking, + **engine.to_kwargs, + ) + g_output = engine.g_inferer(g_input, engine.g_network) + engine.g_optimizer.zero_grad(set_to_none=engine.optim_set_to_none) + g_loss = engine.g_loss_function(g_output) + g_loss.backward() + engine.g_optimizer.step() + + return { + GanKeys.REALS: d_input, + GanKeys.FAKES: g_output, + GanKeys.LATENTS: g_input, + GanKeys.GLOSS: g_loss.item(), + GanKeys.DLOSS: d_total_loss.item(), + } diff --git a/source_code/SegMamba/monai/engines/utils.py b/source_code/SegMamba/monai/engines/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..02c718cd14ff502354e830b51ae54e83deedd61e --- /dev/null +++ b/source_code/SegMamba/monai/engines/utils.py @@ -0,0 +1,288 @@ +# 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 abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any, cast + +import torch + +from monai.config import IgniteInfo +from monai.transforms import apply_transform +from monai.utils import ensure_tuple, min_version, optional_import +from monai.utils.enums import CommonKeys, GanKeys + +if TYPE_CHECKING: + from ignite.engine import EventEnum +else: + EventEnum, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum", as_type="base" + ) + +__all__ = [ + "IterationEvents", + "get_devices_spec", + "default_prepare_batch", + "PrepareBatch", + "PrepareBatchDefault", + "PrepareBatchExtraInput", + "default_make_latent", + "engine_apply_transform", + "default_metric_cmp_fn", +] + + +class IterationEvents(EventEnum): + """ + Additional Events engine can register and trigger in the iteration process. + Refer to the example in ignite: https://pytorch.org/ignite/generated/ignite.engine.events.EventEnum.html. + These Events can be triggered during training iteration: + `FORWARD_COMPLETED` is the Event when `network(image, label)` completed. + `LOSS_COMPLETED` is the Event when `loss(pred, label)` completed. + `BACKWARD_COMPLETED` is the Event when `loss.backward()` completed. + `MODEL_COMPLETED` is the Event when all the model related operations completed. + `INNER_ITERATION_STARTED` is the Event when the iteration has an inner loop and the loop is started. + `INNER_ITERATION_COMPLETED` is the Event when the iteration has an inner loop and the loop is completed. + """ + + FORWARD_COMPLETED = "forward_completed" + LOSS_COMPLETED = "loss_completed" + BACKWARD_COMPLETED = "backward_completed" + MODEL_COMPLETED = "model_completed" + INNER_ITERATION_STARTED = "inner_iteration_started" + INNER_ITERATION_COMPLETED = "inner_iteration_completed" + + +def get_devices_spec(devices: Sequence[torch.device | str] | None = None) -> list[torch.device]: + """ + Get a valid specification for one or more devices. If `devices` is None get devices for all CUDA devices available. + If `devices` is and zero-length structure a single CPU compute device is returned. In any other cases `devices` is + returned unchanged. + + Args: + devices: list of devices to request, None for all GPU devices, [] for CPU. + + Raises: + RuntimeError: When all GPUs are selected (``devices=None``) but no GPUs are available. + + Returns: + list of torch.device: list of devices. + + """ + if devices is None: + devices = [torch.device(f"cuda:{d:d}") for d in range(torch.cuda.device_count())] + + if not devices: + raise RuntimeError("No GPU devices available.") + + elif len(devices) == 0: + devices = [torch.device("cpu")] + + else: + devices = list(devices) + + devices = [torch.device(d) if isinstance(d, str) else d for d in devices] + return devices # type: ignore + + +def default_prepare_batch( + batchdata: dict[str, torch.Tensor] | torch.Tensor | Sequence[torch.Tensor], + device: str | torch.device | None = None, + non_blocking: bool = False, + **kwargs: Any, +) -> tuple[torch.Tensor, torch.Tensor | None] | torch.Tensor: + """ + Default function to prepare the data for current iteration. + + The input `batchdata` is either a single tensor, a pair of tensors, or a dictionary of data. In the first case the + return value is the tensor and None, in the second case the return value is the two tensors, and in the dictionary + case the return value depends on what keys are present. if `CommonKeys.IMAGE` and `CommonKeys.LABEL` are present + then the tensors they key to are returned, if only `CommonKeys.IMAGE` is present that tensor and None is returned. + If `CommonKeys.REALS` is present this is returned with None. All returned tensors are moved to the given device + using the given non-blocking argument before being returned. + + This function implements the expected API for a `prepare_batch` callable in Ignite: + https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html + + Args: + batchdata: input batch data which is either a single tensor, a pair, or a dictionary + device: device to move every returned tensor to + non_blocking: equivalent argument for `Tensor.to` + kwargs: further arguments for `Tensor.to` + + Returns: + image, label(optional). + """ + if not isinstance(batchdata, dict): + if isinstance(batchdata, torch.Tensor): + return batchdata.to(device=device, non_blocking=non_blocking, **kwargs), None + elif len(batchdata) == 2: + image, label = batchdata + return ( + image.to(device=device, non_blocking=non_blocking, **kwargs), + label.to(device=device, non_blocking=non_blocking, **kwargs), + ) + + raise AssertionError("Default prepare_batch expects a single tensor, a tensor pair, or dictionary input data.") + + if isinstance(batchdata.get(CommonKeys.LABEL), torch.Tensor): + return ( + batchdata[CommonKeys.IMAGE].to(device=device, non_blocking=non_blocking, **kwargs), + batchdata[CommonKeys.LABEL].to(device=device, non_blocking=non_blocking, **kwargs), + ) + + if GanKeys.REALS in batchdata: + return batchdata[GanKeys.REALS].to(device=device, non_blocking=non_blocking, **kwargs) + + return batchdata[CommonKeys.IMAGE].to(device=device, non_blocking=non_blocking, **kwargs), None + + +class PrepareBatch(ABC): + """ + Interface of customized prepare_batch in the trainer or evaluator workflows. + It takes the data of current batch, target device and non_blocking flag as input. + Args `batchdata`, `device`, `non_blocking` refer to the ignite API: + https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html. + `kwargs` supports other args for `Tensor.to()` API. + """ + + @abstractmethod + def __call__( + self, + batchdata: dict[str, torch.Tensor], + device: str | torch.device | None = None, + non_blocking: bool = False, + **kwargs: Any, + ) -> Any: + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + +class PrepareBatchDefault(PrepareBatch): + """ + This wraps `default_prepare_batch` to return `image` and `label` only, so is consistent with its API. + """ + + def __call__( + self, + batchdata: dict[str, torch.Tensor] | torch.Tensor | Sequence[torch.Tensor], + device: str | torch.device | None = None, + non_blocking: bool = False, + **kwargs: Any, + ) -> tuple[torch.Tensor, torch.Tensor | None] | torch.Tensor: + """ + Args `batchdata`, `device`, `non_blocking` refer to the ignite API: + https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html. + `kwargs` supports other args for `Tensor.to()` API. + + """ + return default_prepare_batch(batchdata, device, non_blocking, **kwargs) + + +class PrepareBatchExtraInput(PrepareBatch): + """ + Customized prepare batch callable for trainers or evaluators which support extra input data for the network. + Extra items are specified by the `extra_keys` parameter and are extracted from the input dictionary (ie. the batch). + This uses `default_prepare_batch` but requires dictionary inputs. + + Args: + extra_keys: If a string or sequence of strings is provided, values from the input dictionary are extracted from + those keys and passed to the network as extra positional arguments. If a dictionary is provided, every pair + `(k, v)` in that dictionary will become a new keyword argument assigning to `k` the value in the input + dictionary keyed to `v`. + """ + + def __init__(self, extra_keys: str | Sequence[str] | dict[str, str]) -> None: + self.extra_keys = extra_keys + + def __call__( + self, + batchdata: dict[str, torch.Tensor], + device: str | torch.device | None = None, + non_blocking: bool = False, + **kwargs: Any, + ) -> tuple[torch.Tensor, torch.Tensor, tuple, dict]: + """ + Args `batchdata`, `device`, `non_blocking` refer to the ignite API: + https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html. + `kwargs` supports other args for `Tensor.to()` API. + """ + image, label = default_prepare_batch(batchdata, device, non_blocking, **kwargs) + args_ = list() + kwargs_ = dict() + + def _get_data(key: str) -> torch.Tensor: + data = batchdata[key] + + if isinstance(data, torch.Tensor): + data = data.to(device=device, non_blocking=non_blocking, **kwargs) + + return data + + if isinstance(self.extra_keys, (str, list, tuple)): + for k in ensure_tuple(self.extra_keys): + args_.append(_get_data(k)) + elif isinstance(self.extra_keys, dict): + for k, v in self.extra_keys.items(): + kwargs_.update({k: _get_data(v)}) + + return cast(torch.Tensor, image), cast(torch.Tensor, label), tuple(args_), kwargs_ + + +def default_make_latent( + num_latents: int, + latent_size: int, + device: str | torch.device | None = None, + non_blocking: bool = False, + **kwargs: Any, +) -> torch.Tensor: + return torch.randn(num_latents, latent_size).to(device=device, non_blocking=non_blocking, **kwargs) + + +def engine_apply_transform(batch: Any, output: Any, transform: Callable[..., dict]) -> tuple[Any, Any]: + """ + Apply transform on `batch` and `output`. + If `batch` and `output` are dictionaries, temporarily combine them for the transform, + otherwise, apply the transform for `output` data only. + + """ + if isinstance(batch, dict) and isinstance(output, dict): + data = dict(batch) + data.update(output) + transformed_data = apply_transform(transform, data) + + if not isinstance(transformed_data, dict): + raise AssertionError("With a dict supplied to apply_transform a single dict return is expected.") + + for k, v in transformed_data.items(): + # split the output data of post transforms into `output` and `batch`, + # `batch` should be read-only, so save the generated key-value into `output` + if k in output or k not in batch: + output[k] = v + else: + batch[k] = v + else: + output = apply_transform(transform, output) + + return batch, output + + +def default_metric_cmp_fn(current_metric: float, prev_best: float) -> bool: + """ + The default function to compare metric values between current metric and previous best metric. + + Args: + current_metric: metric value of current round computation. + prev_best: the best metric value of previous rounds to compare with. + + """ + return current_metric > prev_best diff --git a/source_code/SegMamba/monai/engines/workflow.py b/source_code/SegMamba/monai/engines/workflow.py new file mode 100644 index 0000000000000000000000000000000000000000..30622c2b93e276cbd67d78dec9c861304bee2c8c --- /dev/null +++ b/source_code/SegMamba/monai/engines/workflow.py @@ -0,0 +1,309 @@ +# 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 collections.abc import Callable, Iterable, Sequence +from typing import TYPE_CHECKING, Any + +import torch +import torch.distributed as dist +from torch.utils.data import DataLoader +from torch.utils.data.distributed import DistributedSampler + +from monai.config import IgniteInfo +from monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batch +from monai.transforms import Decollated +from monai.utils import ensure_tuple, is_scalar, min_version, optional_import + +from .utils import engine_apply_transform + +State, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "State") +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") + +if TYPE_CHECKING: + from ignite.engine import Engine, EventEnum + from ignite.metrics import Metric +else: + Engine, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine", as_type="decorator" + ) + Metric, _ = optional_import( + "ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric", as_type="decorator" + ) + EventEnum, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum", as_type="decorator" + ) + + +class Workflow(Engine): + """ + Workflow defines the core work process inheriting from Ignite engine. + All trainer, validator and evaluator share this same workflow as base class, + because they all can be treated as same Ignite engine loops. + It initializes all the sharable data in Ignite engine.state. + And attach additional processing logics to Ignite engine based on Event-Handler mechanism. + + Users should consider inheriting from `trainer` or `evaluator` to develop more trainers or evaluators. + + Args: + device: an object representing the device on which to run. + max_epochs: the total epoch number for engine to run, validator and evaluator have only 1 epoch. + data_loader: Ignite engine use data_loader to run, must be Iterable or torch.DataLoader. + epoch_length: number of iterations for one epoch, default to `len(data_loader)`. + non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously + with respect to the host. For other cases, this argument has no effect. + prepare_batch: function to parse expected data (usually `image`, `label` and other network args) + from `engine.state.batch` for every iteration, for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. + iteration_update: the callable function for every iteration, expect to accept `engine` + and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. + if not provided, use `self._iteration()` instead. for more details please refer to: + https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. + postprocessing: execute additional transformation for the model output data. + Typically, several Tensor based transforms composed by `Compose`. + key_metric: compute metric when every iteration completed, and save average value to + engine.state.metrics when epoch completed. key_metric is the main metric to compare and save the + checkpoint into files. + additional_metrics: more Ignite metrics that also attach to Ignite Engine. + metric_cmp_fn: function to compare current key metric with previous best key metric value, + it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update + `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. + handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: + CheckpointHandler, StatsHandler, etc. + amp: whether to enable auto-mixed-precision training or inference, default is False. + event_names: additional custom ignite events that will register to the engine. + new events can be a list of str or `ignite.engine.events.EventEnum`. + event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`. + for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html + #ignite.engine.engine.Engine.register_events. + decollate: whether to decollate the batch-first data to a list of data after model computation, + recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. + default to `True`. + to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for + `device`, `non_blocking`. + amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: + https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. + + Raises: + TypeError: When ``data_loader`` is not a ``torch.utils.data.DataLoader``. + TypeError: When ``key_metric`` is not a ``Optional[dict]``. + TypeError: When ``additional_metrics`` is not a ``Optional[dict]``. + + """ + + def __init__( + self, + device: torch.device | str, + max_epochs: int, + data_loader: Iterable | DataLoader, + epoch_length: int | None = None, + non_blocking: bool = False, + prepare_batch: Callable = default_prepare_batch, + iteration_update: Callable[[Engine, Any], Any] | None = None, + postprocessing: Callable | None = None, + key_metric: dict[str, Metric] | None = None, + additional_metrics: dict[str, Metric] | None = None, + metric_cmp_fn: Callable = default_metric_cmp_fn, + handlers: Sequence | None = None, + amp: bool = False, + event_names: list[str | EventEnum | type[EventEnum]] | None = None, + event_to_attr: dict | None = None, + decollate: bool = True, + to_kwargs: dict | None = None, + amp_kwargs: dict | None = None, + ) -> None: + if iteration_update is not None: + super().__init__(iteration_update) + else: + super().__init__(self._iteration) + + if isinstance(data_loader, DataLoader): + sampler = data_loader.__dict__["sampler"] + if isinstance(sampler, DistributedSampler): + + @self.on(Events.EPOCH_STARTED) + def set_sampler_epoch(engine: Engine) -> None: + sampler.set_epoch(engine.state.epoch) + + if epoch_length is None: + epoch_length = len(data_loader) + else: + if epoch_length is None: + raise ValueError("If data_loader is not PyTorch DataLoader, must specify the epoch_length.") + + # set all sharable data for the workflow based on Ignite engine.state + self.state: Any = State( + rank=dist.get_rank() if dist.is_available() and dist.is_initialized() else 0, + seed=0, + iteration=0, + epoch=0, + max_epochs=max_epochs, + epoch_length=epoch_length, + output=None, + batch=None, + metrics={}, + metric_details={}, + dataloader=None, + device=device if isinstance(device, torch.device) or device is None else torch.device(device), + key_metric_name=None, # we can set many metrics, only use key_metric to compare and save the best model + best_metric=-1, + best_metric_epoch=-1, + ) + self.data_loader = data_loader + self.non_blocking = non_blocking + self.prepare_batch = prepare_batch + self.metric_cmp_fn = metric_cmp_fn + self.amp = amp + self.to_kwargs = {} if to_kwargs is None else to_kwargs + self.amp_kwargs = {} if amp_kwargs is None else amp_kwargs + self.scaler: torch.cuda.amp.GradScaler | None = None + + if event_names is None: + event_names = [IterationEvents] + else: + if not isinstance(event_names, list): + raise ValueError("`event_names` must be a list of strings or EventEnums.") + event_names += [IterationEvents] + for name in event_names: + if isinstance(name, (str, EventEnum)): + self.register_events(name, event_to_attr=event_to_attr) # type: ignore[arg-type] + elif issubclass(name, EventEnum): + self.register_events(*name, event_to_attr=event_to_attr) + else: + raise ValueError("`event_names` must be a list of strings or EventEnums.") + + if decollate: + self._register_decollate() + + if postprocessing is not None: + # tips: if `decollate=False` and `postprocessing` is MONAI transforms, it may not work well + # because all the MONAI transforms expect `channel-first` data + self._register_postprocessing(postprocessing) + if key_metric is not None: + self._register_metrics(key_metric, additional_metrics) + if handlers is not None: + self._register_handlers(handlers) + + def _register_decollate(self): + """ + Register the decollate operation for batch data, will execute after model forward and loss forward. + + """ + + @self.on(IterationEvents.MODEL_COMPLETED) + def _decollate_data(engine: Engine) -> None: + # replicate the scalar values to make sure all the items have batch dimension, then decollate + transform = Decollated(keys=None, detach=True) + if isinstance(engine.state.batch, (list, dict)): + engine.state.batch = transform(engine.state.batch) + if isinstance(engine.state.output, (list, dict)): + engine.state.output = transform(engine.state.output) + + def _register_postprocessing(self, posttrans: Callable) -> None: + """ + Register the postprocessing logic to the engine, will execute them as a chain when iteration completed. + + """ + + @self.on(IterationEvents.MODEL_COMPLETED) + def _run_postprocessing(engine: Engine) -> None: + if not isinstance(engine.state.batch, list) or not isinstance(engine.state.output, list): + engine.state.batch, engine.state.output = engine_apply_transform( + batch=engine.state.batch, output=engine.state.output, transform=posttrans + ) + else: + for i, (b, o) in enumerate(zip(engine.state.batch, engine.state.output)): + engine.state.batch[i], engine.state.output[i] = engine_apply_transform(b, o, posttrans) + + def _register_metrics(self, k_metric: dict, add_metrics: dict | None = None) -> None: + """ + Register the key metric and additional metrics to the engine, supports ignite Metrics. + + """ + if not isinstance(k_metric, dict): + raise TypeError(f"`key_metric` must be None or a dict but is {type(k_metric).__name__}.") + self.state.key_metric_name = list(k_metric.keys())[0] + metrics = dict(k_metric) + if add_metrics is not None and len(add_metrics) > 0: + if not isinstance(add_metrics, dict): + raise TypeError(f"Additional metrics must be None or a dict but is {type(add_metrics).__name__}.") + metrics.update(add_metrics) + for name, metric in metrics.items(): + metric.attach(self, name) + + @self.on(Events.EPOCH_COMPLETED) + def _compare_metrics(engine: Workflow) -> None: + key_metric_name = engine.state.key_metric_name + if key_metric_name is not None: + current_val_metric = engine.state.metrics[key_metric_name] + if not is_scalar(current_val_metric): + warnings.warn( + "Key metric is not a scalar value, skip the metric comparison with the current best metric." + "Please set other metrics as the key metric, or change the `reduction` mode to 'mean'." + ) + return + + if engine.state.best_metric_epoch == -1 or self.metric_cmp_fn( + current_val_metric, engine.state.best_metric + ): + self.logger.info(f"Got new best metric of {key_metric_name}: {current_val_metric}") + engine.state.best_metric = current_val_metric + engine.state.best_metric_epoch = engine.state.epoch + + def _register_handlers(self, handlers: Sequence) -> None: + """ + Register the handlers to the engine, supports ignite Handlers with `attach` API. + + """ + handlers_ = ensure_tuple(handlers) + for handler in handlers_: + handler.attach(self) + + def run(self) -> None: # type: ignore[override] + """ + Execute training, validation or evaluation based on Ignite Engine. + """ + if self.state.epoch_length == 0: + warnings.warn( + "`dataloader` is empty or the specified `epoch_length` is 0, skip the `run`." + " If running distributed training, the program may hang in `all-gather`, `all-reduce`, etc." + " because not all the ranks run the same computation logic." + ) + return + super().run(data=self.data_loader, max_epochs=self.state.max_epochs) + + def _iteration(self, engine: Any, batchdata: dict[str, torch.Tensor]) -> dict: + """ + Abstract callback function for the processing logic of 1 iteration in Ignite Engine. + Need subclass to implement different logics, like SupervisedTrainer/Evaluator, GANTrainer, etc. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data. + + Raises: + NotImplementedError: When the subclass does not override this method. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + def get_stats(self, *vars): + """ + Get the statistics information of the workflow process. + + Args: + vars: variables name in the `self.state`, will use the variable name as the key + and the state content as the value. if the variable doesn't exist, default value is `None`. + + """ + return {k: getattr(self.state, k, None) for k in vars} diff --git a/source_code/SegMamba/monai/fl/__init__.py b/source_code/SegMamba/monai/fl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e97f8940782e96a77c1c08483fc41da9a48ae22 --- /dev/null +++ b/source_code/SegMamba/monai/fl/__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/handlers/__init__.py b/source_code/SegMamba/monai/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..641f9aae7dab692dd9b5c9485d46aff97723480a --- /dev/null +++ b/source_code/SegMamba/monai/handlers/__init__.py @@ -0,0 +1,44 @@ +# 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 .checkpoint_loader import CheckpointLoader +from .checkpoint_saver import CheckpointSaver +from .classification_saver import ClassificationSaver +from .clearml_handlers import ClearMLHandler, ClearMLImageHandler, ClearMLStatsHandler +from .confusion_matrix import ConfusionMatrix +from .decollate_batch import DecollateBatch +from .earlystop_handler import EarlyStopHandler +from .garbage_collector import GarbageCollector +from .hausdorff_distance import HausdorffDistance +from .ignite_metric import IgniteMetric, IgniteMetricHandler +from .logfile_handler import LogfileHandler +from .lr_schedule_handler import LrScheduleHandler +from .mean_dice import MeanDice +from .mean_iou import MeanIoUHandler +from .metric_logger import MetricLogger, MetricLoggerKeys +from .metrics_reloaded_handler import MetricsReloadedBinaryHandler, MetricsReloadedCategoricalHandler +from .metrics_saver import MetricsSaver +from .mlflow_handler import MLFlowHandler +from .nvtx_handlers import MarkHandler, RangeHandler, RangePopHandler, RangePushHandler +from .panoptic_quality import PanopticQuality +from .parameter_scheduler import ParamSchedulerHandler +from .postprocessing import PostProcessing +from .probability_maps import ProbMapProducer +from .regression_metrics import MeanAbsoluteError, MeanSquaredError, PeakSignalToNoiseRatio, RootMeanSquaredError +from .roc_auc import ROCAUC +from .smartcache_handler import SmartCacheHandler +from .stats_handler import StatsHandler +from .surface_distance import SurfaceDistance +from .tensorboard_handlers import TensorBoardHandler, TensorBoardImageHandler, TensorBoardStatsHandler +from .utils import from_engine, ignore_data, stopping_fn_from_loss, stopping_fn_from_metric, write_metrics_reports +from .validation_handler import ValidationHandler diff --git a/source_code/SegMamba/monai/handlers/checkpoint_loader.py b/source_code/SegMamba/monai/handlers/checkpoint_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..9a867534a3f1af590d96e65933790b42c8ced9db --- /dev/null +++ b/source_code/SegMamba/monai/handlers/checkpoint_loader.py @@ -0,0 +1,157 @@ +# 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 warnings +from typing import TYPE_CHECKING + +import torch + +from monai.config import IgniteInfo +from monai.networks.utils import copy_model_state +from monai.utils import min_version, optional_import + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +Checkpoint, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Checkpoint") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + + +class CheckpointLoader: + """ + CheckpointLoader acts as an Ignite handler to load checkpoint data from file. + It can load variables for network, optimizer, lr_scheduler, etc. + If saving checkpoint after `torch.nn.DataParallel`, need to save `model.module` instead + as PyTorch recommended and then use this loader to load the model. + + Usage example:: + + trainer = SupervisedTrainer(...) + save_dict = { + "trainer": trainer, + "net": network, + "opt": optimizer, + "lr": lr_scheduler, + } + + map_location = "cuda:0" + # checkpoint needs to have same save_dict for this to work + handler = CheckpointLoader(load_path="/test/checkpoint.pt", load_dict=save_dict, map_location=map_location, strict=True) + handler(trainer) + # Trainer now has the same state as stored, including the number of epochs and iterations completed + # so you can resume an interrupted training at the place where it left + + Args: + load_path: the file path of checkpoint, it should be a PyTorch `pth` file. + load_dict: target objects that load checkpoint to. examples:: + + {'network': net, 'optimizer': optimizer, 'lr_scheduler': lr_scheduler} + + name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``. + map_location: when loading the module for distributed training/evaluation, + need to provide an appropriate map_location argument to prevent a process + to step into others’ devices. If map_location is missing, torch.load will + first load the module to CPU and then copy each parameter to where it was + saved, which would result in all processes on the same machine using the + same set of devices. + strict: whether to strictly enforce that the keys and data shape in the `state_dict` of every item + of `load_dict` match the `state_dict` of the corresponding items of checkpoint, default to `True`. + strict_shape: whether to enforce the data shape of the matched layers in the checkpoint, + `if `False`, it will skip the layers that have different data shape with checkpoint content, + and ignore the `strict` arg. this can be useful advanced feature for transfer learning. + users should totally understand which layers will have different shape. default to `True`. + + Note: if `strict_shape=False`, will only load checkpoint for `torch.nn.Module` and skip other + items in the `load_dict`. For example, if the shape of some layers in current model can't + match the checkpoint, the `parameter_group` of current optimizer may also can't match the + checkpoint, so skip loading checkpoint for optimizer. + + For more details about loading checkpoint, please refer to: + https://pytorch.org/ignite/v0.4.5/generated/ignite.handlers.checkpoint.Checkpoint.html + #ignite.handlers.checkpoint.Checkpoint.load_objects. + https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.load_state_dict. + + """ + + def __init__( + self, + load_path: str, + load_dict: dict, + name: str | None = None, + map_location: dict | None = None, + strict: bool = True, + strict_shape: bool = True, + ) -> None: + if load_path is None: + raise AssertionError("must provide clear path to load checkpoint.") + self.load_path = load_path + if load_dict is None or len(load_dict) <= 0: + raise AssertionError("must provide target objects to load.") + self.logger = logging.getLogger(name) + self.load_dict = load_dict + self._name = name + self.map_location = map_location + if strict and not strict_shape: + warnings.warn("as `strict_shape` is already False, change `strict` to False.") + strict = False + self.strict = strict + self.strict_shape = strict_shape + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + engine.add_event_handler(Events.STARTED, self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + checkpoint = torch.load(self.load_path, map_location=self.map_location) + + k, _ = list(self.load_dict.items())[0] + # single object and checkpoint is directly a state_dict + if len(self.load_dict) == 1 and k not in checkpoint: + checkpoint = {k: checkpoint} + + if not self.strict_shape: + pop_items: list[str] = [] + for k, obj in self.load_dict.items(): + if isinstance(obj, torch.nn.Module): + # skip items that don't match key name or data shape + checkpoint[k] = copy_model_state(obj, checkpoint, inplace=False)[0] + else: + warnings.warn("`strict_shape` is False, load checkpoint for model, skip others in `load_dict`.") + pop_items.append(k) + for i in pop_items: + self.load_dict.pop(i) + + # save current max epochs setting in the engine, don't overwrite it if larger than max_epochs in checkpoint + prior_max_epochs = engine.state.max_epochs + Checkpoint.load_objects(to_load=self.load_dict, checkpoint=checkpoint, strict=self.strict) + if prior_max_epochs is not None and engine.state.epoch > prior_max_epochs: + raise ValueError( + f"Epoch count ({engine.state.epoch}) in checkpoint is larger than " + f"the `engine.state.max_epochs` ({prior_max_epochs}) of engine. To further train from checkpoint, " + "construct trainer with `max_epochs` larger than checkpoint's epoch count. " + "To use checkpoint for inference, no need to load state_dict for the engine." + ) + engine.state.max_epochs = prior_max_epochs + + self.logger.info(f"Restored all variables from {self.load_path}") diff --git a/source_code/SegMamba/monai/handlers/checkpoint_saver.py b/source_code/SegMamba/monai/handlers/checkpoint_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..0651c6ff3342da1be8ac6d0c23c0ba2e44eff49d --- /dev/null +++ b/source_code/SegMamba/monai/handlers/checkpoint_saver.py @@ -0,0 +1,334 @@ +# 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 +import warnings +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from monai.config import IgniteInfo +from monai.utils import is_scalar, min_version, optional_import + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") + +if TYPE_CHECKING: + from ignite.engine import Engine + from ignite.handlers import Checkpoint, DiskSaver +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + DiskSaver, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "DiskSaver") + Checkpoint, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Checkpoint") + + +class CheckpointSaver: + """ + CheckpointSaver acts as an Ignite handler to save checkpoint data into files. + It supports to save according to metrics result, epoch number, iteration number + and last model or exception. + + Args: + save_dir: the target directory to save the checkpoints. + save_dict: source objects that save to the checkpoint. examples:: + + {'network': net, 'optimizer': optimizer, 'lr_scheduler': lr_scheduler} + + name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``. + file_prefix: prefix for the filenames to which objects will be saved. + save_final: whether to save checkpoint or session at final iteration or exception. + If checkpoints are to be saved when an exception is raised, put this handler before + `StatsHandler` in the handler list, because the logic with Ignite can only trigger + the first attached handler for `EXCEPTION_RAISED` event. + final_filename: set a fixed filename to save the final model if `save_final=True`. + If None, default to `checkpoint_final_iteration=N.pt`. + save_key_metric: whether to save checkpoint or session when the value of key_metric is + higher than all the previous values during training.keep 4 decimal places of metric, + checkpoint name is: {file_prefix}_key_metric=0.XXXX.pth. + key_metric_name: the name of key_metric in ignite metrics dictionary. + If None, use `engine.state.key_metric` instead. + key_metric_n_saved: save top N checkpoints or sessions, sorted by the value of key + metric in descending order. + key_metric_filename: set a fixed filename to set the best metric model, if not None, + `key_metric_n_saved` should be 1 and only keep the best metric model. + key_metric_save_state: whether to save the tracking list of key metric in the checkpoint file. + if `True`, then will save an object in the checkpoint file with key `checkpointer` to be + consistent with the `include_self` arg of `Checkpoint` in ignite: + https://pytorch.org/ignite/v0.4.5/generated/ignite.handlers.checkpoint.Checkpoint.html. + typically, it's used to resume training and compare current metric with previous N values. + key_metric_greater_or_equal: if `True`, the latest equally scored model is stored. Otherwise, + save the first equally scored model. default to `False`. + key_metric_negative_sign: whether adding a negative sign to the metric score to compare metrics, + because for error-like metrics, smaller is better(objects with larger score are retained). + default to `False`. + epoch_level: save checkpoint during training for every N epochs or every N iterations. + `True` is epoch level, `False` is iteration level. + save_interval: save checkpoint every N epochs, default is 0 to save no checkpoint. + n_saved: save latest N checkpoints of epoch level or iteration level, 'None' is to save all. + + Note: + CheckpointHandler can be used during training, validation or evaluation. + example of saved files: + + - checkpoint_iteration=400.pt + - checkpoint_iteration=800.pt + - checkpoint_epoch=1.pt + - checkpoint_final_iteration=1000.pt + - checkpoint_key_metric=0.9387.pt + + """ + + def __init__( + self, + save_dir: str, + save_dict: dict, + name: str | None = None, + file_prefix: str = "", + save_final: bool = False, + final_filename: str | None = None, + save_key_metric: bool = False, + key_metric_name: str | None = None, + key_metric_n_saved: int = 1, + key_metric_filename: str | None = None, + key_metric_save_state: bool = False, + key_metric_greater_or_equal: bool = False, + key_metric_negative_sign: bool = False, + epoch_level: bool = True, + save_interval: int = 0, + n_saved: int | None = None, + ) -> None: + if save_dir is None: + raise AssertionError("must provide directory to save the checkpoints.") + self.save_dir = save_dir + if not (save_dict is not None and len(save_dict) > 0): + raise AssertionError("must provide source objects to save.") + self.save_dict = save_dict + self.logger = logging.getLogger(name) + self.epoch_level = epoch_level + self.save_interval = save_interval + self._final_checkpoint: Checkpoint | None = None + self._key_metric_checkpoint: Checkpoint | None = None + self._interval_checkpoint: Checkpoint | None = None + self._name = name + self._final_filename = final_filename + + class _DiskSaver(DiskSaver): + """ + Enhance the DiskSaver to support fixed filename. + + """ + + def __init__(self, dirname: str, filename: str | None = None): + # set `atomic=False` as `atomic=True` only gives read/write permission to the user who saved the file, + # without group/others read permission + super().__init__(dirname=dirname, require_empty=False, atomic=False) + self.filename = filename + + def __call__(self, checkpoint: Mapping, filename: str, metadata: Mapping | None = None) -> None: + if self.filename is not None: + filename = self.filename + super().__call__(checkpoint=checkpoint, filename=filename, metadata=metadata) + + def remove(self, filename: str) -> None: + if self.filename is not None: + filename = self.filename + super().remove(filename=filename) + + if save_final: + + def _final_func(engine: Engine) -> Any: + return engine.state.iteration + + self._final_checkpoint = Checkpoint( + to_save=self.save_dict, + save_handler=_DiskSaver(dirname=self.save_dir, filename=self._final_filename), + filename_prefix=file_prefix, + score_function=_final_func, + score_name="final_iteration", + ) + + if save_key_metric: + + def _score_func(engine: Engine) -> Any: + if isinstance(key_metric_name, str): + metric_name = key_metric_name + elif hasattr(engine.state, "key_metric_name"): + metric_name = engine.state.key_metric_name + else: + raise ValueError( + f"Incompatible values: save_key_metric=True and key_metric_name={key_metric_name}." + ) + metric = engine.state.metrics[metric_name] + if not is_scalar(metric): + warnings.warn( + "key metric is not a scalar value, skip metric comparison and don't save a model." + "please use other metrics as key metric, or change the `reduction` mode to 'mean'." + f"got metric: {metric_name}={metric}." + ) + return -1 + return (-1 if key_metric_negative_sign else 1) * metric + + if key_metric_filename is not None and key_metric_n_saved > 1: + raise ValueError("if using fixed filename to save the best metric model, we should only save 1 model.") + + self._key_metric_checkpoint = Checkpoint( + to_save=self.save_dict, + save_handler=_DiskSaver(dirname=self.save_dir, filename=key_metric_filename), + filename_prefix=file_prefix, + score_function=_score_func, + score_name="key_metric", + n_saved=key_metric_n_saved, + include_self=key_metric_save_state, + greater_or_equal=key_metric_greater_or_equal, + ) + + if save_interval > 0: + + def _interval_func(engine: Engine) -> Any: + return engine.state.epoch if self.epoch_level else engine.state.iteration + + self._interval_checkpoint = Checkpoint( + to_save=self.save_dict, + save_handler=_DiskSaver(dirname=self.save_dir), + filename_prefix=file_prefix, + score_function=_interval_func, + score_name="epoch" if self.epoch_level else "iteration", + n_saved=n_saved, + ) + + def load_state_dict(self, state_dict: dict) -> None: + """ + Utility to resume the internal state of key metric tracking list if configured to save + checkpoints based on the key metric value. + Note to set `key_metric_save_state=True` when saving the previous checkpoint. + + Example:: + + CheckpointSaver( + ... + save_key_metric=True, + key_metric_save_state=True, # config to also save the state of this saver + ).attach(engine) + engine.run(...) + + # resumed training with a new CheckpointSaver + saver = CheckpointSaver(save_key_metric=True, ...) + # load the previous key metric tracking list into saver + CheckpointLoader("/test/model.pt"), {"checkpointer": saver}).attach(engine) + + """ + if self._key_metric_checkpoint is not None: + self._key_metric_checkpoint.load_state_dict(state_dict) + else: + warnings.warn("no key metric checkpoint saver to resume the key metric tracking list.") + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + if self._final_checkpoint is not None: + engine.add_event_handler(Events.COMPLETED, self.completed) + engine.add_event_handler(Events.EXCEPTION_RAISED, self.exception_raised) + if self._key_metric_checkpoint is not None: + engine.add_event_handler(Events.EPOCH_COMPLETED, self.metrics_completed) + if self._interval_checkpoint is not None: + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.save_interval), self.interval_completed) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.save_interval), self.interval_completed) + + def _delete_previous_final_ckpt(self): + if self._final_checkpoint is not None: + saved = self._final_checkpoint._saved + if len(saved) > 0: + item = saved.pop(0) + self._final_checkpoint.save_handler.remove(item.filename) + self.logger.info(f"Deleted previous saved final checkpoint: {item.filename}") + + def completed(self, engine: Engine) -> None: + """Callback for train or validation/evaluation completed Event. + Save final checkpoint if configure save_final is True. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if not callable(self._final_checkpoint): + raise AssertionError("Error: _final_checkpoint function not specified.") + # delete previous saved final checkpoint if existing + self._delete_previous_final_ckpt() + self._final_checkpoint(engine) + if self.logger is None: + raise AssertionError + if not hasattr(self.logger, "info"): + raise AssertionError("Error, provided logger has not info attribute.") + if self._final_filename is not None: + _final_checkpoint_path = os.path.join(self.save_dir, self._final_filename) + else: + _final_checkpoint_path = self._final_checkpoint.last_checkpoint # type: ignore[assignment] + self.logger.info(f"Train completed, saved final checkpoint: {_final_checkpoint_path}") + + def exception_raised(self, engine: Engine, e: Exception) -> None: + """Callback for train or validation/evaluation exception raised Event. + Save current data as final checkpoint if configure save_final is True. This callback may be skipped + because the logic with Ignite can only trigger the first attached handler for `EXCEPTION_RAISED` event. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + e: the exception caught in Ignite during engine.run(). + """ + if not callable(self._final_checkpoint): + raise AssertionError("Error: _final_checkpoint function not specified.") + # delete previous saved final checkpoint if existing + self._delete_previous_final_ckpt() + self._final_checkpoint(engine) + if self.logger is None: + raise AssertionError + if not hasattr(self.logger, "info"): + raise AssertionError("Error, provided logger has not info attribute.") + if self._final_filename is not None: + _final_checkpoint_path = os.path.join(self.save_dir, self._final_filename) + else: + _final_checkpoint_path = self._final_checkpoint.last_checkpoint # type: ignore[assignment] + self.logger.info(f"Exception raised, saved the last checkpoint: {_final_checkpoint_path}") + raise e + + def metrics_completed(self, engine: Engine) -> None: + """Callback to compare metrics and save models in train or validation when epoch completed. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if not callable(self._key_metric_checkpoint): + raise AssertionError("Error: _key_metric_checkpoint function not specified.") + self._key_metric_checkpoint(engine) + + def interval_completed(self, engine: Engine) -> None: + """Callback for train epoch/iteration completed Event. + Save checkpoint if configure save_interval = N + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if not callable(self._interval_checkpoint): + raise AssertionError("Error: _interval_checkpoint function not specified.") + self._interval_checkpoint(engine) + if self.logger is None: + raise AssertionError + if not hasattr(self.logger, "info"): + raise AssertionError("Error, provided logger has not info attribute.") + if self.epoch_level: + self.logger.info(f"Saved checkpoint at epoch: {engine.state.epoch}") + else: + self.logger.info(f"Saved checkpoint at iteration: {engine.state.iteration}") diff --git a/source_code/SegMamba/monai/handlers/classification_saver.py b/source_code/SegMamba/monai/handlers/classification_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..831808f4fb3c7788f33cc2c40656fbef933fb80e --- /dev/null +++ b/source_code/SegMamba/monai/handlers/classification_saver.py @@ -0,0 +1,167 @@ +# 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 warnings +from collections.abc import Callable +from typing import TYPE_CHECKING + +import torch + +from monai.config import IgniteInfo +from monai.data import CSVSaver, decollate_batch +from monai.utils import ImageMetaKey as Key +from monai.utils import evenly_divisible_all_gather, min_version, optional_import, string_list_all_gather + +idist, _ = optional_import("ignite", IgniteInfo.OPT_IMPORT_VERSION, min_version, "distributed") +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + + +class ClassificationSaver: + """ + Event handler triggered on completing every iteration to save the classification predictions as CSV file. + If running in distributed data parallel, only saves CSV file in the specified rank. + + """ + + def __init__( + self, + output_dir: str = "./", + filename: str = "predictions.csv", + delimiter: str = ",", + overwrite: bool = True, + batch_transform: Callable = lambda x: x, + output_transform: Callable = lambda x: x, + name: str | None = None, + save_rank: int = 0, + saver: CSVSaver | None = None, + ) -> None: + """ + Args: + output_dir: if `saver=None`, output CSV file directory. + filename: if `saver=None`, name of the saved CSV file name. + delimiter: the delimiter character in the saved file, default to "," as the default output type is `csv`. + to be consistent with: https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter. + overwrite: if `saver=None`, whether to overwriting existing file content, if True, + will clear the file before saving. otherwise, will append new content to the file. + batch_transform: a callable that is used to extract the `meta_data` dictionary of + the input images from `ignite.engine.state.batch`. the purpose is to get the input + filenames from the `meta_data` and store with classification results together. + `engine.state` and `batch_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + output_transform: a callable that is used to extract the model prediction data from + `ignite.engine.state.output`. the first dimension of its output will be treated as + the batch dimension. each item in the batch will be saved individually. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + name: identifier of logging.logger to use, defaulting to `engine.logger`. + save_rank: only the handler on specified rank will save to CSV file in multi-gpus validation, + default to 0. + saver: the saver instance to save classification results, if None, create a CSVSaver internally. + the saver must provide `save_batch(batch_data, meta_data)` and `finalize()` APIs. + + """ + self.save_rank = save_rank + self.output_dir = output_dir + self.filename = filename + self.delimiter = delimiter + self.overwrite = overwrite + self.batch_transform = batch_transform + self.output_transform = output_transform + self.saver = saver + + self.logger = logging.getLogger(name) + self._name = name + self._outputs: list[torch.Tensor] = [] + self._filenames: list[str] = [] + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + if not engine.has_event_handler(self._started, Events.EPOCH_STARTED): + engine.add_event_handler(Events.EPOCH_STARTED, self._started) + if not engine.has_event_handler(self, Events.ITERATION_COMPLETED): + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + if not engine.has_event_handler(self._finalize, Events.EPOCH_COMPLETED): + engine.add_event_handler(Events.EPOCH_COMPLETED, self._finalize) + + def _started(self, _engine: Engine) -> None: + """ + Initialize internal buffers. + + Args: + _engine: Ignite Engine, unused argument. + + """ + self._outputs = [] + self._filenames = [] + + def __call__(self, engine: Engine) -> None: + """ + This method assumes self.batch_transform will extract metadata from the input batch. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + meta_data = self.batch_transform(engine.state.batch) + if isinstance(meta_data, dict): + # decollate the `dictionary of list` to `list of dictionaries` + meta_data = decollate_batch(meta_data) + engine_output = self.output_transform(engine.state.output) + for m, o in zip(meta_data, engine_output): + self._filenames.append(f"{m.get(Key.FILENAME_OR_OBJ)}") + if isinstance(o, torch.Tensor): + o = o.detach() + self._outputs.append(o) + + def _finalize(self, _engine: Engine) -> None: + """ + All gather classification results from ranks and save to CSV file. + + Args: + _engine: Ignite Engine, unused argument. + """ + ws = idist.get_world_size() + if self.save_rank >= ws: + raise ValueError("target save rank is greater than the distributed group size.") + + outputs = torch.stack(self._outputs, dim=0) + filenames = self._filenames + if ws > 1: + outputs = evenly_divisible_all_gather(outputs, concat=True) + filenames = string_list_all_gather(filenames) + + if len(filenames) == 0: + meta_dict = None + else: + if len(filenames) != len(outputs): + warnings.warn(f"filenames length: {len(filenames)} doesn't match outputs length: {len(outputs)}.") + meta_dict = {Key.FILENAME_OR_OBJ: filenames} + + # save to CSV file only in the expected rank + if idist.get_rank() == self.save_rank: + saver = self.saver or CSVSaver( + output_dir=self.output_dir, filename=self.filename, overwrite=self.overwrite, delimiter=self.delimiter + ) + saver.save_batch(outputs, meta_dict) + saver.finalize() diff --git a/source_code/SegMamba/monai/handlers/confusion_matrix.py b/source_code/SegMamba/monai/handlers/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..89c0f5551f47904c5d1e75d6a107f3d4ad1cc373 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/confusion_matrix.py @@ -0,0 +1,71 @@ +# 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 + +from monai.handlers.ignite_metric import IgniteMetricHandler +from monai.metrics import ConfusionMatrixMetric +from monai.utils.enums import MetricReduction + + +class ConfusionMatrix(IgniteMetricHandler): + """ + Compute confusion matrix related metrics from full size Tensor and collects average over batch, class-channels, iterations. + """ + + def __init__( + self, + include_background: bool = True, + metric_name: str = "hit_rate", + compute_sample: bool = False, + reduction: MetricReduction | str = MetricReduction.MEAN, + output_transform: Callable = lambda x: x, + save_details: bool = True, + ) -> None: + """ + + Args: + include_background: whether to include metric computation on the first channel of + the predicted output. Defaults to True. + metric_name: [``"sensitivity"``, ``"specificity"``, ``"precision"``, ``"negative predictive value"``, + ``"miss rate"``, ``"fall out"``, ``"false discovery rate"``, ``"false omission rate"``, + ``"prevalence threshold"``, ``"threat score"``, ``"accuracy"``, ``"balanced accuracy"``, + ``"f1 score"``, ``"matthews correlation coefficient"``, ``"fowlkes mallows index"``, + ``"informedness"``, ``"markedness"``] + Some of the metrics have multiple aliases (as shown in the wikipedia page aforementioned), + and you can also input those names instead. + compute_sample: when reducing, if ``True``, each sample's metric will be computed based on each confusion matrix first. + if ``False``, compute reduction on the confusion matrices first, defaults to ``False``. + reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + output_transform: callable to extract `y_pred` and `y` from `ignite.engine.state.output` then + construct `(y_pred, y)` pair, where `y_pred` and `y` can be `batch-first` Tensors or + lists of `channel-first` Tensors. the form of `(y_pred, y)` is required by the `update()`. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + save_details: whether to save metric computation details per image, for example: TP/TN/FP/FN of every image. + default to True, will save to `engine.state.metric_details` dict with the metric name as key. + + See also: + :py:meth:`monai.metrics.confusion_matrix` + """ + metric_fn = ConfusionMatrixMetric( + include_background=include_background, + metric_name=metric_name, + compute_sample=compute_sample, + reduction=reduction, + ) + self.metric_name = metric_name + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/source_code/SegMamba/monai/handlers/decollate_batch.py b/source_code/SegMamba/monai/handlers/decollate_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3aa94145d1890ffff1ebcbdefd79ff1d709c50 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/decollate_batch.py @@ -0,0 +1,96 @@ +# 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 typing import TYPE_CHECKING + +from monai.config import IgniteInfo, KeysCollection +from monai.engines.utils import IterationEvents +from monai.transforms import Decollated +from monai.utils import min_version, optional_import + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + + +class DecollateBatch: + """ + Ignite handler to execute the `decollate batch` logic for `engine.state.batch` and `engine.state.output`. + Typical usage is to set `decollate=False` in the engine and execute some postprocessing logic first + then decollate the batch, otherwise, engine will decollate batch before the postprocessing. + + Args: + event: expected EVENT to attach the handler, should be "MODEL_COMPLETED" or "ITERATION_COMPLETED". + default to "MODEL_COMPLETED". + detach: whether to detach the tensors. scalars tensors will be detached into number types + instead of torch tensors. + decollate_batch: whether to decollate `engine.state.batch` of ignite engine. + batch_keys: if `decollate_batch=True`, specify the keys of the corresponding items to decollate + in `engine.state.batch`, note that it will delete other keys not specified. if None, + will decollate all the keys. it replicates the scalar values to every item of the decollated list. + decollate_output: whether to decollate `engine.state.output` of ignite engine. + output_keys: if `decollate_output=True`, specify the keys of the corresponding items to decollate + in `engine.state.output`, note that it will delete other keys not specified. if None, + will decollate all the keys. it replicates the scalar values to every item of the decollated list. + allow_missing_keys: don't raise exception if key is missing. + + """ + + def __init__( + self, + event: str = "MODEL_COMPLETED", + detach: bool = True, + decollate_batch: bool = True, + batch_keys: KeysCollection | None = None, + decollate_output: bool = True, + output_keys: KeysCollection | None = None, + allow_missing_keys: bool = False, + ): + event = event.upper() + if event not in ("MODEL_COMPLETED", "ITERATION_COMPLETED"): + raise ValueError("event should be `MODEL_COMPLETED` or `ITERATION_COMPLETED`.") + self.event = event + + self.batch_transform = ( + Decollated(keys=batch_keys, detach=detach, allow_missing_keys=allow_missing_keys) + if decollate_batch + else None + ) + + self.output_transform = ( + Decollated(keys=output_keys, detach=detach, allow_missing_keys=allow_missing_keys) + if decollate_output + else None + ) + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self.event == "MODEL_COMPLETED": + engine.add_event_handler(IterationEvents.MODEL_COMPLETED, self) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self.batch_transform is not None and isinstance(engine.state.batch, (list, dict)): + engine.state.batch = self.batch_transform(engine.state.batch) + if self.output_transform is not None and isinstance(engine.state.output, (list, dict)): + engine.state.output = self.output_transform(engine.state.output) diff --git a/source_code/SegMamba/monai/handlers/earlystop_handler.py b/source_code/SegMamba/monai/handlers/earlystop_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..93334bf5c07481e74054fd55f8ec612950c95ef8 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/earlystop_handler.py @@ -0,0 +1,124 @@ +# 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 +from typing import TYPE_CHECKING + +from monai.config import IgniteInfo +from monai.utils import min_version, optional_import + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +EarlyStopping, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EarlyStopping") + +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine", as_type="decorator" + ) + + +class EarlyStopHandler: + """ + EarlyStopHandler acts as an Ignite handler to stop training if no improvement after a given number of events. + It‘s based on the `EarlyStopping` handler in ignite. + + Args: + patience: number of events to wait if no improvement and then stop the training. + score_function: It should be a function taking a single argument, an :class:`~ignite.engine.engine.Engine` + object that the handler attached, can be a trainer or validator, and return a score `float`. + an improvement is considered if the score is higher. + trainer: trainer engine to stop the run if no improvement, if None, must call `set_trainer()` before training. + min_delta: a minimum increase in the score to qualify as an improvement, + i.e. an increase of less than or equal to `min_delta`, will count as no improvement. + cumulative_delta: if True, `min_delta` defines an increase since the last `patience` reset, otherwise, + it defines an increase after the last event, default to False. + epoch_level: check early stopping for every epoch or every iteration of the attached engine, + `True` is epoch level, `False` is iteration level, default to epoch level. + + Note: + If in distributed training and uses loss value of every iteration to detect early stopping, + the values may be different in different ranks. When using this handler with distributed training, + please also note that to prevent "dist.destroy_process_group()" hangs, you can use an "all_reduce" operation + to synchronize the stop signal across all ranks. The mechanism can be implemented in the `score_function`. The following + is an example: + + .. code-block:: python + + import os + + import torch + import torch.distributed as dist + + + def score_function(engine): + val_metric = engine.state.metrics["val_mean_dice"] + if dist.is_initialized(): + device = torch.device("cuda:" + os.environ["LOCAL_RANK"]) + val_metric = torch.tensor([val_metric]).to(device) + dist.all_reduce(val_metric, op=dist.ReduceOp.SUM) + val_metric /= dist.get_world_size() + return val_metric.item() + return val_metric + + + User may attach this handler to validator engine to detect validation metrics and stop the training, + in this case, the `score_function` is executed on validator engine and `trainer` is the trainer engine. + + """ + + def __init__( + self, + patience: int, + score_function: Callable, + trainer: Engine | None = None, + min_delta: float = 0.0, + cumulative_delta: bool = False, + epoch_level: bool = True, + ) -> None: + self.patience = patience + self.score_function = score_function + self.min_delta = min_delta + self.cumulative_delta = cumulative_delta + self.epoch_level = epoch_level + self._handler = None + + if trainer is not None: + self.set_trainer(trainer=trainer) + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED, self) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + + def set_trainer(self, trainer: Engine) -> None: + """ + Set trainer to execute early stop if not setting properly in `__init__()`. + """ + self._handler = EarlyStopping( + patience=self.patience, + score_function=self.score_function, + trainer=trainer, + min_delta=self.min_delta, + cumulative_delta=self.cumulative_delta, + ) + + def __call__(self, engine: Engine) -> None: + if self._handler is None: + raise RuntimeError("please set trainer in __init__() or call set_trainer() before training.") + self._handler(engine) diff --git a/source_code/SegMamba/monai/handlers/garbage_collector.py b/source_code/SegMamba/monai/handlers/garbage_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7e9483645d75bc51ae5c8291a79c31f09cefec --- /dev/null +++ b/source_code/SegMamba/monai/handlers/garbage_collector.py @@ -0,0 +1,88 @@ +# 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 gc +from typing import TYPE_CHECKING + +from monai.config import IgniteInfo +from monai.utils import min_version, optional_import + +if TYPE_CHECKING: + from ignite.engine import Engine, Events + from ignite.engine.events import CallableEventWithFilter +else: + CallableEventWithFilter, _ = optional_import( + "ignite.engine.events", IgniteInfo.OPT_IMPORT_VERSION, min_version, "CallableEventWithFilter" + ) + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") + + +class GarbageCollector: + """ + Run garbage collector after each epoch + + Args: + trigger_event: the event that trigger a call to this handler. + - "epoch", after completion of each epoch (equivalent of ignite.engine.Events.EPOCH_COMPLETED) + - "iteration", after completion of each iteration (equivalent of ignite.engine.Events.ITERATION_COMPLETED) + - any ignite built-in event from ignite.engine.Events. + Defaults to "epoch". + log_level: log level (integer) for some garbage collection information as below. Defaults to 10 (DEBUG). + - 50 (CRITICAL) + - 40 (ERROR) + - 30 (WARNING) + - 20 (INFO) + - 10 (DEBUG) + - 0 (NOTSET) + """ + + def __init__(self, trigger_event: str | Events | CallableEventWithFilter = "epoch", log_level: int = 10): + self.trigger_event: Events | CallableEventWithFilter + if isinstance(trigger_event, (Events, CallableEventWithFilter)): + self.trigger_event = trigger_event + elif trigger_event.lower() == "epoch": + self.trigger_event = Events.EPOCH_COMPLETED + elif trigger_event.lower() == "iteration": + self.trigger_event = Events.ITERATION_COMPLETED + else: + raise ValueError( + f"'trigger_event' should be either epoch, iteration, or an ignite built-in event from" + f" ignite.engine.Events, '{trigger_event}' was given." + ) + + self.log_level = log_level + + def attach(self, engine: Engine) -> None: + if not engine.has_event_handler(self, self.trigger_event): + engine.add_event_handler(self.trigger_event, self) + + def __call__(self, engine: Engine) -> None: + """ + This method calls python garbage collector. + + Args: + engine: Ignite Engine, it should be either a trainer or validator. + """ + # get count before garbage collection + pre_count = gc.get_count() + # first call to garbage collector + gc.collect() + # second call to garbage collector + unreachable = gc.collect() + # get count after garbage collection + after_count = gc.get_count() + engine.logger.log( + self.log_level, + f"Garbage Count: [before: {pre_count}] -> [after: {after_count}] (unreachable : {unreachable})", + ) diff --git a/source_code/SegMamba/monai/handlers/ignite_metric.py b/source_code/SegMamba/monai/handlers/ignite_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..021154d7059578636aac439f0962c51f4b4715aa --- /dev/null +++ b/source_code/SegMamba/monai/handlers/ignite_metric.py @@ -0,0 +1,177 @@ +# 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 collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any, cast + +import torch +from torch.nn.modules.loss import _Loss + +from monai.config import IgniteInfo +from monai.metrics import CumulativeIterationMetric, LossMetric +from monai.utils import MetricReduction, deprecated, min_version, optional_import + +idist, _ = optional_import("ignite", IgniteInfo.OPT_IMPORT_VERSION, min_version, "distributed") + +if TYPE_CHECKING: + try: + _, has_ignite = optional_import("ignite") + from ignite.engine import Engine + from ignite.metrics import Metric + from ignite.metrics.metric import reinit__is_reduced + except ImportError: + has_ignite = False + +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric", as_type="base") + reinit__is_reduced, _ = optional_import( + "ignite.metrics.metric", IgniteInfo.OPT_IMPORT_VERSION, min_version, "reinit__is_reduced", as_type="decorator" + ) + + +class IgniteMetricHandler(Metric): + """ + Base Metric class based on ignite event handler mechanism. + The input `prediction` or `label` data can be a PyTorch Tensor or numpy array with batch dim and channel dim, + or a list of PyTorch Tensor or numpy array without batch dim. + + Args: + metric_fn: callable function or class to compute raw metric results after every iteration. + expect to return a Tensor with shape (batch, channel, ...) or tuple (Tensor, not_nans). + loss_fn: A torch _Loss function which is used to generate the LossMetric + output_transform: callable to extract `y_pred` and `y` from `ignite.engine.state.output` then + construct `(y_pred, y)` pair, where `y_pred` and `y` can be `batch-first` Tensors or + lists of `channel-first` Tensors. the form of `(y_pred, y)` is required by the `update()`. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + save_details: whether to save metric computation details per image, for example: mean_dice of every image. + default to True, will save to `engine.state.metric_details` dict with the metric name as key. + reduction: Argument for the LossMetric, look there for details + get_not_nans: Argument for the LossMetric, look there for details + + """ + + def __init__( + self, + metric_fn: CumulativeIterationMetric | None = None, + loss_fn: _Loss | None = None, + output_transform: Callable = lambda x: x, + save_details: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + ) -> None: + self._is_reduced: bool = False + self.metric_fn: CumulativeIterationMetric = cast(CumulativeIterationMetric, metric_fn) + self.loss_fn = loss_fn + self.save_details = save_details + self._scores: list = [] + self._engine: Engine | None = None + self._name: str | None = None + + if self.metric_fn is None and self.loss_fn is None: + raise ValueError("Either metric_fn or loss_fn have to be passed.") + if self.metric_fn is not None and self.loss_fn is not None: + raise ValueError("Either metric_fn or loss_fn have to be passed, but not both.") + if self.loss_fn: + self.metric_fn = LossMetric(loss_fn=self.loss_fn, reduction=reduction, get_not_nans=get_not_nans) + + super().__init__(output_transform) + + @reinit__is_reduced + def reset(self) -> None: + self.metric_fn.reset() + + @reinit__is_reduced + def update(self, output: Sequence[torch.Tensor]) -> None: + """ + Args: + output: sequence with contents [y_pred, y]. + + Raises: + ValueError: When ``output`` length is not 2. metric_fn can only support y_pred and y. + + """ + if len(output) != 2: + raise ValueError(f"output must have length 2, got {len(output)}.") + + y_pred, y = output + + self.metric_fn(y_pred, y) + + def compute(self) -> Any: + """ + Raises: + NotComputableError: When ``compute`` is called before an ``update`` occurs. + + """ + result = self.metric_fn.aggregate() + if isinstance(result, (tuple, list)): + if len(result) > 1: + warnings.warn("metric handler can only record the first value of result list.") + result = result[0] + + self._is_reduced = True + + # save score of every image into engine.state for other components + if self.save_details: + if self._engine is None or self._name is None: + raise RuntimeError("please call the attach() function to connect expected engine first.") + self._engine.state.metric_details[self._name] = self.metric_fn.get_buffer() # type: ignore + + if isinstance(result, torch.Tensor): + result = result.squeeze() + if result.ndim == 0: + result = result.item() + return result + + def attach(self, engine: Engine, name: str) -> None: # type: ignore[override] + """ + Attaches current metric to provided engine. On the end of engine's run, + `engine.state.metrics` dictionary will contain computed metric's value under provided name. + + Args: + engine: the engine to which the metric must be attached. + name: the name of the metric to attach. + + """ + super().attach(engine=engine, name=name) + # FIXME: record engine for communication, ignite will support it in the future version soon + self._engine = engine + self._name = name + if self.save_details and not hasattr(engine.state, "metric_details"): + engine.state.metric_details = {} # type: ignore + + +@deprecated(since="1.2", removed="1.4", msg_suffix="Use IgniteMetricHandler instead of IgniteMetric.") +class IgniteMetric(IgniteMetricHandler): + + def __init__( + self, + metric_fn: CumulativeIterationMetric | None = None, + loss_fn: _Loss | None = None, + output_transform: Callable = lambda x: x, + save_details: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + ) -> None: + super().__init__( + metric_fn=metric_fn, + loss_fn=loss_fn, + output_transform=output_transform, + save_details=save_details, + reduction=reduction, + get_not_nans=get_not_nans, + ) diff --git a/source_code/SegMamba/monai/handlers/logfile_handler.py b/source_code/SegMamba/monai/handlers/logfile_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..df6ebd34a7b0dd88e939c61edfbdb9c1c05dbeab --- /dev/null +++ b/source_code/SegMamba/monai/handlers/logfile_handler.py @@ -0,0 +1,91 @@ +# 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 typing import TYPE_CHECKING + +from monai.config import IgniteInfo +from monai.utils import min_version, optional_import + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + +__all__ = ["LogfileHandler"] + + +class LogfileHandler: + """ + Adds a `logging.FileHandler` to the attached engine's logger when the start event occurs and removes it again when + then completed event occurs. + + A handler is needed to remove `FileHandler` object when the complete event occurs so that further runs of different + engines write only to the log files they should, rather than previous files. Multiple handlers can write to the same + file which allows output from train and evaluation engine objects to be condensed in one file. If the given output + directory doesn't exist it will by default be created when the start event occurs. This can be used in conjunction + with `CheckpointSaver` to save a log file to the same destination as the saved checkpoints. Since the handler is + added possibly after other logging events during initialisation, not all logging data will be retained. + + Args: + output_dir: directory to save the log file to + filename: name of the file to save log to + loglevel: log level for the handler + formatter: format string for the `logging.Formatter` set for the handler + create_dir: if True, create `output_dir` if it doesn't exist + """ + + def __init__( + self, + output_dir: str, + filename: str = "log.txt", + loglevel: int = logging.INFO, + formatter: str = "%(asctime)s %(name)s %(levelname)s: %(message)s", + create_dir: bool = True, + ): + self.output_dir: str = output_dir + self.filename: str = filename + self.loglevel: int = loglevel + self.formatter: str = formatter + self.create_dir: bool = create_dir + self.logger: logging.Logger | None = None + self.handler: logging.FileHandler | None = None + + def attach(self, engine: Engine) -> None: + self.logger = engine.logger + engine.add_event_handler(Events.STARTED, self._start) + engine.add_event_handler(Events.COMPLETED, self._completed) + + def _start(self, engine: Engine) -> None: + if self.create_dir and not os.path.exists(self.output_dir): + os.makedirs(self.output_dir, exist_ok=True) + + self.handler = logging.FileHandler(os.path.join(self.output_dir, self.filename)) + self.handler.setLevel(self.loglevel) + self.handler.setFormatter(logging.Formatter(self.formatter)) + + if self.logger is not None: + self.logger.addHandler(self.handler) + else: + raise AttributeError("`self.logger` must not be None in start event") + + def _completed(self, engine: Engine) -> None: + if self.logger is not None and self.handler is not None: + self.logger.removeHandler(self.handler) + self.handler.close() + else: + raise AttributeError("`self.logger` and `self.handler` must not be None in complete event") + + self.handler = None diff --git a/source_code/SegMamba/monai/handlers/lr_schedule_handler.py b/source_code/SegMamba/monai/handlers/lr_schedule_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..a79722517de8a9473cb45d38191ab9cf2d3a0157 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/lr_schedule_handler.py @@ -0,0 +1,90 @@ +# 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 +from collections.abc import Callable +from typing import TYPE_CHECKING, Any + +from torch.optim.lr_scheduler import ReduceLROnPlateau, _LRScheduler + +from monai.config import IgniteInfo +from monai.utils import ensure_tuple, min_version, optional_import + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine", as_type="decorator" + ) + + +class LrScheduleHandler: + """ + Ignite handler to update the Learning Rate based on PyTorch LR scheduler. + """ + + def __init__( + self, + lr_scheduler: _LRScheduler | ReduceLROnPlateau, + print_lr: bool = True, + name: str | None = None, + epoch_level: bool = True, + step_transform: Callable[[Engine], Any] = lambda engine: (), + ) -> None: + """ + Args: + lr_scheduler: typically, lr_scheduler should be PyTorch + lr_scheduler object. If customized version, must have `step` and `get_last_lr` methods. + print_lr: whether to print out the latest learning rate with logging. + name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``. + epoch_level: execute lr_scheduler.step() after every epoch or every iteration. + `True` is epoch level, `False` is iteration level. + step_transform: a callable that is used to transform the information from `engine` + to expected input data of lr_scheduler.step() function if necessary. + + Raises: + TypeError: When ``step_transform`` is not ``callable``. + + """ + self.lr_scheduler = lr_scheduler + self.print_lr = print_lr + self.logger = logging.getLogger(name) + self.epoch_level = epoch_level + if not callable(step_transform): + raise TypeError(f"step_transform must be callable but is {type(step_transform).__name__}.") + self.step_transform = step_transform + + self._name = name + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self._name is None: + self.logger = engine.logger + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED, self) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED, self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + args = ensure_tuple(self.step_transform(engine)) + self.lr_scheduler.step(*args) + if self.print_lr: + self.logger.info(f"Current learning rate: {self.lr_scheduler._last_lr[0]}") # type: ignore[union-attr] diff --git a/source_code/SegMamba/monai/handlers/mean_dice.py b/source_code/SegMamba/monai/handlers/mean_dice.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7793da68820aee924da1629c6a56d3673b6a2b --- /dev/null +++ b/source_code/SegMamba/monai/handlers/mean_dice.py @@ -0,0 +1,68 @@ +# 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 + +from monai.handlers.ignite_metric import IgniteMetricHandler +from monai.metrics import DiceMetric +from monai.utils import MetricReduction + + +class MeanDice(IgniteMetricHandler): + """ + Computes Dice score metric from full size Tensor and collects average over batch, class-channels, iterations. + """ + + def __init__( + self, + include_background: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + num_classes: int | None = None, + output_transform: Callable = lambda x: x, + save_details: bool = True, + return_with_label: bool | list[str] = False, + ) -> None: + """ + + Args: + include_background: whether to include dice computation on the first channel of the predicted output. + Defaults to True. + reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + num_classes: number of input channels (always including the background). When this is None, + ``y_pred.shape[1]`` will be used. This option is useful when both ``y_pred`` and ``y`` are + single-channel class indices and the number of classes is not automatically inferred from data. + output_transform: callable to extract `y_pred` and `y` from `ignite.engine.state.output` then + construct `(y_pred, y)` pair, where `y_pred` and `y` can be `batch-first` Tensors or + lists of `channel-first` Tensors. the form of `(y_pred, y)` is required by the `update()`. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + save_details: whether to save metric computation details per image, for example: mean dice of every image. + default to True, will save to `engine.state.metric_details` dict with the metric name as key. + return_with_label: whether to return the metrics with label, only works when reduction is "mean_batch". + If `True`, use "label_{index}" as the key corresponding to C channels; if 'include_background' is True, + the index begins at "0", otherwise at "1". It can also take a list of label names. + The outcome will then be returned as a dictionary. + + See also: + :py:meth:`monai.metrics.meandice.compute_dice` + """ + metric_fn = DiceMetric( + include_background=include_background, + reduction=reduction, + num_classes=num_classes, + return_with_label=return_with_label, + ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/source_code/SegMamba/monai/handlers/mean_iou.py b/source_code/SegMamba/monai/handlers/mean_iou.py new file mode 100644 index 0000000000000000000000000000000000000000..69f11a8749c864fda65b07c1d4ce9e6812c9a8a3 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/mean_iou.py @@ -0,0 +1,54 @@ +# 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 + +from monai.handlers.ignite_metric import IgniteMetricHandler +from monai.metrics import MeanIoU +from monai.utils import MetricReduction + + +class MeanIoUHandler(IgniteMetricHandler): + """ + Computes IoU score metric from full size Tensor and collects average over batch, class-channels, iterations. + """ + + def __init__( + self, + include_background: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + output_transform: Callable = lambda x: x, + save_details: bool = True, + ) -> None: + """ + + Args: + include_background: whether to include iou computation on the first channel of the predicted output. + Defaults to True. + reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + output_transform: callable to extract `y_pred` and `y` from `ignite.engine.state.output` then + construct `(y_pred, y)` pair, where `y_pred` and `y` can be `batch-first` Tensors or + lists of `channel-first` Tensors. the form of `(y_pred, y)` is required by the `update()`. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + save_details: whether to save metric computation details per image, for example: mean iou of every image. + default to True, will save to `engine.state.metric_details` dict with the metric name as key. + + See also: + :py:meth:`monai.metrics.meaniou.compute_iou` + """ + metric_fn = MeanIoU(include_background=include_background, reduction=reduction) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/source_code/SegMamba/monai/handlers/metrics_saver.py b/source_code/SegMamba/monai/handlers/metrics_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..88a0926b91d87b39632650194006782b2ccdfa19 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/metrics_saver.py @@ -0,0 +1,164 @@ +# 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 +from typing import TYPE_CHECKING + +from monai.config import IgniteInfo +from monai.data import decollate_batch +from monai.handlers.utils import write_metrics_reports +from monai.utils import ImageMetaKey as Key +from monai.utils import ensure_tuple, min_version, optional_import, string_list_all_gather + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +idist, _ = optional_import("ignite", IgniteInfo.OPT_IMPORT_VERSION, min_version, "distributed") +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + + +class MetricsSaver: + """ + ignite handler to save metrics values and details into expected files. + + Args: + save_dir: directory to save the metrics and metric details. + metrics: expected final metrics to save into files, can be: None, "*" or list of strings. + None - don't save any metrics into files. + "*" - save all the existing metrics in `engine.state.metrics` dict into separate files. + list of strings - specify the expected metrics to save. + default to "*" to save all the metrics into `metrics.csv`. + metric_details: expected metric details to save into files, the data comes from + `engine.state.metric_details`, which should be provided by different `Metrics`, + typically, it's some intermediate values in metric computation. + for example: mean dice of every channel of every image in the validation dataset. + it must contain at least 2 dims: (batch, classes, ...), + if not, will unsqueeze to 2 dims. + this arg can be: None, "*" or list of strings. + None - don't save any metric_details into files. + "*" - save all the existing metric_details in `engine.state.metric_details` dict into separate files. + list of strings - specify the metric_details of expected metrics to save. + if not None, every metric_details array will save a separate `{metric name}_raw.csv` file. + batch_transform: a callable that is used to extract the `meta_data` dictionary of + the input images from `ignite.engine.state.batch` if saving metric details. the purpose is to get the + input filenames from the `meta_data` and store with metric details together. + `engine.state` and `batch_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + summary_ops: expected computation operations to generate the summary report. + it can be: None, "*" or list of strings, default to None. + None - don't generate summary report for every expected metric_details. + "*" - generate summary report for every metric_details with all the supported operations. + list of strings - generate summary report for every metric_details with specified operations, they + should be within list: ["mean", "median", "max", "min", "percentile", "std", "notnans"]. + the number in "percentile" should be [0, 100], like: "15percentile". default: "90percentile". + for more details, please check: https://numpy.org/doc/stable/reference/generated/numpy.nanpercentile.html. + note that: for the overall summary, it computes `nanmean` of all classes for each image first, + then compute summary. example of the generated summary report:: + + class mean median max 5percentile 95percentile notnans + class0 6.0000 6.0000 7.0000 5.1000 6.9000 2.0000 + class1 6.0000 6.0000 6.0000 6.0000 6.0000 1.0000 + mean 6.2500 6.2500 7.0000 5.5750 6.9250 2.0000 + + save_rank: only the handler on specified rank will save to files in multi-gpus validation, default to 0. + delimiter: the delimiter character in the saved file, default to "," as the default output type is `csv`. + to be consistent with: https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter. + output_type: expected output file type, supported types: ["csv"], default to "csv". + + """ + + def __init__( + self, + save_dir: str, + metrics: str | Sequence[str] | None = "*", + metric_details: str | Sequence[str] | None = None, + batch_transform: Callable = lambda x: x, + summary_ops: str | Sequence[str] | None = None, + save_rank: int = 0, + delimiter: str = ",", + output_type: str = "csv", + ) -> None: + self.save_dir = save_dir + self.metrics = ensure_tuple(metrics) if metrics is not None else None + self.metric_details = ensure_tuple(metric_details) if metric_details is not None else None + self.batch_transform = batch_transform + self.summary_ops = ensure_tuple(summary_ops) if summary_ops is not None else None + self.save_rank = save_rank + self.deli = delimiter + self.output_type = output_type + self._filenames: list[str] = [] + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + engine.add_event_handler(Events.EPOCH_STARTED, self._started) + engine.add_event_handler(Events.ITERATION_COMPLETED, self._get_filenames) + engine.add_event_handler(Events.EPOCH_COMPLETED, self) + + def _started(self, _engine: Engine) -> None: + """ + Initialize internal buffers. + + Args: + _engine: Ignite Engine, unused argument. + + """ + self._filenames = [] + + def _get_filenames(self, engine: Engine) -> None: + if self.metric_details is not None: + meta_data = self.batch_transform(engine.state.batch) + if isinstance(meta_data, dict): + # decollate the `dictionary of list` to `list of dictionaries` + meta_data = decollate_batch(meta_data) + for m in meta_data: + self._filenames.append(f"{m.get(Key.FILENAME_OR_OBJ)}") + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + ws = idist.get_world_size() + if self.save_rank >= ws: + raise ValueError("target save rank is greater than the distributed group size.") + + # all gather file names across ranks + _images = string_list_all_gather(strings=self._filenames) if ws > 1 else self._filenames + + # only save metrics to file in specified rank + if idist.get_rank() == self.save_rank: + _metrics = {} + if self.metrics is not None and len(engine.state.metrics) > 0: + _metrics = {k: v for k, v in engine.state.metrics.items() if k in self.metrics or "*" in self.metrics} + _metric_details = {} + if hasattr(engine.state, "metric_details"): + details = engine.state.metric_details + if self.metric_details is not None and len(details) > 0: + for k, v in details.items(): + if k in self.metric_details or "*" in self.metric_details: + _metric_details[k] = v + + write_metrics_reports( + save_dir=self.save_dir, + images=None if len(_images) == 0 else _images, + metrics=_metrics, + metric_details=_metric_details, + summary_ops=self.summary_ops, + deli=self.deli, + output_type=self.output_type, + ) diff --git a/source_code/SegMamba/monai/handlers/mlflow_handler.py b/source_code/SegMamba/monai/handlers/mlflow_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..df209c1c8b14f013c3e1c028945066421b6449a7 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/mlflow_handler.py @@ -0,0 +1,465 @@ +# 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 time +import warnings +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import torch +from torch.utils.data import Dataset + +from monai.config import IgniteInfo +from monai.utils import CommonKeys, ensure_tuple, min_version, optional_import + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") +mlflow, _ = optional_import("mlflow", descriptor="Please install mlflow before using MLFlowHandler.") +mlflow.entities, _ = optional_import( + "mlflow.entities", descriptor="Please install mlflow.entities before using MLFlowHandler." +) +pandas, _ = optional_import("pandas", descriptor="Please install pandas for recording the dataset.") +tqdm, _ = optional_import("tqdm", "4.47.0", min_version, "tqdm") + +if TYPE_CHECKING: + from ignite.engine import Engine +else: + Engine, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine", as_type="decorator" + ) + +DEFAULT_TAG = "Loss" + + +class MLFlowHandler: + """ + MLFlowHandler defines a set of Ignite Event-handlers for the MLFlow tracking logics. + It can be used for any Ignite Engine(trainer, validator and evaluator). + And it can track both epoch level and iteration level logging, then MLFlow can store + the data and visualize. + The expected data source is Ignite ``engine.state.output`` and ``engine.state.metrics``. + + Default behaviors: + - When EPOCH_COMPLETED, track each dictionary item in + ``engine.state.metrics`` in MLFlow. + - When ITERATION_COMPLETED, track expected item in + ``self.output_transform(engine.state.output)`` in MLFlow, default to `Loss`. + + Usage example is available in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/3d_segmentation/unet_segmentation_3d_ignite.ipynb. + + Args: + tracking_uri: connects to a tracking URI. can also set the `MLFLOW_TRACKING_URI` environment + variable to have MLflow find a URI from there. in both cases, the URI can either be + an HTTP/HTTPS URI for a remote server, a database connection string, or a local path + to log data to a directory. The URI defaults to path `mlruns`. + for more details: https://mlflow.org/docs/latest/python_api/mlflow.html#mlflow.set_tracking_uri. + iteration_log: whether to log data to MLFlow when iteration completed, default to `True`. + ``iteration_log`` can be also a function and it will be interpreted as an event filter + (see https://pytorch.org/ignite/generated/ignite.engine.events.Events.html for details). + Event filter function accepts as input engine and event value (iteration) and should return True/False. + epoch_log: whether to log data to MLFlow when epoch completed, default to `True`. + ``epoch_log`` can be also a function and it will be interpreted as an event filter. + See ``iteration_log`` argument for more details. + epoch_logger: customized callable logger for epoch level logging with MLFlow. + Must accept parameter "engine", use default logger if None. + iteration_logger: customized callable logger for iteration level logging with MLFlow. + Must accept parameter "engine", use default logger if None. + dataset_logger: customized callable logger to log the dataset information with MLFlow. + Must accept parameter "dataset_dict", use default logger if None. + dataset_dict: a dictionary in which the key is the name of the dataset and the value is a PyTorch + dataset, that needs to be recorded. This arg is only useful when MLFlow version >= 2.4.0. + For more details about how to log data with MLFlow, please go to the website: + https://mlflow.org/docs/latest/python_api/mlflow.data.html. + dataset_keys: a key or a collection of keys to indicate contents in the dataset that + need to be stored by MLFlow. + output_transform: a callable that is used to transform the + ``ignite.engine.state.output`` into a scalar to track, or a dictionary of {key: scalar}. + By default this value logging happens when every iteration completed. + The default behavior is to track loss from output[0] as output is a decollated list + and we replicated loss value for every item of the decollated list. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch-ignite.ai/concepts/03-state/, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + global_epoch_transform: a callable that is used to customize global epoch number. + For example, in evaluation, the evaluator engine might want to track synced epoch number + with the trainer engine. + state_attributes: expected attributes from `engine.state`, if provided, will extract them + when epoch completed. + tag_name: when iteration output is a scalar, `tag_name` is used to track, defaults to `'Loss'`. + experiment_name: the experiment name of MLflow, default to `'monai_experiment'`. An experiment can be + used to record several runs. + run_name: the run name in an experiment. A run can be used to record information about a workflow, + like the loss, metrics and so on. + experiment_param: a dict recording parameters which will not change through the whole workflow, + like torch version, cuda version and so on. + artifacts: paths to images that need to be recorded after running the workflow. + optimizer_param_names: parameter names in the optimizer that need to be recorded during running the + workflow, default to `'lr'`. + close_on_complete: whether to close the mlflow run in `complete` phase in workflow, default to False. + + For more details of MLFlow usage, please refer to: https://mlflow.org/docs/latest/index.html. + + """ + + # parameters that are logged at the start of training + default_tracking_params = ["max_epochs", "epoch_length"] + + def __init__( + self, + tracking_uri: str | None = None, + iteration_log: bool | Callable[[Engine, int], bool] = True, + epoch_log: bool | Callable[[Engine, int], bool] = True, + epoch_logger: Callable[[Engine], Any] | None = None, + iteration_logger: Callable[[Engine], Any] | None = None, + dataset_logger: Callable[[Mapping[str, Dataset]], Any] | None = None, + dataset_dict: Mapping[str, Dataset] | None = None, + dataset_keys: str = CommonKeys.IMAGE, + output_transform: Callable = lambda x: x[0], + global_epoch_transform: Callable = lambda x: x, + state_attributes: Sequence[str] | None = None, + tag_name: str = DEFAULT_TAG, + experiment_name: str = "monai_experiment", + run_name: str | None = None, + experiment_param: dict | None = None, + artifacts: str | Sequence[Path] | None = None, + optimizer_param_names: str | Sequence[str] = "lr", + close_on_complete: bool = False, + ) -> None: + self.iteration_log = iteration_log + self.epoch_log = epoch_log + self.epoch_logger = epoch_logger + self.iteration_logger = iteration_logger + self.dataset_logger = dataset_logger + self.output_transform = output_transform + self.global_epoch_transform = global_epoch_transform + self.state_attributes = state_attributes + self.tag_name = tag_name + self.experiment_name = experiment_name + self.run_name = run_name + self.experiment_param = experiment_param + self.artifacts = ensure_tuple(artifacts) + self.optimizer_param_names = ensure_tuple(optimizer_param_names) + self.client = mlflow.MlflowClient(tracking_uri=tracking_uri if tracking_uri else None) + self.run_finish_status = mlflow.entities.RunStatus.to_string(mlflow.entities.RunStatus.FINISHED) + self.close_on_complete = close_on_complete + self.experiment = None + self.cur_run = None + self.dataset_dict = dataset_dict + self.dataset_keys = ensure_tuple(dataset_keys) + + def _delete_exist_param_in_dict(self, param_dict: dict) -> None: + """ + Delete parameters in given dict, if they are already logged by current mlflow run. + + Args: + param_dict: parameter dict to be logged to mlflow. + """ + if self.cur_run is None: + return + + key_list = list(param_dict.keys()) + log_data = self.client.get_run(self.cur_run.info.run_id).data + log_param_dict = log_data.params + for key in key_list: + if key in log_param_dict: + del param_dict[key] + + def attach(self, engine: Engine) -> None: + """ + Register a set of Ignite Event-Handlers to a specified Ignite engine. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if not engine.has_event_handler(self.start, Events.STARTED): + engine.add_event_handler(Events.STARTED, self.start) + if self.iteration_log and not engine.has_event_handler(self.iteration_completed, Events.ITERATION_COMPLETED): + event = Events.ITERATION_COMPLETED + if callable(self.iteration_log): # substitute event with new one using filter callable + event = event(event_filter=self.iteration_log) + engine.add_event_handler(event, self.iteration_completed) + if self.epoch_log and not engine.has_event_handler(self.epoch_completed, Events.EPOCH_COMPLETED): + event = Events.EPOCH_COMPLETED + if callable(self.epoch_log): # substitute event with new one using filter callable + event = event(event_filter=self.epoch_log) + engine.add_event_handler(event, self.epoch_completed) + if not engine.has_event_handler(self.complete, Events.COMPLETED): + engine.add_event_handler(Events.COMPLETED, self.complete) + if self.close_on_complete and (not engine.has_event_handler(self.close, Events.COMPLETED)): + engine.add_event_handler(Events.COMPLETED, self.close) + + def start(self, engine: Engine) -> None: + """ + Check MLFlow status and start if not active. + + """ + self._set_experiment() + if not self.experiment: + raise ValueError(f"Failed to set experiment '{self.experiment_name}' as the active experiment") + + if not self.cur_run: + run_name = f"run_{time.strftime('%Y%m%d_%H%M%S')}" if self.run_name is None else self.run_name + runs = self.client.search_runs(self.experiment.experiment_id) + runs = [r for r in runs if r.info.run_name == run_name or not self.run_name] + # runs marked as finish should not record info any more + runs = [r for r in runs if r.info.status != self.run_finish_status] + if runs: + self.cur_run = self.client.get_run(runs[-1].info.run_id) # pick latest active run + else: + self.cur_run = self.client.create_run(experiment_id=self.experiment.experiment_id, run_name=run_name) + + if self.experiment_param: + self._log_params(self.experiment_param) + + attrs = {attr: getattr(engine.state, attr, None) for attr in self.default_tracking_params} + self._delete_exist_param_in_dict(attrs) + self._log_params(attrs) + + if self.dataset_logger: + self.dataset_logger(self.dataset_dict) + else: + self._default_dataset_log(self.dataset_dict) + + def _set_experiment(self): + experiment = self.experiment + if not experiment: + experiment = self.client.get_experiment_by_name(self.experiment_name) + if not experiment: + experiment_id = self.client.create_experiment(self.experiment_name) + experiment = self.client.get_experiment(experiment_id) + + if experiment.lifecycle_stage != mlflow.entities.LifecycleStage.ACTIVE: + raise ValueError(f"Cannot set a deleted experiment '{self.experiment_name}' as the active experiment") + self.experiment = experiment + + @staticmethod + def _get_pandas_dataset_info(pandas_dataset): + dataset_name = pandas_dataset.name + return { + f"{dataset_name}_digest": pandas_dataset.digest, + f"{dataset_name}_samples": pandas_dataset.profile["num_rows"], + } + + def _log_dataset(self, sample_dict: dict[str, Any], context: str = "train") -> None: + if not self.cur_run: + raise ValueError("Current Run is not Active to log the dataset") + + # Need to update the self.cur_run to sync the dataset log, otherwise the `inputs` info will be out-of-date. + self.cur_run = self.client.get_run(self.cur_run.info.run_id) + logged_set = [x for x in self.cur_run.inputs.dataset_inputs if x.dataset.name.startswith(context)] + # In case there are datasets with the same name. + dataset_count = str(len(logged_set)) + dataset_name = f"{context}_dataset_{dataset_count}" + sample_df = pandas.DataFrame(sample_dict) + dataset = mlflow.data.from_pandas(sample_df, name=dataset_name) + exist_dataset_list = list( + filter(lambda x: x.dataset.digest == dataset.digest, self.cur_run.inputs.dataset_inputs) + ) + + if not len(exist_dataset_list): + datasets = [mlflow.entities.DatasetInput(dataset._to_mlflow_entity())] + self.client.log_inputs(run_id=self.cur_run.info.run_id, datasets=datasets) + dataset_info = MLFlowHandler._get_pandas_dataset_info(dataset) + self._log_params(dataset_info) + + def _log_params(self, params: dict[str, Any]) -> None: + if not self.cur_run: + raise ValueError("Current Run is not Active to log params") + params_arr = [mlflow.entities.Param(key, str(value)) for key, value in params.items()] + self.client.log_batch(run_id=self.cur_run.info.run_id, metrics=[], params=params_arr, tags=[]) + + def _log_metrics(self, metrics: dict[str, Any], step: int | None = None) -> None: + if not self.cur_run: + raise ValueError("Current Run is not Active to log metrics") + + run_id = self.cur_run.info.run_id + timestamp = int(time.time() * 1000) + metrics_arr = [mlflow.entities.Metric(key, value, timestamp, step or 0) for key, value in metrics.items()] + self.client.log_batch(run_id=run_id, metrics=metrics_arr, params=[], tags=[]) + + def _parse_artifacts(self): + """ + Log artifacts to mlflow. Given a path, all files in the path will be logged recursively. + Given a file, it will be logged to mlflow. + """ + artifact_list = [] + for path_name in self.artifacts: + # in case the input is (None,) by default + if not path_name: + continue + if os.path.isfile(path_name): + artifact_list.append(path_name) + else: + for root, _, filenames in os.walk(path_name): + for filename in filenames: + file_path = os.path.join(root, filename) + artifact_list.append(file_path) + return artifact_list + + def complete(self) -> None: + """ + Handler for train or validation/evaluation completed Event. + """ + if self.artifacts and self.cur_run: + artifact_list = self._parse_artifacts() + for artifact in artifact_list: + self.client.log_artifact(self.cur_run.info.run_id, artifact) + + def close(self) -> None: + """ + Stop current running logger of MLFlow. + + """ + if self.cur_run: + self.client.set_terminated(self.cur_run.info.run_id, self.run_finish_status) + self.cur_run = None + + def epoch_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation epoch completed Event. + Track epoch level log, default values are from Ignite `engine.state.metrics` dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.epoch_logger is not None: + self.epoch_logger(engine) + else: + self._default_epoch_log(engine) + + def iteration_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation iteration completed Event. + Track iteration level log. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.iteration_logger is not None: + self.iteration_logger(engine) + else: + self._default_iteration_log(engine) + + def _default_epoch_log(self, engine: Engine) -> None: + """ + Execute epoch level log operation. + Default to track the values from Ignite `engine.state.metrics` dict and + track the values of specified attributes of `engine.state`. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + log_dict = engine.state.metrics + if not log_dict: + return + + current_epoch = self.global_epoch_transform(engine.state.epoch) + self._log_metrics(log_dict, step=current_epoch) + + if self.state_attributes is not None: + attrs = {attr: getattr(engine.state, attr, None) for attr in self.state_attributes} + self._log_metrics(attrs, step=current_epoch) + + def _default_iteration_log(self, engine: Engine) -> None: + """ + Execute iteration log operation based on Ignite `engine.state.output` data. + Log the values from `self.output_transform(engine.state.output)`. + Since `engine.state.output` is a decollated list and we replicated the loss value for every item + of the decollated list, the default behavior is to track the loss from `output[0]`. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + loss = self.output_transform(engine.state.output) + if loss is None: + return + + if not isinstance(loss, dict): + loss = {self.tag_name: loss.item() if isinstance(loss, torch.Tensor) else loss} + + self._log_metrics(loss, step=engine.state.iteration) + + # If there is optimizer attr in engine, then record parameters specified in init function. + if hasattr(engine, "optimizer"): + cur_optimizer = engine.optimizer + for param_name in self.optimizer_param_names: + params = { + f"{param_name}_group_{i}": float(param_group[param_name]) + for i, param_group in enumerate(cur_optimizer.param_groups) + } + self._log_metrics(params, step=engine.state.iteration) + + def _default_dataset_log(self, dataset_dict: Mapping[str, Dataset] | None) -> None: + """ + Execute dataset log operation based on the input dataset_dict. The dataset_dict should have a format + like: + { + "dataset_name0": dataset0, + "dataset_name1": dataset1, + ...... + } + The keys stand for names of datasets, which will be logged as prefixes of dataset names in MLFlow. + The values are PyTorch datasets from which sample names are abstracted to build a Pandas DataFrame. + If the input dataset_dict is None, this function will directly return and do nothing. + + To use this function, every sample in the input datasets must contain keys specified by the `dataset_keys` + parameter. + This function will log a PandasDataset to MLFlow inputs, generated from the Pandas DataFrame. + For more details about PandasDataset, please refer to this link: + https://mlflow.org/docs/latest/python_api/mlflow.data.html#mlflow.data.pandas_dataset.PandasDataset + + Please note that it may take a while to record the dataset if it has too many samples. + + Args: + dataset_dict: a dictionary in which the key is the name of the dataset and the value is a PyTorch + dataset, that needs to be recorded. + + """ + + if dataset_dict is None: + return + elif len(dataset_dict) == 0: + warnings.warn("There is no dataset to log!") + + # Log datasets to MLFlow one by one. + for dataset_type, dataset in dataset_dict.items(): + if dataset is None: + raise AttributeError(f"The {dataset_type} dataset of is None. Cannot record it by MLFlow.") + + sample_dict: dict[str, list[str]] = {} + dataset_samples = getattr(dataset, "data", []) + for sample in tqdm(dataset_samples, f"Recording the {dataset_type} dataset"): + for key in self.dataset_keys: + if key not in sample_dict: + sample_dict[key] = [] + + if key in sample: + value_to_log = sample[key] + else: + raise KeyError(f"Unexpect key '{key}' in the sample.") + + if not isinstance(value_to_log, str): + warnings.warn( + f"Expected type string, got type {type(value_to_log)} of the {key} name." + "May log an empty dataset in MLFlow" + ) + else: + sample_dict[key].append(value_to_log) + self._log_dataset(sample_dict, dataset_type) diff --git a/source_code/SegMamba/monai/handlers/parameter_scheduler.py b/source_code/SegMamba/monai/handlers/parameter_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..d12e6e072c0a12edf3e1d2b608178a0bff4065a8 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/parameter_scheduler.py @@ -0,0 +1,178 @@ +# 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 +from bisect import bisect_right +from collections.abc import Callable +from typing import TYPE_CHECKING + +from monai.config import IgniteInfo +from monai.utils import min_version, optional_import + +if TYPE_CHECKING: + from ignite.engine import Engine, Events +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") + + +class ParamSchedulerHandler: + """ + General purpose scheduler for parameters values. By default it can schedule in a linear, exponential, step or + multistep function. One can also pass Callables to have customized scheduling logic. + + Args: + parameter_setter (Callable): Function that sets the required parameter + value_calculator (Union[str,Callable]): Either a string ('linear', 'exponential', 'step' or 'multistep') + or Callable for custom logic. + vc_kwargs (Dict): Dictionary that stores the required parameters for the value_calculator. + epoch_level (bool): Whether the step is based on epoch or iteration. Defaults to False. + name (Optional[str]): Identifier of logging.logger to use, if None, defaulting to ``engine.logger``. + event (Optional[str]): Event to which the handler attaches. Defaults to Events.ITERATION_COMPLETED. + """ + + def __init__( + self, + parameter_setter: Callable, + value_calculator: str | Callable, + vc_kwargs: dict, + epoch_level: bool = False, + name: str | None = None, + event: str | None = None, + ): + self.epoch_level = epoch_level + self.event = event if event is not None else Events.ITERATION_COMPLETED + + self._calculators = { + "linear": self._linear, + "exponential": self._exponential, + "step": self._step, + "multistep": self._multistep, + } + + self._parameter_setter = parameter_setter + self._vc_kwargs = vc_kwargs + self._value_calculator = self._get_value_calculator(value_calculator=value_calculator) + + self.logger = logging.getLogger(name) + self._name = name + + def _get_value_calculator(self, value_calculator): + if isinstance(value_calculator, str): + return self._calculators[value_calculator] + if callable(value_calculator): + return value_calculator + raise ValueError( + f"value_calculator must be either a string from {list(self._calculators.keys())} or a Callable." + ) + + def __call__(self, engine: Engine) -> None: + if self.epoch_level: + self._vc_kwargs["current_step"] = engine.state.epoch + else: + self._vc_kwargs["current_step"] = engine.state.iteration + + new_value = self._value_calculator(**self._vc_kwargs) + self._parameter_setter(new_value) + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine that is used for training. + """ + if self._name is None: + self.logger = engine.logger + engine.add_event_handler(self.event, self) + + @staticmethod + def _linear( + initial_value: float, step_constant: int, step_max_value: int, max_value: float, current_step: int + ) -> float: + """ + Keeps the parameter value to zero until step_zero steps passed and then linearly increases it to 1 until an + additional step_one steps passed. Continues the trend until it reaches max_value. + + Args: + initial_value (float): Starting value of the parameter. + step_constant (int): Step index until parameter's value is kept constant. + step_max_value (int): Step index at which parameter's value becomes max_value. + max_value (float): Max parameter value. + current_step (int): Current step index. + + Returns: + float: new parameter value + """ + if current_step <= step_constant: + delta = 0.0 + elif current_step > step_max_value: + delta = max_value - initial_value + else: + delta = (max_value - initial_value) / (step_max_value - step_constant) * (current_step - step_constant) + + return initial_value + delta + + @staticmethod + def _exponential(initial_value: float, gamma: float, current_step: int) -> float: + """ + Decays the parameter value by gamma every step. + + Based on the closed form of ExponentialLR from Pytorch: + https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ExponentialLR.html. + + Args: + initial_value (float): Starting value of the parameter. + gamma (float): Multiplicative factor of parameter value decay. + current_step (int): Current step index. + + Returns: + float: new parameter value + """ + return initial_value * gamma**current_step + + @staticmethod + def _step(initial_value: float, gamma: float, step_size: int, current_step: int) -> float: + """ + Decays the parameter value by gamma every step_size. + + Based on StepLR from Pytorch: + https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.StepLR.html. + + Args: + initial_value (float): Starting value of the parameter. + gamma (float): Multiplicative factor of parameter value decay. + step_size (int): Period of parameter value decay. + current_step (int): Current step index. + + Returns + float: new parameter value + """ + return initial_value * gamma ** (current_step // step_size) + + @staticmethod + def _multistep(initial_value: float, gamma: float, milestones: list[int], current_step: int) -> float: + """ + Decays the parameter value by gamma once the number of steps reaches one of the milestones. + + Based on MultiStepLR from Pytorch. + https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.MultiStepLR.html. + + Args: + initial_value (float): Starting value of the parameter. + gamma (float): Multiplicative factor of parameter value decay. + milestones (List[int]): List of step indices. Must be increasing. + current_step (int): Current step index. + + Returns: + float: new parameter value + """ + return initial_value * gamma ** bisect_right(milestones, current_step) diff --git a/source_code/SegMamba/monai/handlers/surface_distance.py b/source_code/SegMamba/monai/handlers/surface_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..1a002d2e730755cc73bf93073acf4a9351b664f6 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/surface_distance.py @@ -0,0 +1,63 @@ +# 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 + +from monai.handlers.ignite_metric import IgniteMetricHandler +from monai.metrics import SurfaceDistanceMetric +from monai.utils import MetricReduction + + +class SurfaceDistance(IgniteMetricHandler): + """ + Computes surface distance from full size Tensor and collects average over batch, class-channels, iterations. + """ + + def __init__( + self, + include_background: bool = False, + symmetric: bool = False, + distance_metric: str = "euclidean", + reduction: MetricReduction | str = MetricReduction.MEAN, + output_transform: Callable = lambda x: x, + save_details: bool = True, + ) -> None: + """ + + Args: + include_background: whether to include distance computation on the first channel of the predicted output. + Defaults to ``False``. + symmetric: whether to calculate the symmetric average surface distance between + `seg_pred` and `seg_gt`. Defaults to ``False``. + distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``] + the metric used to compute surface distance. Defaults to ``"euclidean"``. + reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + output_transform: callable to extract `y_pred` and `y` from `ignite.engine.state.output` then + construct `(y_pred, y)` pair, where `y_pred` and `y` can be `batch-first` Tensors or + lists of `channel-first` Tensors. the form of `(y_pred, y)` is required by the `update()`. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + save_details: whether to save metric computation details per image, for example: surface dice + of every image. default to True, will save to `engine.state.metric_details` dict with the metric name as key. + + """ + metric_fn = SurfaceDistanceMetric( + include_background=include_background, + symmetric=symmetric, + distance_metric=distance_metric, + reduction=reduction, + ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/source_code/SegMamba/monai/inferers/__init__.py b/source_code/SegMamba/monai/inferers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..960380bfb8ef5e859a1a8c02cbb38bb3abdca765 --- /dev/null +++ b/source_code/SegMamba/monai/inferers/__init__.py @@ -0,0 +1,25 @@ +# 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 .inferer import ( + Inferer, + PatchInferer, + SaliencyInferer, + SimpleInferer, + SliceInferer, + SlidingWindowInferer, + SlidingWindowInfererAdapt, +) +from .merger import AvgMerger, Merger, ZarrAvgMerger +from .splitter import SlidingWindowSplitter, Splitter, WSISlidingWindowSplitter +from .utils import sliding_window_inference diff --git a/source_code/SegMamba/monai/losses/__init__.py b/source_code/SegMamba/monai/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e937b53fa4dea9aa07ee4992d8fae3ae8a3e9942 --- /dev/null +++ b/source_code/SegMamba/monai/losses/__init__.py @@ -0,0 +1,46 @@ +# 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 .adversarial_loss import PatchAdversarialLoss +from .barlow_twins import BarlowTwinsLoss +from .cldice import SoftclDiceLoss, SoftDiceclDiceLoss +from .contrastive import ContrastiveLoss +from .deform import BendingEnergyLoss, DiffusionLoss +from .dice import ( + Dice, + DiceCELoss, + DiceFocalLoss, + DiceLoss, + GeneralizedDiceFocalLoss, + GeneralizedDiceLoss, + GeneralizedWassersteinDiceLoss, + MaskedDiceLoss, + dice_ce, + dice_focal, + generalized_dice, + generalized_dice_focal, + generalized_wasserstein_dice, +) +from .ds_loss import DeepSupervisionLoss +from .focal_loss import FocalLoss +from .giou_loss import BoxGIoULoss, giou +from .hausdorff_loss import HausdorffDTLoss, LogHausdorffDTLoss +from .image_dissimilarity import GlobalMutualInformationLoss, LocalNormalizedCrossCorrelationLoss +from .multi_scale import MultiScaleLoss +from .perceptual import PerceptualLoss +from .spatial_mask import MaskedLoss +from .spectral_loss import JukeboxLoss +from .ssim_loss import SSIMLoss +from .sure_loss import SURELoss +from .tversky import TverskyLoss +from .unified_focal_loss import AsymmetricUnifiedFocalLoss diff --git a/source_code/SegMamba/monai/losses/barlow_twins.py b/source_code/SegMamba/monai/losses/barlow_twins.py new file mode 100644 index 0000000000000000000000000000000000000000..a61acca66e2ef812beb75cb774a546029438a4a2 --- /dev/null +++ b/source_code/SegMamba/monai/losses/barlow_twins.py @@ -0,0 +1,84 @@ +# 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 torch +from torch.nn.modules.loss import _Loss + + +class BarlowTwinsLoss(_Loss): + """ + The Barlow Twins cost function takes the representations extracted by a neural network from two + distorted views and seeks to make the cross-correlation matrix of the two representations tend + towards identity. This encourages the neural network to learn similar representations with the least + amount of redundancy. This cost function can be used in particular in multimodal learning to work on + representations from two modalities. The most common use case is for unsupervised learning, where data + augmentations are used to generate 2 distorted views of the same sample to force the encoder to + extract useful features for downstream tasks. + + Zbontar, Jure, et al. "Barlow Twins: Self-Supervised Learning via Redundancy Reduction" International + conference on machine learning. PMLR, 2020. (http://proceedings.mlr.press/v139/zbontar21a/zbontar21a.pdf) + + Adapted from: + https://github.com/facebookresearch/barlowtwins + + """ + + def __init__(self, lambd: float = 5e-3) -> None: + """ + Args: + lamb: Can be any float to handle the informativeness and invariance trade-off. Ideally set to 5e-3. + + Raises: + ValueError: When an input of dimension length > 2 is passed + ValueError: When input and target are of different shapes + ValueError: When batch size is less than or equal to 1 + + """ + super().__init__() + self.lambd = lambd + + def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """ + Args: + input: the shape should be B[F]. + target: the shape should be B[F]. + """ + if len(target.shape) > 2 or len(input.shape) > 2: + raise ValueError( + f"Either target or input has dimensions greater than 2 where target " + f"shape is ({target.shape}) and input shape is ({input.shape})" + ) + + if target.shape != input.shape: + raise ValueError(f"ground truth has differing shape ({target.shape}) from input ({input.shape})") + + if target.size(0) <= 1: + raise ValueError( + f"Batch size must be greater than 1 to compute Barlow Twins Loss, but got {target.size(0)}" + ) + + lambd_tensor = torch.as_tensor(self.lambd).to(input.device) + batch_size = input.shape[0] + + # normalize input and target + input_norm = (input - input.mean(0)) / input.std(0).add(1e-6) + target_norm = (target - target.mean(0)) / target.std(0).add(1e-6) + + # cross-correlation matrix + c = torch.mm(input_norm.t(), target_norm) / batch_size # input_norm.t() is FxB, target_norm is BxF so c is FxF + + # loss + c_diff = (c - torch.eye(c.size(0), device=c.device)).pow_(2) # FxF + c_diff[~torch.eye(c.size(0), device=c.device).bool()] *= lambd_tensor + + return c_diff.sum()