Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- source_code/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/.ninja_logAdded+11
- source_code/SegMamba/mamba/csrc/selective_scan/reverse_scan.cuhAdded+401
- source_code/SegMamba/mamba/csrc/selective_scan/selective_scan.hAdded+101
- source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_common.hAdded+221
- source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp16.cuAdded+10
- source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp32.cuAdded+10
- source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_kernel.cuhAdded+345
- source_code/SegMamba/mamba/csrc/selective_scan/static_switch.hAdded+25
- source_code/SegMamba/mamba/csrc/selective_scan/uninitialized_copy.cuhAdded+69
- source_code/SegMamba/mamba/mamba_ssm/models/mixer_seq_simple.pyAdded+233
- source_code/SegMamba/mamba/mamba_ssm/ops/triton/layernorm.pyAdded+636
- source_code/SegMamba/mamba/mamba_ssm/ops/triton/selective_state_update.pyAdded+192
- source_code/SegMamba/mamba/mamba_ssm/utils/generation.pyAdded+377
- source_code/SegMamba/mamba/tests/ops/test_selective_scan.pyAdded+423
- source_code/SegMamba/monai/_extensions/loader.pyAdded+93
- source_code/SegMamba/monai/apps/datasets.pyAdded+745
- source_code/SegMamba/monai/apps/utils.pyAdded+336
- source_code/SegMamba/monai/auto3dseg/__init__.pyAdded+37
- source_code/SegMamba/monai/auto3dseg/algo_gen.pyAdded+107
- source_code/SegMamba/monai/auto3dseg/analyzer.pyAdded+1038
- source_code/SegMamba/monai/auto3dseg/operations.pyAdded+152
- source_code/SegMamba/monai/auto3dseg/seg_summarizer.pyAdded+213
- source_code/SegMamba/monai/auto3dseg/utils.pyAdded+524
- source_code/SegMamba/monai/bundle/__init__.pyAdded+46
- source_code/SegMamba/monai/bundle/__main__.pyAdded+31
- source_code/SegMamba/monai/bundle/config_item.pyAdded+412
- source_code/SegMamba/monai/bundle/config_parser.pyAdded+508
- source_code/SegMamba/monai/bundle/properties.pyAdded+262
- source_code/SegMamba/monai/bundle/reference_resolver.pyAdded+345
- source_code/SegMamba/monai/bundle/scripts.pyAdded+1806
- source_code/SegMamba/monai/bundle/utils.pyAdded+232
- source_code/SegMamba/monai/bundle/workflows.pyAdded+524
- source_code/SegMamba/monai/config/__init__.pyAdded+36
- source_code/SegMamba/monai/config/deviceconfig.pyAdded+274
- source_code/SegMamba/monai/config/type_definitions.pyAdded+85
- source_code/SegMamba/monai/csrc/ext.cppAdded+75
- source_code/SegMamba/monai/engines/__init__.pyAdded+27
- source_code/SegMamba/monai/engines/evaluator.pyAdded+507
- source_code/SegMamba/monai/engines/trainer.pyAdded+473
- source_code/SegMamba/monai/engines/utils.pyAdded+288
- source_code/SegMamba/monai/engines/workflow.pyAdded+309
- source_code/SegMamba/monai/fl/__init__.pyAdded+10
- source_code/SegMamba/monai/handlers/__init__.pyAdded+44
- source_code/SegMamba/monai/handlers/checkpoint_loader.pyAdded+157
- source_code/SegMamba/monai/handlers/checkpoint_saver.pyAdded+334
- source_code/SegMamba/monai/handlers/classification_saver.pyAdded+167
- source_code/SegMamba/monai/handlers/confusion_matrix.pyAdded+71
- source_code/SegMamba/monai/handlers/decollate_batch.pyAdded+96
- source_code/SegMamba/monai/handlers/earlystop_handler.pyAdded+124
- source_code/SegMamba/monai/handlers/garbage_collector.pyAdded+88
1234567891011# ninja log v50 19490 1769349310623049020 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan.o 36279c78d02f77a41 39202 1769349330318255082 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_fp32.o 7d6547add5004b461 39876 1769349330973261935 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_fp16.o 4bbc57405a8462fd1 40297 1769349331412266528 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_bf16.o 4bcb4935fbabf3751 65588 1769349356697531076 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp32_real.o 7aa656e8f7592440 67915 1769349359001555182 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp16_real.o a9ff622fcbfad1330 70957 1769349362064587229 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_bf16_real.o 975c2cf7bf417ec81 92869 1769349383962816340 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp32_complex.o 18c4e1712400dbd80 94589 1769349385684834357 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp16_complex.o f494d02f2077ad750 99933 1769349391029890280 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_bf16_complex.o f81edc21b8db261123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401/****************************************************************************** * Copyright (c) 2023, Tri Dao. ******************************************************************************/
#pragma once
#include <cub/config.cuh>
#include <cub/util_ptx.cuh>#include <cub/util_type.cuh>#include <cub/block/block_raking_layout.cuh>// #include <cub/detail/uninitialized_copy.cuh>#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<LOGICAL_WARP_THREADS>::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<LOGICAL_WARP_THREADS>(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<LOGICAL_WARP_THREADS>(input, src_lane, member_mask); }
/// Inclusive scan template <typename ScanOpT> __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<LOGICAL_WARP_THREADS>( inclusive_output, offset, LOGICAL_WARP_THREADS - 1, member_mask ); // Perform scan op if from a valid peer inclusive_output = static_cast<int>(lane_id) >= LOGICAL_WARP_THREADS - offset ? inclusive_output : scan_op(temp, inclusive_output); } }
/// Exclusive scan // Get exclusive from inclusive template <typename ScanOpT> __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<LOGICAL_WARP_THREADS>(inclusive_output, 0, member_mask); // initial value unknown exclusive_output = cub::ShuffleDown<LOGICAL_WARP_THREADS>( 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 <em>warp-lane</em> is undefined. */ template <typename ScanOpT> __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<LOGICAL_WARP_THREADS>( 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<T, BLOCK_THREADS>; // 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<T, RAKING_THREADS>;
/// 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 <typename ScanOp> __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 <typename ScanOp> __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 <em>lane</em><sub>0</sub> 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] <b>[<em>warp</em><sub>0</sub> only]</b> 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 <em>lane</em><sub>0</sub> 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] <b>[<em>warp</em><sub>0</sub> only]</b> 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); }
};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101/****************************************************************************** * 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;};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221/****************************************************************************** * Copyright (c) 2023, Tri Dao. ******************************************************************************/
#pragma once
#include <cuda_bf16.h>#include <cuda_fp16.h>#include <c10/util/complex.h> // For scalar_value_type
#define MAX_DSTATE 256
using complex_t = c10::complex<float>;
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<int BYTES> 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<typename scalar_t, int N>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<int N>struct Converter<at::Half, N>{ static inline __device__ void to_float(const at::Half (&src)[N], float (&dst)[N]) { static_assert(N % 2 == 0); auto &src2 = reinterpret_cast<const half2 (&)[N / 2]>(src); auto &dst2 = reinterpret_cast<float2 (&)[N / 2]>(dst); #pragma unroll for (int i = 0; i < N / 2; ++i) { dst2[i] = __half22float2(src2[i]); } }};
#if __CUDA_ARCH__ >= 800template<int N>struct Converter<at::BFloat16, N>{ static inline __device__ void to_float(const at::BFloat16 (&src)[N], float (&dst)[N]) { static_assert(N % 2 == 0); auto &src2 = reinterpret_cast<const nv_bfloat162 (&)[N / 2]>(src); auto &dst2 = reinterpret_cast<float2 (&)[N / 2]>(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<typename scalar_t> struct SSMScanOp;
template<>struct SSMScanOp<float> { __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<complex_t> { __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 <typename scalar_t> struct SSMScanPrefixCallbackOp { using scan_t = std::conditional_t<std::is_same_v<scalar_t, float>, 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<scalar_t>()(running_prefix, block_aggregate); return old_prefix; }};
////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename Ktraits>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<typename Ktraits::BlockLoadVecT::TempStorage&>(smem_load); using vec_t = typename Ktraits::vec_t; Ktraits::BlockLoadVecT(smem_load_vec).Load( reinterpret_cast<vec_t*>(u), reinterpret_cast<vec_t(&)[Ktraits::kNLoads]>(u_vals) ); } else { Ktraits::BlockLoadT(smem_load).Load(u, u_vals, seqlen, 0.f); }}
template<typename Ktraits>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<typename Ktraits::BlockLoadWeightVecT::TempStorage&>(smem_load_weight); using vec_t = typename Ktraits::vec_t; Ktraits::BlockLoadWeightVecT(smem_load_weight_vec).Load( reinterpret_cast<vec_t*>(Bvar), reinterpret_cast<vec_t(&)[Ktraits::kNLoads]>(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<typename Ktraits::input_t, kNItems>::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<typename Ktraits::BlockLoadWeightVecT::TempStorage&>(smem_load_weight); using vec_t = typename Ktraits::vec_t; Ktraits::BlockLoadWeightVecT(smem_load_weight_vec).Load( reinterpret_cast<vec_t*>(Bvar), reinterpret_cast<vec_t(&)[Ktraits::kNLoads * 2]>(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<typename Ktraits>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<typename Ktraits::BlockStoreVecT::TempStorage&>(smem_store); using vec_t = typename Ktraits::vec_t; Ktraits::BlockStoreVecT(smem_store_vec).Store( reinterpret_cast<vec_t*>(out), reinterpret_cast<vec_t(&)[Ktraits::kNLoads]>(write_vals) ); } else { Ktraits::BlockStoreT(smem_store).Store(out, write_vals, seqlen); }}12345678910/****************************************************************************** * 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<at::Half, float>(SSMParamsBase ¶ms, cudaStream_t stream);template void selective_scan_fwd_cuda<at::Half, complex_t>(SSMParamsBase ¶ms, cudaStream_t stream);12345678910/****************************************************************************** * 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<float, float>(SSMParamsBase ¶ms, cudaStream_t stream);template void selective_scan_fwd_cuda<float, complex_t>(SSMParamsBase ¶ms, cudaStream_t stream);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345/****************************************************************************** * Copyright (c) 2023, Tri Dao. ******************************************************************************/
#pragma once
#include <c10/util/BFloat16.h>#include <c10/util/Half.h>#include <c10/cuda/CUDAException.h> // For C10_CUDA_CHECK and C10_CUDA_KERNEL_LAUNCH_CHECK
#include <cub/block/block_load.cuh>#include <cub/block/block_store.cuh>#include <cub/block/block_scan.cuh>
#include "selective_scan.h"#include "selective_scan_common.h"#include "static_switch.h"
template<int kNThreads_, int kNItems_, int kNRows_, bool kIsEvenLen_, bool kIsVariableB_, bool kIsVariableC_, bool kHasZ_, typename input_t_, typename weight_t_>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<weight_t, complex_t>; 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<kNBytes * kNElts>::Type; using scan_t = std::conditional_t<!kIsComplex, float2, float4>; using BlockLoadT = cub::BlockLoad<input_t, kNThreads, kNItems, cub::BLOCK_LOAD_WARP_TRANSPOSE>; using BlockLoadVecT = cub::BlockLoad<vec_t, kNThreads, kNLoads, !kDirectIO ? cub::BLOCK_LOAD_WARP_TRANSPOSE : cub::BLOCK_LOAD_DIRECT>; using BlockLoadWeightT = cub::BlockLoad<input_t, kNThreads, !kIsComplex ? kNItems : kNItems * 2, cub::BLOCK_LOAD_WARP_TRANSPOSE>; using BlockLoadWeightVecT = cub::BlockLoad<vec_t, kNThreads, !kIsComplex ? kNLoads : kNLoads * 2, !kDirectIO ? cub::BLOCK_LOAD_WARP_TRANSPOSE : cub::BLOCK_LOAD_DIRECT>; using BlockStoreT = cub::BlockStore<input_t, kNThreads, kNItems, cub::BLOCK_STORE_WARP_TRANSPOSE>; using BlockStoreVecT = cub::BlockStore<vec_t, kNThreads, kNLoads, !kDirectIO ? cub::BLOCK_STORE_WARP_TRANSPOSE : cub::BLOCK_STORE_DIRECT>; // using BlockScanT = cub::BlockScan<scan_t, kNThreads, cub::BLOCK_SCAN_RAKING_MEMOIZE>; // using BlockScanT = cub::BlockScan<scan_t, kNThreads, cub::BLOCK_SCAN_RAKING>; using BlockScanT = cub::BlockScan<scan_t, kNThreads, cub::BLOCK_SCAN_WARP_SCANS>; 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<typename Ktraits>__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<typename BlockLoadT::TempStorage&>(smem_ + 2 * MAX_DSTATE * sizeof(weight_t)); // auto& smem_load = reinterpret_cast<typename BlockLoadT::TempStorage&>(smem_loadstorescan); auto& smem_load = reinterpret_cast<typename Ktraits::BlockLoadT::TempStorage&>(smem_); auto& smem_load_weight = reinterpret_cast<typename Ktraits::BlockLoadWeightT::TempStorage&>(smem_); auto& smem_load_weight1 = *reinterpret_cast<typename Ktraits::BlockLoadWeightT::TempStorage*>(smem_ + sizeof(typename Ktraits::BlockLoadWeightT::TempStorage)); auto& smem_store = reinterpret_cast<typename Ktraits::BlockStoreT::TempStorage&>(smem_); auto& smem_scan = *reinterpret_cast<typename Ktraits::BlockScanT::TempStorage*>(smem_ + Ktraits::kSmemIOSize); // weight_t *smem_a = reinterpret_cast<weight_t *>(smem_ + smem_loadstorescan_size); // weight_t *smem_bc = reinterpret_cast<weight_t *>(smem_a + MAX_DSTATE); scan_t *smem_running_prefix = reinterpret_cast<scan_t *>(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<input_t *>(params.u_ptr) + batch_id * params.u_batch_stride + dim_id * kNRows * params.u_d_stride; input_t *delta = reinterpret_cast<input_t *>(params.delta_ptr) + batch_id * params.delta_batch_stride + dim_id * kNRows * params.delta_d_stride; weight_t *A = reinterpret_cast<weight_t *>(params.A_ptr) + dim_id * kNRows * params.A_d_stride; weight_t *B = reinterpret_cast<weight_t *>(params.B_ptr) + dim_id * kNRows * params.B_d_stride; input_t *Bvar = reinterpret_cast<input_t *>(params.B_ptr) + batch_id * params.B_batch_stride + group_id * params.B_group_stride; weight_t *C = reinterpret_cast<weight_t *>(params.C_ptr) + dim_id * kNRows * params.C_d_stride; input_t *Cvar = reinterpret_cast<input_t *>(params.C_ptr) + batch_id * params.C_batch_stride + group_id * params.C_group_stride; scan_t *x = reinterpret_cast<scan_t *>(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<float *>(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<float *>(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<Ktraits>(u + r * params.u_d_stride, u_vals[r], smem_load, params.seqlen - chunk * kChunkSize); if constexpr (!kDirectIO) { __syncthreads(); } load_input<Ktraits>(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<Ktraits>(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<Ktraits>(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<weight_t> prefix_op(running_prefix); Ktraits::BlockScanT(smem_scan).InclusiveScan( thread_data, thread_data, SSMScanOp<weight_t>(), 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<input_t *>(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<Ktraits>(out + r * params.out_d_stride, out_vals[r], smem_store, params.seqlen - chunk * kChunkSize); }
if constexpr (kHasZ) { input_t *z = reinterpret_cast<input_t *>(params.z_ptr) + batch_id * params.z_batch_stride + dim_id * kNRows * params.z_d_stride + chunk * kChunkSize; input_t *out_z = reinterpret_cast<input_t *>(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<Ktraits>(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<Ktraits>(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<int kNThreads, int kNItems, typename input_t, typename weight_t>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<kNThreads, kNItems, kNRows, kIsEvenLen, kIsVariableB, kIsVariableC, kHasZ, input_t, weight_t>; // 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<Ktraits>; if (kSmemSize >= 48 * 1024) { C10_CUDA_CHECK(cudaFuncSetAttribute( kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kSmemSize)); } kernel<<<grid, Ktraits::kNThreads, kSmemSize, stream>>>(params); C10_CUDA_KERNEL_LAUNCH_CHECK(); }); }); }); });}
template<typename input_t, typename weight_t>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); }}12345678910111213141516171819202122232425// 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<BoolConst>(...);/// });/// ```#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__(); \ } \ }()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869/****************************************************************************** * 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 <cub/config.cuh>
#include <cuda/std/type_traits>
namespace detail{
#if defined(_NVHPC_CUDA)template <typename T, typename U>__host__ __device__ void uninitialized_copy(T *ptr, U &&val){ // NVBug 3384810 new (ptr) T(::cuda::std::forward<U>(val));}#elsetemplate <typename T, typename U, typename ::cuda::std::enable_if< ::cuda::std::is_trivially_copyable<T>::value, int >::type = 0>__host__ __device__ void uninitialized_copy(T *ptr, U &&val){ *ptr = ::cuda::std::forward<U>(val);}
template <typename T, typename U, typename ::cuda::std::enable_if< !::cuda::std::is_trivially_copyable<T>::value, int >::type = 0>__host__ __device__ void uninitialized_copy(T *ptr, U &&val){ new (ptr) T(::cuda::std::forward<U>(val));}#endif
} // namespace detail123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233# Copyright (c) 2023, Albert Gu, Tri Dao.
import mathfrom functools import partial
from collections import namedtuple
import torchimport torch.nn as nn
from mamba_ssm.modules.mamba_simple import Mamba, Blockfrom mamba_ssm.utils.generation import GenerationMixinfrom 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_fnexcept 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#L454def _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 model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636# 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 torchimport torch.nn.functional as Ffrom torch.cuda.amp import custom_fwd, custom_bwd
import tritonimport 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.jitdef _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.jitdef _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, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192# Copyright (c) 2023, Tri Dao.
"""We want triton==2.1.0 for this"""
import mathimport torchimport torch.nn.functional as F
import tritonimport 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.jitdef _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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377# Copyright (c) 2023, Albert Gu, Tri Dao.import gcimport timefrom collections import namedtuplefrom dataclasses import dataclass, fieldfrom functools import partialfrom typing import Callable, Optional, Sequence, Union
import torchimport torch.nn.functional as Ffrom einops import rearrange, repeatfrom torch import Tensorfrom torch.profiler import ProfilerActivity, profile, record_functionfrom transformers.generation import GreedySearchDecoderOnlyOutput, SampleDecoderOnlyOutput
@dataclassclass 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#L231def 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#L170def 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}
@dataclassclass 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 run123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423# Copyright (C) 2023, Tri Dao.
import math
import torchimport torch.nn.functional as Ffrom torch.autograd import gradcheckimport pytest
from einops import rearrange
from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_reffrom mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, mamba_inner_reffrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# 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 platformfrom _thread import interrupt_mainfrom contextlib import contextmanagerfrom glob import globfrom os import pathfrom threading import Timerfrom types import ModuleType
import torch
from monai.utils.module import get_torch_version_tuple, optional_import
dir_path = path.dirname(path.realpath(__file__))
@contextmanagerdef 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]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745# 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 osimport shutilimport sysimport warningsfrom collections.abc import Callable, Sequencefrom pathlib import Pathfrom 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_extractfrom monai.config.type_definitions import PathLikefrom monai.data import ( CacheDataset, PydicomReader, load_decathlon_datalist, load_decathlon_properties, partition_dataset, select_cross_validation_folds,)from monai.transforms import LoadImaged, Randomizablefrom 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_)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336# 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 hashlibimport jsonimport loggingimport osimport shutilimport sysimport tarfileimport tempfileimport warningsimport zipfilefrom pathlib import Pathfrom typing import TYPE_CHECKING, Anyfrom urllib.error import ContentTooShortError, HTTPError, URLErrorfrom urllib.parse import urlparsefrom urllib.request import urlopen, urlretrieve
from monai.config.type_definitions import PathLikefrom 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 = Trueelse: 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 loggerlogger = 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)12345678910111213141516171819202122232425262728293031323334353637# 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, AlgoGenfrom .analyzer import ( Analyzer, FgImageStats, FgImageStatsSumm, FilenameStats, ImageStats, ImageStatsSumm, LabelStats, LabelStatsSumm,)from .operations import Operations, SampleOperations, SummaryOperationsfrom .seg_summarizer import SegSummarizerfrom .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,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107# 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 PathLikefrom 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. """ pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038# 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 timefrom abc import ABC, abstractmethodfrom collections.abc import Hashable, Mappingfrom copy import deepcopyfrom typing import Any
import numpy as npimport torch
from monai.apps.utils import get_loggerfrom monai.auto3dseg.operations import Operations, SampleOperations, SummaryOperationsfrom 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 ConfigParserfrom monai.bundle.utils import ID_SEP_KEYfrom monai.data import MetaTensor, affine_to_spacingfrom monai.transforms.transform import MapTransformfrom monai.transforms.utils_pytorch_numpy_unification import sum, uniquefrom monai.utils import convert_to_numpyfrom monai.utils.enums import DataStatsKeys, ImageStatsKeys, LabelStatsKeysfrom 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 report123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# 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 UserDictfrom functools import partialfrom 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)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# 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 Composefrom 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 report123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524# 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 loggingimport osimport pickleimport subprocessimport sysfrom copy import deepcopyfrom numbers import Numberfrom typing import Any, cast
import numpy as npimport torch
from monai.auto3dseg import Algofrom monai.bundle.config_parser import ConfigParserfrom monai.bundle.utils import ID_SEP_KEYfrom monai.config import PathLikefrom monai.data.meta_tensor import MetaTensorfrom monai.transforms import CropForeground, ToCupyfrom 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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546# 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, Instantiablefrom .config_parser import ConfigParserfrom .properties import InferProperties, MetaProperties, TrainPropertiesfrom .reference_resolver import ReferenceResolverfrom .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, ConfigWorkflow12345678910111213141516171819202122232425262728293031# 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412# 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 astimport inspectimport sysimport warningsfrom abc import ABC, abstractmethodfrom collections.abc import Mapping, Sequencefrom importlib import import_modulefrom pprint import pformatfrom typing import Any
from monai.bundle.utils import EXPR_KEYfrom 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) # <monai.transforms.io.dictionary.LoadImaged object at 0x7fba7ad1ee50>
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) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508# 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 jsonimport refrom collections.abc import Sequencefrom copy import deepcopyfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any
from monai.bundle.config_item import ComponentLocator, ConfigComponent, ConfigExpression, ConfigItemfrom monai.bundle.reference_resolver import ReferenceResolverfrom monai.bundle.utils import ID_REF_KEY, ID_SEP_KEY, MACRO_KEYfrom monai.config import PathLikefrom monai.utils import ensure_tuple, look_up_option, optional_importfrom monai.utils.misc import CheckKeyDuplicatesYamlLoader, check_key_duplicates
if TYPE_CHECKING: import yamlelse: 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 value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262# 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 propertiesto interact with the bundle workflow.Some properties are required and some are optional, optional properties mean: if some component of thebundle 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_KEYfrom 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", },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345# 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 reimport warningsfrom collections.abc import Sequencefrom typing import Any, Iterator
from monai.bundle.config_item import ConfigComponent, ConfigExpression, ConfigItemfrom monai.bundle.utils import ID_REF_KEY, ID_SEP_KEYfrom 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 ret123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806# 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 astimport jsonimport osimport reimport warningsfrom collections.abc import Mapping, Sequencefrom pathlib import Pathfrom pydoc import locatefrom shutil import copyfilefrom textwrap import dedentfrom typing import Any, Callable
import torchfrom torch.cuda import is_available
from monai.apps.mmars.mmars import _get_all_ngc_modelsfrom monai.apps.utils import _basename, download_url, extractall, get_loggerfrom monai.bundle.config_item import ConfigComponentfrom monai.bundle.config_parser import ConfigParserfrom monai.bundle.utils import DEFAULT_INFERENCE, DEFAULT_METADATAfrom monai.bundle.workflows import BundleWorkflow, ConfigWorkflowfrom monai.config import IgniteInfo, PathLikefrom monai.data import load_net_with_metadata, save_net_with_metadatafrom 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 downloadDEFAULT_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 <bundle_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 <bundle_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 <bundle_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 <bundle_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 <bundle_name> --url <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 <meta path> --config_file <config path>
# Execute with specified `run_id=training`: python -m monai.bundle run training --meta_file <meta path> --config_file <config path>
# 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 <config path>
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 "<bundle root>/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 "<bundle_root>/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 <meta path> --config_file <config path>
# 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 <meta path> --config_file <config path>
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 <export path> --ckpt_file <checkpoint path> ...
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 <export path> --ckpt_file <checkpoint path> ...
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 <network definition> --filepath <export path> \ --ckpt_file <checkpoint path> --input_shape <input shape> --dynamic_batchsize <batch range> ...
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 <HF repository id> --name <bundle name> \ --bundle_dir <bundle directory> --version <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 <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 <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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232# 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 jsonimport osimport zipfilefrom typing import Any
from monai.config.deviceconfig import get_config_valuesfrom 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 ConfigItemID_SEP_KEY = "::" # separator for the ID of a ConfigItemEXPR_KEY = "$" # start of a ConfigExpressionMACRO_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 "<bundle root>/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 parser123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524# 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 jsonimport osimport sysimport timefrom abc import ABC, abstractmethodfrom copy import copyfrom logging.config import fileConfigfrom pathlib import Pathfrom typing import Any, Sequence
from monai.apps.utils import get_loggerfrom monai.bundle.config_parser import ConfigParserfrom monai.bundle.properties import InferProperties, MetaProperties, TrainPropertiesfrom monai.bundle.utils import DEFAULT_EXP_MGMT_SETTINGS, EXPR_KEY, ID_REF_KEY, ID_SEP_KEYfrom monai.config import PathLikefrom 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 "<bundle root>/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"] = None123456789101112131415161718192021222324252627282930313233343536# 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,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274# 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 getpassimport osimport platformimport reimport sysfrom collections import OrderedDictfrom typing import TextIO
import numpy as npimport torch
import monaifrom 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, "<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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# 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 osfrom typing import Collection, Hashable, Iterable, Sequence, TypeVar, Union
import numpy as npimport 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# useKeysCollection = 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#L121DtypeLike = Union[np.dtype, type, str, None]
#: NdarrayOrTensor: Union of numpy.ndarray and torch.Tensor to be used for typingNdarrayOrTensor = 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]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475/*Copyright (c) MONAI ConsortiumLicensed 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.0Unless required by applicable law or agreed to in writing, softwaredistributed 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 andlimitations under the License.*/
#include <torch/extension.h>
#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_<monai::BoundType>(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_<monai::InterpolationType>(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");}123456789101112131415161718192021222324252627# 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, SupervisedEvaluatorfrom .trainer import GanTrainer, SupervisedTrainer, Trainerfrom .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 Workflow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507# 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 warningsfrom typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence
import torchfrom torch.utils.data import DataLoader
from monai.config import IgniteInfo, KeysCollectionfrom monai.data import MetaTensorfrom monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batchfrom monai.engines.workflow import Workflowfrom monai.inferers import Inferer, SimpleInfererfrom monai.networks.utils import eval_mode, train_modefrom monai.transforms import Transformfrom monai.utils import ForwardMode, ensure_tuple, min_version, optional_importfrom monai.utils.enums import CommonKeys as Keysfrom monai.utils.enums import EngineStatsKeys as ESKeysfrom monai.utils.module import look_up_option, pytorch_after
if TYPE_CHECKING: from ignite.engine import Engine, EventEnum from ignite.metrics import Metricelse: 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.output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473# 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 warningsfrom typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence
import torchfrom torch.optim.optimizer import Optimizerfrom torch.utils.data import DataLoader
from monai.config import IgniteInfofrom monai.data import MetaTensorfrom monai.engines.utils import IterationEvents, default_make_latent, default_metric_cmp_fn, default_prepare_batchfrom monai.engines.workflow import Workflowfrom monai.inferers import Inferer, SimpleInfererfrom monai.transforms import Transformfrom monai.utils import GanKeys, min_version, optional_importfrom monai.utils.enums import CommonKeys as Keysfrom monai.utils.enums import EngineStatsKeys as ESKeysfrom monai.utils.module import pytorch_after
if TYPE_CHECKING: from ignite.engine import Engine, EventEnum from ignite.metrics import Metricelse: 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(), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288# 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, abstractmethodfrom collections.abc import Callable, Sequencefrom typing import TYPE_CHECKING, Any, cast
import torch
from monai.config import IgniteInfofrom monai.transforms import apply_transformfrom monai.utils import ensure_tuple, min_version, optional_importfrom monai.utils.enums import CommonKeys, GanKeys
if TYPE_CHECKING: from ignite.engine import EventEnumelse: 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_best123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309# 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 warningsfrom collections.abc import Callable, Iterable, Sequencefrom typing import TYPE_CHECKING, Any
import torchimport torch.distributed as distfrom torch.utils.data import DataLoaderfrom torch.utils.data.distributed import DistributedSampler
from monai.config import IgniteInfofrom monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batchfrom monai.transforms import Decollatedfrom 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 Metricelse: 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}12345678910# 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.1234567891011121314151617181920212223242526272829303132333435363738394041424344# 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 CheckpointLoaderfrom .checkpoint_saver import CheckpointSaverfrom .classification_saver import ClassificationSaverfrom .clearml_handlers import ClearMLHandler, ClearMLImageHandler, ClearMLStatsHandlerfrom .confusion_matrix import ConfusionMatrixfrom .decollate_batch import DecollateBatchfrom .earlystop_handler import EarlyStopHandlerfrom .garbage_collector import GarbageCollectorfrom .hausdorff_distance import HausdorffDistancefrom .ignite_metric import IgniteMetric, IgniteMetricHandlerfrom .logfile_handler import LogfileHandlerfrom .lr_schedule_handler import LrScheduleHandlerfrom .mean_dice import MeanDicefrom .mean_iou import MeanIoUHandlerfrom .metric_logger import MetricLogger, MetricLoggerKeysfrom .metrics_reloaded_handler import MetricsReloadedBinaryHandler, MetricsReloadedCategoricalHandlerfrom .metrics_saver import MetricsSaverfrom .mlflow_handler import MLFlowHandlerfrom .nvtx_handlers import MarkHandler, RangeHandler, RangePopHandler, RangePushHandlerfrom .panoptic_quality import PanopticQualityfrom .parameter_scheduler import ParamSchedulerHandlerfrom .postprocessing import PostProcessingfrom .probability_maps import ProbMapProducerfrom .regression_metrics import MeanAbsoluteError, MeanSquaredError, PeakSignalToNoiseRatio, RootMeanSquaredErrorfrom .roc_auc import ROCAUCfrom .smartcache_handler import SmartCacheHandlerfrom .stats_handler import StatsHandlerfrom .surface_distance import SurfaceDistancefrom .tensorboard_handlers import TensorBoardHandler, TensorBoardImageHandler, TensorBoardStatsHandlerfrom .utils import from_engine, ignore_data, stopping_fn_from_loss, stopping_fn_from_metric, write_metrics_reportsfrom .validation_handler import ValidationHandler123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# 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 loggingimport warningsfrom typing import TYPE_CHECKING
import torch
from monai.config import IgniteInfofrom monai.networks.utils import copy_model_statefrom 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 Engineelse: 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}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334# 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 loggingimport osimport warningsfrom collections.abc import Mappingfrom typing import TYPE_CHECKING, Any
from monai.config import IgniteInfofrom 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, DiskSaverelse: 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}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167# 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 loggingimport warningsfrom collections.abc import Callablefrom typing import TYPE_CHECKING
import torch
from monai.config import IgniteInfofrom monai.data import CSVSaver, decollate_batchfrom monai.utils import ImageMetaKey as Keyfrom 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 Engineelse: 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# 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 IgniteMetricHandlerfrom monai.metrics import ConfusionMatrixMetricfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# 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, KeysCollectionfrom monai.engines.utils import IterationEventsfrom monai.transforms import Decollatedfrom 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 Engineelse: 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124# 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 Callablefrom typing import TYPE_CHECKING
from monai.config import IgniteInfofrom 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 Engineelse: 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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788# 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 gcfrom typing import TYPE_CHECKING
from monai.config import IgniteInfofrom monai.utils import min_version, optional_import
if TYPE_CHECKING: from ignite.engine import Engine, Events from ignite.engine.events import CallableEventWithFilterelse: 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})", )source_code/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/.ninja_logAdded+11
source_code/SegMamba/mamba/csrc/selective_scan/reverse_scan.cuhAdded+401
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan.hAdded+101
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_common.hAdded+221
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp16.cuAdded+10
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp32.cuAdded+10
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_kernel.cuhAdded+345
source_code/SegMamba/mamba/csrc/selective_scan/static_switch.hAdded+25
source_code/SegMamba/mamba/csrc/selective_scan/uninitialized_copy.cuhAdded+69
source_code/SegMamba/mamba/mamba_ssm/models/mixer_seq_simple.pyAdded+233
source_code/SegMamba/mamba/mamba_ssm/ops/triton/layernorm.pyAdded+636
source_code/SegMamba/mamba/mamba_ssm/ops/triton/selective_state_update.pyAdded+192
source_code/SegMamba/mamba/mamba_ssm/utils/generation.pyAdded+377
source_code/SegMamba/mamba/tests/ops/test_selective_scan.pyAdded+423
source_code/SegMamba/monai/_extensions/loader.pyAdded+93
source_code/SegMamba/monai/apps/datasets.pyAdded+745
source_code/SegMamba/monai/apps/utils.pyAdded+336
source_code/SegMamba/monai/auto3dseg/__init__.pyAdded+37
source_code/SegMamba/monai/auto3dseg/algo_gen.pyAdded+107
source_code/SegMamba/monai/auto3dseg/analyzer.pyAdded+1038
source_code/SegMamba/monai/auto3dseg/operations.pyAdded+152
source_code/SegMamba/monai/auto3dseg/seg_summarizer.pyAdded+213
source_code/SegMamba/monai/auto3dseg/utils.pyAdded+524
source_code/SegMamba/monai/bundle/__init__.pyAdded+46
source_code/SegMamba/monai/bundle/__main__.pyAdded+31
source_code/SegMamba/monai/bundle/config_item.pyAdded+412
source_code/SegMamba/monai/bundle/config_parser.pyAdded+508
source_code/SegMamba/monai/bundle/properties.pyAdded+262
source_code/SegMamba/monai/bundle/reference_resolver.pyAdded+345
source_code/SegMamba/monai/bundle/scripts.pyAdded+1806
source_code/SegMamba/monai/bundle/utils.pyAdded+232
source_code/SegMamba/monai/bundle/workflows.pyAdded+524
source_code/SegMamba/monai/config/__init__.pyAdded+36
source_code/SegMamba/monai/config/deviceconfig.pyAdded+274
source_code/SegMamba/monai/config/type_definitions.pyAdded+85
source_code/SegMamba/monai/csrc/ext.cppAdded+75
source_code/SegMamba/monai/engines/__init__.pyAdded+27
source_code/SegMamba/monai/engines/evaluator.pyAdded+507
source_code/SegMamba/monai/engines/trainer.pyAdded+473
source_code/SegMamba/monai/engines/utils.pyAdded+288
source_code/SegMamba/monai/engines/workflow.pyAdded+309
source_code/SegMamba/monai/fl/__init__.pyAdded+10
source_code/SegMamba/monai/handlers/__init__.pyAdded+44
source_code/SegMamba/monai/handlers/checkpoint_loader.pyAdded+157
source_code/SegMamba/monai/handlers/checkpoint_saver.pyAdded+334
source_code/SegMamba/monai/handlers/classification_saver.pyAdded+167
source_code/SegMamba/monai/handlers/confusion_matrix.pyAdded+71
source_code/SegMamba/monai/handlers/decollate_batch.pyAdded+96
source_code/SegMamba/monai/handlers/earlystop_handler.pyAdded+124
source_code/SegMamba/monai/handlers/garbage_collector.pyAdded+88