ChipYTY commited on
Commit
d7b4cbb
·
verified ·
1 Parent(s): fe8202e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. source_code/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/.ninja_log +11 -0
  2. source_code/SegMamba/mamba/csrc/selective_scan/reverse_scan.cuh +401 -0
  3. source_code/SegMamba/mamba/csrc/selective_scan/selective_scan.h +101 -0
  4. source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_common.h +221 -0
  5. source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp16.cu +10 -0
  6. source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp32.cu +10 -0
  7. source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_kernel.cuh +345 -0
  8. source_code/SegMamba/mamba/csrc/selective_scan/static_switch.h +25 -0
  9. source_code/SegMamba/mamba/csrc/selective_scan/uninitialized_copy.cuh +69 -0
  10. source_code/SegMamba/mamba/mamba_ssm/models/mixer_seq_simple.py +233 -0
  11. source_code/SegMamba/mamba/mamba_ssm/ops/triton/layernorm.py +636 -0
  12. source_code/SegMamba/mamba/mamba_ssm/ops/triton/selective_state_update.py +192 -0
  13. source_code/SegMamba/mamba/mamba_ssm/utils/generation.py +377 -0
  14. source_code/SegMamba/mamba/tests/ops/test_selective_scan.py +423 -0
  15. source_code/SegMamba/monai/_extensions/loader.py +93 -0
  16. source_code/SegMamba/monai/apps/datasets.py +745 -0
  17. source_code/SegMamba/monai/apps/utils.py +336 -0
  18. source_code/SegMamba/monai/auto3dseg/__init__.py +37 -0
  19. source_code/SegMamba/monai/auto3dseg/algo_gen.py +107 -0
  20. source_code/SegMamba/monai/auto3dseg/analyzer.py +1038 -0
  21. source_code/SegMamba/monai/auto3dseg/operations.py +152 -0
  22. source_code/SegMamba/monai/auto3dseg/seg_summarizer.py +213 -0
  23. source_code/SegMamba/monai/auto3dseg/utils.py +524 -0
  24. source_code/SegMamba/monai/bundle/__init__.py +46 -0
  25. source_code/SegMamba/monai/bundle/__main__.py +31 -0
  26. source_code/SegMamba/monai/bundle/config_item.py +412 -0
  27. source_code/SegMamba/monai/bundle/config_parser.py +508 -0
  28. source_code/SegMamba/monai/bundle/properties.py +262 -0
  29. source_code/SegMamba/monai/bundle/reference_resolver.py +345 -0
  30. source_code/SegMamba/monai/bundle/scripts.py +1806 -0
  31. source_code/SegMamba/monai/bundle/utils.py +232 -0
  32. source_code/SegMamba/monai/bundle/workflows.py +524 -0
  33. source_code/SegMamba/monai/config/__init__.py +36 -0
  34. source_code/SegMamba/monai/config/deviceconfig.py +274 -0
  35. source_code/SegMamba/monai/config/type_definitions.py +85 -0
  36. source_code/SegMamba/monai/csrc/ext.cpp +75 -0
  37. source_code/SegMamba/monai/engines/__init__.py +27 -0
  38. source_code/SegMamba/monai/engines/evaluator.py +507 -0
  39. source_code/SegMamba/monai/engines/trainer.py +473 -0
  40. source_code/SegMamba/monai/engines/utils.py +288 -0
  41. source_code/SegMamba/monai/engines/workflow.py +309 -0
  42. source_code/SegMamba/monai/fl/__init__.py +10 -0
  43. source_code/SegMamba/monai/handlers/__init__.py +44 -0
  44. source_code/SegMamba/monai/handlers/checkpoint_loader.py +157 -0
  45. source_code/SegMamba/monai/handlers/checkpoint_saver.py +334 -0
  46. source_code/SegMamba/monai/handlers/classification_saver.py +167 -0
  47. source_code/SegMamba/monai/handlers/confusion_matrix.py +71 -0
  48. source_code/SegMamba/monai/handlers/decollate_batch.py +96 -0
  49. source_code/SegMamba/monai/handlers/earlystop_handler.py +124 -0
  50. source_code/SegMamba/monai/handlers/garbage_collector.py +88 -0
source_code/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/.ninja_log ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ninja log v5
2
+ 0 19490 1769349310623049020 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan.o 36279c78d02f77a4
3
+ 1 39202 1769349330318255082 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_fp32.o 7d6547add5004b46
4
+ 1 39876 1769349330973261935 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_fp16.o 4bbc57405a8462fd
5
+ 1 40297 1769349331412266528 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_fwd_bf16.o 4bcb4935fbabf375
6
+ 1 65588 1769349356697531076 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp32_real.o 7aa656e8f759244
7
+ 0 67915 1769349359001555182 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp16_real.o a9ff622fcbfad133
8
+ 0 70957 1769349362064587229 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_bf16_real.o 975c2cf7bf417ec8
9
+ 1 92869 1769349383962816340 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp32_complex.o 18c4e1712400dbd8
10
+ 0 94589 1769349385684834357 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_fp16_complex.o f494d02f2077ad75
11
+ 0 99933 1769349391029890280 /root/githubs/SegMamba/mamba/build/temp.linux-x86_64-cpython-312/csrc/selective_scan/selective_scan_bwd_bf16_complex.o f81edc21b8db261
source_code/SegMamba/mamba/csrc/selective_scan/reverse_scan.cuh ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2023, Tri Dao.
3
+ ******************************************************************************/
4
+
5
+ #pragma once
6
+
7
+ #include <cub/config.cuh>
8
+
9
+ #include <cub/util_ptx.cuh>
10
+ #include <cub/util_type.cuh>
11
+ #include <cub/block/block_raking_layout.cuh>
12
+ // #include <cub/detail/uninitialized_copy.cuh>
13
+ #include "uninitialized_copy.cuh"
14
+
15
+ /**
16
+ * Perform a reverse sequential reduction over \p LENGTH elements of the \p input array. The aggregate is returned.
17
+ */
18
+ template <
19
+ int LENGTH,
20
+ typename T,
21
+ typename ReductionOp>
22
+ __device__ __forceinline__ T ThreadReverseReduce(const T (&input)[LENGTH], ReductionOp reduction_op) {
23
+ static_assert(LENGTH > 0);
24
+ T retval = input[LENGTH - 1];
25
+ #pragma unroll
26
+ for (int i = LENGTH - 2; i >= 0; --i) { retval = reduction_op(retval, input[i]); }
27
+ return retval;
28
+ }
29
+
30
+ /**
31
+ * Perform a sequential inclusive postfix reverse scan over the statically-sized \p input array, seeded with the specified \p postfix. The aggregate is returned.
32
+ */
33
+ template <
34
+ int LENGTH,
35
+ typename T,
36
+ typename ScanOp>
37
+ __device__ __forceinline__ T ThreadReverseScanInclusive(
38
+ const T (&input)[LENGTH],
39
+ T (&output)[LENGTH],
40
+ ScanOp scan_op,
41
+ const T postfix)
42
+ {
43
+ T inclusive = postfix;
44
+ #pragma unroll
45
+ for (int i = LENGTH - 1; i >= 0; --i) {
46
+ inclusive = scan_op(inclusive, input[i]);
47
+ output[i] = inclusive;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Perform a sequential exclusive postfix reverse scan over the statically-sized \p input array, seeded with the specified \p postfix. The aggregate is returned.
53
+ */
54
+ template <
55
+ int LENGTH,
56
+ typename T,
57
+ typename ScanOp>
58
+ __device__ __forceinline__ T ThreadReverseScanExclusive(
59
+ const T (&input)[LENGTH],
60
+ T (&output)[LENGTH],
61
+ ScanOp scan_op,
62
+ const T postfix)
63
+ {
64
+ // Careful, output maybe be aliased to input
65
+ T exclusive = postfix;
66
+ T inclusive;
67
+ #pragma unroll
68
+ for (int i = LENGTH - 1; i >= 0; --i) {
69
+ inclusive = scan_op(exclusive, input[i]);
70
+ output[i] = exclusive;
71
+ exclusive = inclusive;
72
+ }
73
+ return inclusive;
74
+ }
75
+
76
+
77
+ /**
78
+ * \brief WarpReverseScan provides SHFL-based variants of parallel postfix scan of items partitioned across a CUDA thread warp.
79
+ *
80
+ * LOGICAL_WARP_THREADS must be a power-of-two
81
+ */
82
+ template <
83
+ typename T, ///< Data type being scanned
84
+ int LOGICAL_WARP_THREADS ///< Number of threads per logical warp
85
+ >
86
+ struct WarpReverseScan {
87
+ //---------------------------------------------------------------------
88
+ // Constants and type definitions
89
+ //---------------------------------------------------------------------
90
+
91
+ /// Whether the logical warp size and the PTX warp size coincide
92
+ static constexpr bool IS_ARCH_WARP = (LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0));
93
+ /// The number of warp scan steps
94
+ static constexpr int STEPS = cub::Log2<LOGICAL_WARP_THREADS>::VALUE;
95
+ static_assert(LOGICAL_WARP_THREADS == 1 << STEPS);
96
+
97
+
98
+ //---------------------------------------------------------------------
99
+ // Thread fields
100
+ //---------------------------------------------------------------------
101
+
102
+ /// Lane index in logical warp
103
+ unsigned int lane_id;
104
+
105
+ /// Logical warp index in 32-thread physical warp
106
+ unsigned int warp_id;
107
+
108
+ /// 32-thread physical warp member mask of logical warp
109
+ unsigned int member_mask;
110
+
111
+ //---------------------------------------------------------------------
112
+ // Construction
113
+ //---------------------------------------------------------------------
114
+
115
+ /// Constructor
116
+ explicit __device__ __forceinline__
117
+ WarpReverseScan()
118
+ : lane_id(cub::LaneId())
119
+ , warp_id(IS_ARCH_WARP ? 0 : (lane_id / LOGICAL_WARP_THREADS))
120
+ , member_mask(cub::WarpMask<LOGICAL_WARP_THREADS>(warp_id))
121
+ {
122
+ if (!IS_ARCH_WARP) {
123
+ lane_id = lane_id % LOGICAL_WARP_THREADS;
124
+ }
125
+ }
126
+
127
+
128
+ /// Broadcast
129
+ __device__ __forceinline__ T Broadcast(
130
+ T input, ///< [in] The value to broadcast
131
+ int src_lane) ///< [in] Which warp lane is to do the broadcasting
132
+ {
133
+ return cub::ShuffleIndex<LOGICAL_WARP_THREADS>(input, src_lane, member_mask);
134
+ }
135
+
136
+
137
+ /// Inclusive scan
138
+ template <typename ScanOpT>
139
+ __device__ __forceinline__ void InclusiveReverseScan(
140
+ T input, ///< [in] Calling thread's input item.
141
+ T &inclusive_output, ///< [out] Calling thread's output item. May be aliased with \p input.
142
+ ScanOpT scan_op) ///< [in] Binary scan operator
143
+ {
144
+ inclusive_output = input;
145
+ #pragma unroll
146
+ for (int STEP = 0; STEP < STEPS; STEP++) {
147
+ int offset = 1 << STEP;
148
+ T temp = cub::ShuffleDown<LOGICAL_WARP_THREADS>(
149
+ inclusive_output, offset, LOGICAL_WARP_THREADS - 1, member_mask
150
+ );
151
+ // Perform scan op if from a valid peer
152
+ inclusive_output = static_cast<int>(lane_id) >= LOGICAL_WARP_THREADS - offset
153
+ ? inclusive_output : scan_op(temp, inclusive_output);
154
+ }
155
+ }
156
+
157
+ /// Exclusive scan
158
+ // Get exclusive from inclusive
159
+ template <typename ScanOpT>
160
+ __device__ __forceinline__ void ExclusiveReverseScan(
161
+ T input, ///< [in] Calling thread's input item.
162
+ T &exclusive_output, ///< [out] Calling thread's output item. May be aliased with \p input.
163
+ ScanOpT scan_op, ///< [in] Binary scan operator
164
+ T &warp_aggregate) ///< [out] Warp-wide aggregate reduction of input items.
165
+ {
166
+ T inclusive_output;
167
+ InclusiveReverseScan(input, inclusive_output, scan_op);
168
+ warp_aggregate = cub::ShuffleIndex<LOGICAL_WARP_THREADS>(inclusive_output, 0, member_mask);
169
+ // initial value unknown
170
+ exclusive_output = cub::ShuffleDown<LOGICAL_WARP_THREADS>(
171
+ inclusive_output, 1, LOGICAL_WARP_THREADS - 1, member_mask
172
+ );
173
+ }
174
+
175
+ /**
176
+ * \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.
177
+ */
178
+ template <typename ScanOpT>
179
+ __device__ __forceinline__ void ReverseScan(
180
+ T input, ///< [in] Calling thread's input item.
181
+ T &inclusive_output, ///< [out] Calling thread's inclusive-scan output item.
182
+ T &exclusive_output, ///< [out] Calling thread's exclusive-scan output item.
183
+ ScanOpT scan_op) ///< [in] Binary scan operator
184
+ {
185
+ InclusiveReverseScan(input, inclusive_output, scan_op);
186
+ // initial value unknown
187
+ exclusive_output = cub::ShuffleDown<LOGICAL_WARP_THREADS>(
188
+ inclusive_output, 1, LOGICAL_WARP_THREADS - 1, member_mask
189
+ );
190
+ }
191
+
192
+ };
193
+
194
+ /**
195
+ * \brief BlockReverseScan provides variants of raking-based parallel postfix scan across a CUDA thread block.
196
+ */
197
+ template <
198
+ typename T, ///< Data type being scanned
199
+ int BLOCK_DIM_X, ///< The thread block length in threads along the X dimension
200
+ 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
201
+ >
202
+ struct BlockReverseScan {
203
+ //---------------------------------------------------------------------
204
+ // Types and constants
205
+ //---------------------------------------------------------------------
206
+
207
+ /// Constants
208
+ /// The thread block size in threads
209
+ static constexpr int BLOCK_THREADS = BLOCK_DIM_X;
210
+
211
+ /// Layout type for padded thread block raking grid
212
+ using BlockRakingLayout = cub::BlockRakingLayout<T, BLOCK_THREADS>;
213
+ // The number of reduction elements is not a multiple of the number of raking threads for now
214
+ static_assert(BlockRakingLayout::UNGUARDED);
215
+
216
+ /// Number of raking threads
217
+ static constexpr int RAKING_THREADS = BlockRakingLayout::RAKING_THREADS;
218
+ /// Number of raking elements per warp synchronous raking thread
219
+ static constexpr int SEGMENT_LENGTH = BlockRakingLayout::SEGMENT_LENGTH;
220
+ /// Cooperative work can be entirely warp synchronous
221
+ static constexpr bool WARP_SYNCHRONOUS = (int(BLOCK_THREADS) == int(RAKING_THREADS));
222
+
223
+ /// WarpReverseScan utility type
224
+ using WarpReverseScan = WarpReverseScan<T, RAKING_THREADS>;
225
+
226
+ /// Shared memory storage layout type
227
+ struct _TempStorage {
228
+ typename BlockRakingLayout::TempStorage raking_grid; ///< Padded thread block raking grid
229
+ };
230
+
231
+
232
+ /// Alias wrapper allowing storage to be unioned
233
+ struct TempStorage : cub::Uninitialized<_TempStorage> {};
234
+
235
+
236
+ //---------------------------------------------------------------------
237
+ // Per-thread fields
238
+ //---------------------------------------------------------------------
239
+
240
+ // Thread fields
241
+ _TempStorage &temp_storage;
242
+ unsigned int linear_tid;
243
+ T cached_segment[SEGMENT_LENGTH];
244
+
245
+
246
+ //---------------------------------------------------------------------
247
+ // Utility methods
248
+ //---------------------------------------------------------------------
249
+
250
+ /// Performs upsweep raking reduction, returning the aggregate
251
+ template <typename ScanOp>
252
+ __device__ __forceinline__ T Upsweep(ScanOp scan_op) {
253
+ T *smem_raking_ptr = BlockRakingLayout::RakingPtr(temp_storage.raking_grid, linear_tid);
254
+ // Read data into registers
255
+ #pragma unroll
256
+ for (int i = 0; i < SEGMENT_LENGTH; ++i) { cached_segment[i] = smem_raking_ptr[i]; }
257
+ T raking_partial = cached_segment[SEGMENT_LENGTH - 1];
258
+ #pragma unroll
259
+ for (int i = SEGMENT_LENGTH - 2; i >= 0; --i) {
260
+ raking_partial = scan_op(raking_partial, cached_segment[i]);
261
+ }
262
+ return raking_partial;
263
+ }
264
+
265
+
266
+ /// Performs exclusive downsweep raking scan
267
+ template <typename ScanOp>
268
+ __device__ __forceinline__ void ExclusiveDownsweep(
269
+ ScanOp scan_op,
270
+ T raking_partial)
271
+ {
272
+ T *smem_raking_ptr = BlockRakingLayout::RakingPtr(temp_storage.raking_grid, linear_tid);
273
+ // Read data back into registers
274
+ if (!MEMOIZE) {
275
+ #pragma unroll
276
+ for (int i = 0; i < SEGMENT_LENGTH; ++i) { cached_segment[i] = smem_raking_ptr[i]; }
277
+ }
278
+ ThreadReverseScanExclusive(cached_segment, cached_segment, scan_op, raking_partial);
279
+ // Write data back to smem
280
+ #pragma unroll
281
+ for (int i = 0; i < SEGMENT_LENGTH; ++i) { smem_raking_ptr[i] = cached_segment[i]; }
282
+ }
283
+
284
+
285
+ //---------------------------------------------------------------------
286
+ // Constructors
287
+ //---------------------------------------------------------------------
288
+
289
+ /// Constructor
290
+ __device__ __forceinline__ BlockReverseScan(
291
+ TempStorage &temp_storage)
292
+ :
293
+ temp_storage(temp_storage.Alias()),
294
+ linear_tid(cub::RowMajorTid(BLOCK_DIM_X, 1, 1))
295
+ {}
296
+
297
+
298
+ /// 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.
299
+ template <
300
+ typename ScanOp,
301
+ typename BlockPostfixCallbackOp>
302
+ __device__ __forceinline__ void ExclusiveReverseScan(
303
+ T input, ///< [in] Calling thread's input item
304
+ T &exclusive_output, ///< [out] Calling thread's output item (may be aliased to \p input)
305
+ ScanOp scan_op, ///< [in] Binary scan operator
306
+ 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.
307
+ {
308
+ if (WARP_SYNCHRONOUS) {
309
+ // Short-circuit directly to warp-synchronous scan
310
+ T block_aggregate;
311
+ WarpReverseScan warp_scan;
312
+ warp_scan.ExclusiveReverseScan(input, exclusive_output, scan_op, block_aggregate);
313
+ // Obtain warp-wide postfix in lane0, then broadcast to other lanes
314
+ T block_postfix = block_postfix_callback_op(block_aggregate);
315
+ block_postfix = warp_scan.Broadcast(block_postfix, 0);
316
+ exclusive_output = linear_tid == BLOCK_THREADS - 1 ? block_postfix : scan_op(block_postfix, exclusive_output);
317
+ } else {
318
+ // Place thread partial into shared memory raking grid
319
+ T *placement_ptr = BlockRakingLayout::PlacementPtr(temp_storage.raking_grid, linear_tid);
320
+ detail::uninitialized_copy(placement_ptr, input);
321
+ cub::CTA_SYNC();
322
+ // Reduce parallelism down to just raking threads
323
+ if (linear_tid < RAKING_THREADS) {
324
+ WarpReverseScan warp_scan;
325
+ // Raking upsweep reduction across shared partials
326
+ T upsweep_partial = Upsweep(scan_op);
327
+ // Warp-synchronous scan
328
+ T exclusive_partial, block_aggregate;
329
+ warp_scan.ExclusiveReverseScan(upsweep_partial, exclusive_partial, scan_op, block_aggregate);
330
+ // Obtain block-wide postfix in lane0, then broadcast to other lanes
331
+ T block_postfix = block_postfix_callback_op(block_aggregate);
332
+ block_postfix = warp_scan.Broadcast(block_postfix, 0);
333
+ // Update postfix with warpscan exclusive partial
334
+ T downsweep_postfix = linear_tid == RAKING_THREADS - 1
335
+ ? block_postfix : scan_op(block_postfix, exclusive_partial);
336
+ // Exclusive raking downsweep scan
337
+ ExclusiveDownsweep(scan_op, downsweep_postfix);
338
+ }
339
+ cub::CTA_SYNC();
340
+ // Grab thread postfix from shared memory
341
+ exclusive_output = *placement_ptr;
342
+
343
+ // // Compute warp scan in each warp.
344
+ // // The exclusive output from the last lane in each warp is invalid.
345
+ // T inclusive_output;
346
+ // WarpReverseScan warp_scan;
347
+ // warp_scan.ReverseScan(input, inclusive_output, exclusive_output, scan_op);
348
+
349
+ // // Compute the warp-wide postfix and block-wide aggregate for each warp. Warp postfix for the last warp is invalid.
350
+ // T block_aggregate;
351
+ // T warp_postfix = ComputeWarpPostfix(scan_op, inclusive_output, block_aggregate);
352
+
353
+ // // Apply warp postfix to our lane's partial
354
+ // if (warp_id != 0) {
355
+ // exclusive_output = scan_op(warp_postfix, exclusive_output);
356
+ // if (lane_id == 0) { exclusive_output = warp_postfix; }
357
+ // }
358
+
359
+ // // Use the first warp to determine the thread block postfix, returning the result in lane0
360
+ // if (warp_id == 0) {
361
+ // T block_postfix = block_postfix_callback_op(block_aggregate);
362
+ // if (lane_id == 0) {
363
+ // // Share the postfix with all threads
364
+ // detail::uninitialized_copy(&temp_storage.block_postfix,
365
+ // block_postfix);
366
+
367
+ // exclusive_output = block_postfix; // The block postfix is the exclusive output for tid0
368
+ // }
369
+ // }
370
+
371
+ // cub::CTA_SYNC();
372
+
373
+ // // Incorporate thread block postfix into outputs
374
+ // T block_postfix = temp_storage.block_postfix;
375
+ // if (linear_tid > 0) { exclusive_output = scan_op(block_postfix, exclusive_output); }
376
+ }
377
+ }
378
+
379
+
380
+ /**
381
+ * \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.
382
+ */
383
+ template <
384
+ int ITEMS_PER_THREAD,
385
+ typename ScanOp,
386
+ typename BlockPostfixCallbackOp>
387
+ __device__ __forceinline__ void InclusiveReverseScan(
388
+ T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items
389
+ T (&output)[ITEMS_PER_THREAD], ///< [out] Calling thread's output items (may be aliased to \p input)
390
+ ScanOp scan_op, ///< [in] Binary scan functor
391
+ 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.
392
+ {
393
+ // Reduce consecutive thread items in registers
394
+ T thread_postfix = ThreadReverseReduce(input, scan_op);
395
+ // Exclusive thread block-scan
396
+ ExclusiveReverseScan(thread_postfix, thread_postfix, scan_op, block_postfix_callback_op);
397
+ // Inclusive scan in registers with postfix as seed
398
+ ThreadReverseScanInclusive(input, output, scan_op, thread_postfix);
399
+ }
400
+
401
+ };
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan.h ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2023, Tri Dao.
3
+ ******************************************************************************/
4
+
5
+ #pragma once
6
+
7
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
8
+
9
+ struct SSMScanParamsBase {
10
+ using index_t = uint32_t;
11
+
12
+ int batch, seqlen, n_chunks;
13
+ index_t a_batch_stride;
14
+ index_t b_batch_stride;
15
+ index_t out_batch_stride;
16
+
17
+ // Common data pointers.
18
+ void *__restrict__ a_ptr;
19
+ void *__restrict__ b_ptr;
20
+ void *__restrict__ out_ptr;
21
+ void *__restrict__ x_ptr;
22
+ };
23
+
24
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
25
+
26
+ struct SSMParamsBase {
27
+ using index_t = uint32_t;
28
+
29
+ int batch, dim, seqlen, dstate, n_groups, n_chunks;
30
+ int dim_ngroups_ratio;
31
+ bool is_variable_B;
32
+ bool is_variable_C;
33
+
34
+ bool delta_softplus;
35
+
36
+ index_t A_d_stride;
37
+ index_t A_dstate_stride;
38
+ index_t B_batch_stride;
39
+ index_t B_d_stride;
40
+ index_t B_dstate_stride;
41
+ index_t B_group_stride;
42
+ index_t C_batch_stride;
43
+ index_t C_d_stride;
44
+ index_t C_dstate_stride;
45
+ index_t C_group_stride;
46
+ index_t u_batch_stride;
47
+ index_t u_d_stride;
48
+ index_t delta_batch_stride;
49
+ index_t delta_d_stride;
50
+ index_t z_batch_stride;
51
+ index_t z_d_stride;
52
+ index_t out_batch_stride;
53
+ index_t out_d_stride;
54
+ index_t out_z_batch_stride;
55
+ index_t out_z_d_stride;
56
+
57
+ // Common data pointers.
58
+ void *__restrict__ A_ptr;
59
+ void *__restrict__ B_ptr;
60
+ void *__restrict__ C_ptr;
61
+ void *__restrict__ D_ptr;
62
+ void *__restrict__ u_ptr;
63
+ void *__restrict__ delta_ptr;
64
+ void *__restrict__ delta_bias_ptr;
65
+ void *__restrict__ out_ptr;
66
+ void *__restrict__ x_ptr;
67
+ void *__restrict__ z_ptr;
68
+ void *__restrict__ out_z_ptr;
69
+ };
70
+
71
+ struct SSMParamsBwd: public SSMParamsBase {
72
+ index_t dout_batch_stride;
73
+ index_t dout_d_stride;
74
+ index_t dA_d_stride;
75
+ index_t dA_dstate_stride;
76
+ index_t dB_batch_stride;
77
+ index_t dB_group_stride;
78
+ index_t dB_d_stride;
79
+ index_t dB_dstate_stride;
80
+ index_t dC_batch_stride;
81
+ index_t dC_group_stride;
82
+ index_t dC_d_stride;
83
+ index_t dC_dstate_stride;
84
+ index_t du_batch_stride;
85
+ index_t du_d_stride;
86
+ index_t dz_batch_stride;
87
+ index_t dz_d_stride;
88
+ index_t ddelta_batch_stride;
89
+ index_t ddelta_d_stride;
90
+
91
+ // Common data pointers.
92
+ void *__restrict__ dout_ptr;
93
+ void *__restrict__ dA_ptr;
94
+ void *__restrict__ dB_ptr;
95
+ void *__restrict__ dC_ptr;
96
+ void *__restrict__ dD_ptr;
97
+ void *__restrict__ du_ptr;
98
+ void *__restrict__ dz_ptr;
99
+ void *__restrict__ ddelta_ptr;
100
+ void *__restrict__ ddelta_bias_ptr;
101
+ };
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_common.h ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2023, Tri Dao.
3
+ ******************************************************************************/
4
+
5
+ #pragma once
6
+
7
+ #include <cuda_bf16.h>
8
+ #include <cuda_fp16.h>
9
+ #include <c10/util/complex.h> // For scalar_value_type
10
+
11
+ #define MAX_DSTATE 256
12
+
13
+ using complex_t = c10::complex<float>;
14
+
15
+ inline __device__ float2 operator+(const float2 & a, const float2 & b){
16
+ return {a.x + b.x, a.y + b.y};
17
+ }
18
+
19
+ inline __device__ float3 operator+(const float3 &a, const float3 &b) {
20
+ return {a.x + b.x, a.y + b.y, a.z + b.z};
21
+ }
22
+
23
+ inline __device__ float4 operator+(const float4 & a, const float4 & b){
24
+ return {a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w};
25
+ }
26
+
27
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
28
+
29
+ template<int BYTES> struct BytesToType {};
30
+
31
+ template<> struct BytesToType<16> {
32
+ using Type = uint4;
33
+ static_assert(sizeof(Type) == 16);
34
+ };
35
+
36
+ template<> struct BytesToType<8> {
37
+ using Type = uint64_t;
38
+ static_assert(sizeof(Type) == 8);
39
+ };
40
+
41
+ template<> struct BytesToType<4> {
42
+ using Type = uint32_t;
43
+ static_assert(sizeof(Type) == 4);
44
+ };
45
+
46
+ template<> struct BytesToType<2> {
47
+ using Type = uint16_t;
48
+ static_assert(sizeof(Type) == 2);
49
+ };
50
+
51
+ template<> struct BytesToType<1> {
52
+ using Type = uint8_t;
53
+ static_assert(sizeof(Type) == 1);
54
+ };
55
+
56
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
57
+
58
+ template<typename scalar_t, int N>
59
+ struct Converter{
60
+ static inline __device__ void to_float(const scalar_t (&src)[N], float (&dst)[N]) {
61
+ #pragma unroll
62
+ for (int i = 0; i < N; ++i) { dst[i] = src[i]; }
63
+ }
64
+ };
65
+
66
+ template<int N>
67
+ struct Converter<at::Half, N>{
68
+ static inline __device__ void to_float(const at::Half (&src)[N], float (&dst)[N]) {
69
+ static_assert(N % 2 == 0);
70
+ auto &src2 = reinterpret_cast<const half2 (&)[N / 2]>(src);
71
+ auto &dst2 = reinterpret_cast<float2 (&)[N / 2]>(dst);
72
+ #pragma unroll
73
+ for (int i = 0; i < N / 2; ++i) { dst2[i] = __half22float2(src2[i]); }
74
+ }
75
+ };
76
+
77
+ #if __CUDA_ARCH__ >= 800
78
+ template<int N>
79
+ struct Converter<at::BFloat16, N>{
80
+ static inline __device__ void to_float(const at::BFloat16 (&src)[N], float (&dst)[N]) {
81
+ static_assert(N % 2 == 0);
82
+ auto &src2 = reinterpret_cast<const nv_bfloat162 (&)[N / 2]>(src);
83
+ auto &dst2 = reinterpret_cast<float2 (&)[N / 2]>(dst);
84
+ #pragma unroll
85
+ for (int i = 0; i < N / 2; ++i) { dst2[i] = __bfloat1622float2(src2[i]); }
86
+ }
87
+ };
88
+ #endif
89
+
90
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
91
+
92
+ // From https://stackoverflow.com/questions/9860711/cucomplex-h-and-exp
93
+ // and https://forums.developer.nvidia.com/t/complex-number-exponential-function/24696
94
+ __device__ __forceinline__ complex_t cexp2f(complex_t z) {
95
+ float t = exp2f(z.real_);
96
+ float c, s;
97
+ sincosf(z.imag_, &s, &c);
98
+ return complex_t(c * t, s * t);
99
+ }
100
+
101
+ __device__ __forceinline__ complex_t cexpf(complex_t z) {
102
+ float t = expf(z.real_);
103
+ float c, s;
104
+ sincosf(z.imag_, &s, &c);
105
+ return complex_t(c * t, s * t);
106
+ }
107
+
108
+ template<typename scalar_t> struct SSMScanOp;
109
+
110
+ template<>
111
+ struct SSMScanOp<float> {
112
+ __device__ __forceinline__ float2 operator()(const float2 &ab0, const float2 &ab1) const {
113
+ return make_float2(ab1.x * ab0.x, ab1.x * ab0.y + ab1.y);
114
+ }
115
+ };
116
+
117
+ template<>
118
+ struct SSMScanOp<complex_t> {
119
+ __device__ __forceinline__ float4 operator()(const float4 &ab0, const float4 &ab1) const {
120
+ complex_t a0 = complex_t(ab0.x, ab0.y);
121
+ complex_t b0 = complex_t(ab0.z, ab0.w);
122
+ complex_t a1 = complex_t(ab1.x, ab1.y);
123
+ complex_t b1 = complex_t(ab1.z, ab1.w);
124
+ complex_t out_a = a1 * a0;
125
+ complex_t out_b = a1 * b0 + b1;
126
+ return make_float4(out_a.real_, out_a.imag_, out_b.real_, out_b.imag_);
127
+ }
128
+ };
129
+
130
+ // A stateful callback functor that maintains a running prefix to be applied
131
+ // during consecutive scan operations.
132
+ template <typename scalar_t> struct SSMScanPrefixCallbackOp {
133
+ using scan_t = std::conditional_t<std::is_same_v<scalar_t, float>, float2, float4>;
134
+ scan_t running_prefix;
135
+ // Constructor
136
+ __device__ SSMScanPrefixCallbackOp(scan_t running_prefix_) : running_prefix(running_prefix_) {}
137
+ // Callback operator to be entered by the first warp of threads in the block.
138
+ // Thread-0 is responsible for returning a value for seeding the block-wide scan.
139
+ __device__ scan_t operator()(scan_t block_aggregate) {
140
+ scan_t old_prefix = running_prefix;
141
+ running_prefix = SSMScanOp<scalar_t>()(running_prefix, block_aggregate);
142
+ return old_prefix;
143
+ }
144
+ };
145
+
146
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
147
+
148
+ template<typename Ktraits>
149
+ inline __device__ void load_input(typename Ktraits::input_t *u,
150
+ typename Ktraits::input_t (&u_vals)[Ktraits::kNItems],
151
+ typename Ktraits::BlockLoadT::TempStorage &smem_load,
152
+ int seqlen) {
153
+ if constexpr (Ktraits::kIsEvenLen) {
154
+ auto& smem_load_vec = reinterpret_cast<typename Ktraits::BlockLoadVecT::TempStorage&>(smem_load);
155
+ using vec_t = typename Ktraits::vec_t;
156
+ Ktraits::BlockLoadVecT(smem_load_vec).Load(
157
+ reinterpret_cast<vec_t*>(u),
158
+ reinterpret_cast<vec_t(&)[Ktraits::kNLoads]>(u_vals)
159
+ );
160
+ } else {
161
+ Ktraits::BlockLoadT(smem_load).Load(u, u_vals, seqlen, 0.f);
162
+ }
163
+ }
164
+
165
+ template<typename Ktraits>
166
+ inline __device__ void load_weight(typename Ktraits::input_t *Bvar,
167
+ typename Ktraits::weight_t (&B_vals)[Ktraits::kNItems],
168
+ typename Ktraits::BlockLoadWeightT::TempStorage &smem_load_weight,
169
+ int seqlen) {
170
+ constexpr int kNItems = Ktraits::kNItems;
171
+ if constexpr (!Ktraits::kIsComplex) {
172
+ typename Ktraits::input_t B_vals_load[kNItems];
173
+ if constexpr (Ktraits::kIsEvenLen) {
174
+ auto& smem_load_weight_vec = reinterpret_cast<typename Ktraits::BlockLoadWeightVecT::TempStorage&>(smem_load_weight);
175
+ using vec_t = typename Ktraits::vec_t;
176
+ Ktraits::BlockLoadWeightVecT(smem_load_weight_vec).Load(
177
+ reinterpret_cast<vec_t*>(Bvar),
178
+ reinterpret_cast<vec_t(&)[Ktraits::kNLoads]>(B_vals_load)
179
+ );
180
+ } else {
181
+ Ktraits::BlockLoadWeightT(smem_load_weight).Load(Bvar, B_vals_load, seqlen, 0.f);
182
+ }
183
+ // #pragma unroll
184
+ // for (int i = 0; i < kNItems; ++i) { B_vals[i] = B_vals_load[i]; }
185
+ Converter<typename Ktraits::input_t, kNItems>::to_float(B_vals_load, B_vals);
186
+ } else {
187
+ typename Ktraits::input_t B_vals_load[kNItems * 2];
188
+ if constexpr (Ktraits::kIsEvenLen) {
189
+ auto& smem_load_weight_vec = reinterpret_cast<typename Ktraits::BlockLoadWeightVecT::TempStorage&>(smem_load_weight);
190
+ using vec_t = typename Ktraits::vec_t;
191
+ Ktraits::BlockLoadWeightVecT(smem_load_weight_vec).Load(
192
+ reinterpret_cast<vec_t*>(Bvar),
193
+ reinterpret_cast<vec_t(&)[Ktraits::kNLoads * 2]>(B_vals_load)
194
+ );
195
+ } else {
196
+ Ktraits::BlockLoadWeightT(smem_load_weight).Load(Bvar, B_vals_load, seqlen, 0.f);
197
+ }
198
+ #pragma unroll
199
+ for (int i = 0; i < kNItems; ++i) { B_vals[i] = complex_t(B_vals_load[i * 2], B_vals_load[i * 2 + 1]); }
200
+ }
201
+ }
202
+
203
+ template<typename Ktraits>
204
+ inline __device__ void store_output(typename Ktraits::input_t *out,
205
+ const float (&out_vals)[Ktraits::kNItems],
206
+ typename Ktraits::BlockStoreT::TempStorage &smem_store,
207
+ int seqlen) {
208
+ typename Ktraits::input_t write_vals[Ktraits::kNItems];
209
+ #pragma unroll
210
+ for (int i = 0; i < Ktraits::kNItems; ++i) { write_vals[i] = out_vals[i]; }
211
+ if constexpr (Ktraits::kIsEvenLen) {
212
+ auto& smem_store_vec = reinterpret_cast<typename Ktraits::BlockStoreVecT::TempStorage&>(smem_store);
213
+ using vec_t = typename Ktraits::vec_t;
214
+ Ktraits::BlockStoreVecT(smem_store_vec).Store(
215
+ reinterpret_cast<vec_t*>(out),
216
+ reinterpret_cast<vec_t(&)[Ktraits::kNLoads]>(write_vals)
217
+ );
218
+ } else {
219
+ Ktraits::BlockStoreT(smem_store).Store(out, write_vals, seqlen);
220
+ }
221
+ }
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp16.cu ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2023, Tri Dao.
3
+ ******************************************************************************/
4
+
5
+ // Split into multiple files to compile in paralell
6
+
7
+ #include "selective_scan_fwd_kernel.cuh"
8
+
9
+ template void selective_scan_fwd_cuda<at::Half, float>(SSMParamsBase &params, cudaStream_t stream);
10
+ template void selective_scan_fwd_cuda<at::Half, complex_t>(SSMParamsBase &params, cudaStream_t stream);
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_fp32.cu ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2023, Tri Dao.
3
+ ******************************************************************************/
4
+
5
+ // Split into multiple files to compile in paralell
6
+
7
+ #include "selective_scan_fwd_kernel.cuh"
8
+
9
+ template void selective_scan_fwd_cuda<float, float>(SSMParamsBase &params, cudaStream_t stream);
10
+ template void selective_scan_fwd_cuda<float, complex_t>(SSMParamsBase &params, cudaStream_t stream);
source_code/SegMamba/mamba/csrc/selective_scan/selective_scan_fwd_kernel.cuh ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2023, Tri Dao.
3
+ ******************************************************************************/
4
+
5
+ #pragma once
6
+
7
+ #include <c10/util/BFloat16.h>
8
+ #include <c10/util/Half.h>
9
+ #include <c10/cuda/CUDAException.h> // For C10_CUDA_CHECK and C10_CUDA_KERNEL_LAUNCH_CHECK
10
+
11
+ #include <cub/block/block_load.cuh>
12
+ #include <cub/block/block_store.cuh>
13
+ #include <cub/block/block_scan.cuh>
14
+
15
+ #include "selective_scan.h"
16
+ #include "selective_scan_common.h"
17
+ #include "static_switch.h"
18
+
19
+ template<int kNThreads_, int kNItems_, int kNRows_, bool kIsEvenLen_,
20
+ bool kIsVariableB_, bool kIsVariableC_,
21
+ bool kHasZ_, typename input_t_, typename weight_t_>
22
+ struct Selective_Scan_fwd_kernel_traits {
23
+ static_assert(kNItems_ % 4 == 0);
24
+ using input_t = input_t_;
25
+ using weight_t = weight_t_;
26
+ static constexpr int kNThreads = kNThreads_;
27
+ // Setting MinBlocksPerMP to be 3 (instead of 2) for 128 threads improves occupancy.
28
+ static constexpr int kMinBlocks = kNThreads < 128 ? 5 : 3;
29
+ static constexpr int kNItems = kNItems_;
30
+ static constexpr int kNRows = kNRows_;
31
+ static constexpr int kNBytes = sizeof(input_t);
32
+ static_assert(kNBytes == 2 || kNBytes == 4);
33
+ static constexpr int kNElts = kNBytes == 4 ? 4 : std::min(8, kNItems);
34
+ static_assert(kNItems % kNElts == 0);
35
+ static constexpr int kNLoads = kNItems / kNElts;
36
+ static constexpr bool kIsComplex = std::is_same_v<weight_t, complex_t>;
37
+ static constexpr bool kIsEvenLen = kIsEvenLen_;
38
+ static constexpr bool kIsVariableB = kIsVariableB_;
39
+ static constexpr bool kIsVariableC = kIsVariableC_;
40
+ static constexpr bool kHasZ = kHasZ_;
41
+
42
+ static constexpr bool kDirectIO = kIsEvenLen && kNLoads == 1;
43
+
44
+ using vec_t = typename BytesToType<kNBytes * kNElts>::Type;
45
+ using scan_t = std::conditional_t<!kIsComplex, float2, float4>;
46
+ using BlockLoadT = cub::BlockLoad<input_t, kNThreads, kNItems, cub::BLOCK_LOAD_WARP_TRANSPOSE>;
47
+ using BlockLoadVecT = cub::BlockLoad<vec_t, kNThreads, kNLoads,
48
+ !kDirectIO ? cub::BLOCK_LOAD_WARP_TRANSPOSE : cub::BLOCK_LOAD_DIRECT>;
49
+ using BlockLoadWeightT = cub::BlockLoad<input_t, kNThreads, !kIsComplex ? kNItems : kNItems * 2, cub::BLOCK_LOAD_WARP_TRANSPOSE>;
50
+ using BlockLoadWeightVecT = cub::BlockLoad<vec_t, kNThreads, !kIsComplex ? kNLoads : kNLoads * 2,
51
+ !kDirectIO ? cub::BLOCK_LOAD_WARP_TRANSPOSE : cub::BLOCK_LOAD_DIRECT>;
52
+ using BlockStoreT = cub::BlockStore<input_t, kNThreads, kNItems, cub::BLOCK_STORE_WARP_TRANSPOSE>;
53
+ using BlockStoreVecT = cub::BlockStore<vec_t, kNThreads, kNLoads,
54
+ !kDirectIO ? cub::BLOCK_STORE_WARP_TRANSPOSE : cub::BLOCK_STORE_DIRECT>;
55
+ // using BlockScanT = cub::BlockScan<scan_t, kNThreads, cub::BLOCK_SCAN_RAKING_MEMOIZE>;
56
+ // using BlockScanT = cub::BlockScan<scan_t, kNThreads, cub::BLOCK_SCAN_RAKING>;
57
+ using BlockScanT = cub::BlockScan<scan_t, kNThreads, cub::BLOCK_SCAN_WARP_SCANS>;
58
+ static constexpr int kSmemIOSize = std::max({sizeof(typename BlockLoadT::TempStorage),
59
+ sizeof(typename BlockLoadVecT::TempStorage),
60
+ (int(kIsVariableB) + int(kIsVariableC)) * sizeof(typename BlockLoadWeightT::TempStorage),
61
+ (int(kIsVariableB) + int(kIsVariableC)) * sizeof(typename BlockLoadWeightVecT::TempStorage),
62
+ sizeof(typename BlockStoreT::TempStorage),
63
+ sizeof(typename BlockStoreVecT::TempStorage)});
64
+ static constexpr int kSmemSize = kSmemIOSize + sizeof(typename BlockScanT::TempStorage);
65
+ };
66
+
67
+ template<typename Ktraits>
68
+ __global__ __launch_bounds__(Ktraits::kNThreads, Ktraits::kMinBlocks)
69
+ void selective_scan_fwd_kernel(SSMParamsBase params) {
70
+ constexpr bool kIsComplex = Ktraits::kIsComplex;
71
+ constexpr bool kIsVariableB = Ktraits::kIsVariableB;
72
+ constexpr bool kIsVariableC = Ktraits::kIsVariableC;
73
+ constexpr bool kHasZ = Ktraits::kHasZ;
74
+ constexpr int kNThreads = Ktraits::kNThreads;
75
+ constexpr int kNItems = Ktraits::kNItems;
76
+ constexpr int kNRows = Ktraits::kNRows;
77
+ constexpr bool kDirectIO = Ktraits::kDirectIO;
78
+ using input_t = typename Ktraits::input_t;
79
+ using weight_t = typename Ktraits::weight_t;
80
+ using scan_t = typename Ktraits::scan_t;
81
+
82
+ // Shared memory.
83
+ extern __shared__ char smem_[];
84
+ // cast to lvalue reference of expected type
85
+ // char *smem_loadstorescan = smem_ + 2 * MAX_DSTATE * sizeof(weight_t);
86
+ // auto& smem_load = reinterpret_cast<typename BlockLoadT::TempStorage&>(smem_ + 2 * MAX_DSTATE * sizeof(weight_t));
87
+ // auto& smem_load = reinterpret_cast<typename BlockLoadT::TempStorage&>(smem_loadstorescan);
88
+ auto& smem_load = reinterpret_cast<typename Ktraits::BlockLoadT::TempStorage&>(smem_);
89
+ auto& smem_load_weight = reinterpret_cast<typename Ktraits::BlockLoadWeightT::TempStorage&>(smem_);
90
+ auto& smem_load_weight1 = *reinterpret_cast<typename Ktraits::BlockLoadWeightT::TempStorage*>(smem_ + sizeof(typename Ktraits::BlockLoadWeightT::TempStorage));
91
+ auto& smem_store = reinterpret_cast<typename Ktraits::BlockStoreT::TempStorage&>(smem_);
92
+ auto& smem_scan = *reinterpret_cast<typename Ktraits::BlockScanT::TempStorage*>(smem_ + Ktraits::kSmemIOSize);
93
+ // weight_t *smem_a = reinterpret_cast<weight_t *>(smem_ + smem_loadstorescan_size);
94
+ // weight_t *smem_bc = reinterpret_cast<weight_t *>(smem_a + MAX_DSTATE);
95
+ scan_t *smem_running_prefix = reinterpret_cast<scan_t *>(smem_ + Ktraits::kSmemSize);
96
+
97
+ const int batch_id = blockIdx.x;
98
+ const int dim_id = blockIdx.y;
99
+ const int group_id = dim_id / (params.dim_ngroups_ratio);
100
+ input_t *u = reinterpret_cast<input_t *>(params.u_ptr) + batch_id * params.u_batch_stride
101
+ + dim_id * kNRows * params.u_d_stride;
102
+ input_t *delta = reinterpret_cast<input_t *>(params.delta_ptr) + batch_id * params.delta_batch_stride
103
+ + dim_id * kNRows * params.delta_d_stride;
104
+ weight_t *A = reinterpret_cast<weight_t *>(params.A_ptr) + dim_id * kNRows * params.A_d_stride;
105
+ weight_t *B = reinterpret_cast<weight_t *>(params.B_ptr) + dim_id * kNRows * params.B_d_stride;
106
+ input_t *Bvar = reinterpret_cast<input_t *>(params.B_ptr) + batch_id * params.B_batch_stride + group_id * params.B_group_stride;
107
+ weight_t *C = reinterpret_cast<weight_t *>(params.C_ptr) + dim_id * kNRows * params.C_d_stride;
108
+ input_t *Cvar = reinterpret_cast<input_t *>(params.C_ptr) + batch_id * params.C_batch_stride + group_id * params.C_group_stride;
109
+ scan_t *x = reinterpret_cast<scan_t *>(params.x_ptr) + (batch_id * params.dim + dim_id * kNRows) * params.n_chunks * params.dstate;
110
+
111
+ float D_val[kNRows] = {0};
112
+ if (params.D_ptr != nullptr) {
113
+ #pragma unroll
114
+ for (int r = 0; r < kNRows; ++r) {
115
+ D_val[r] = reinterpret_cast<float *>(params.D_ptr)[dim_id * kNRows + r];
116
+ }
117
+ }
118
+ float delta_bias[kNRows] = {0};
119
+ if (params.delta_bias_ptr != nullptr) {
120
+ #pragma unroll
121
+ for (int r = 0; r < kNRows; ++r) {
122
+ delta_bias[r] = reinterpret_cast<float *>(params.delta_bias_ptr)[dim_id * kNRows + r];
123
+ }
124
+ }
125
+
126
+ // for (int state_idx = threadIdx.x; state_idx < params.dstate; state_idx += blockDim.x) {
127
+ // smem_a[state_idx] = A[state_idx * params.A_dstate_stride];
128
+ // smem_bc[state_idx] = B[state_idx * params.B_dstate_stride] * C[state_idx * params.C_dstate_stride];
129
+ // }
130
+
131
+ constexpr int kChunkSize = kNThreads * kNItems;
132
+ for (int chunk = 0; chunk < params.n_chunks; ++chunk) {
133
+ input_t u_vals[kNRows][kNItems], delta_vals_load[kNRows][kNItems];
134
+ __syncthreads();
135
+ #pragma unroll
136
+ for (int r = 0; r < kNRows; ++r) {
137
+ if constexpr (!kDirectIO) {
138
+ if (r > 0) { __syncthreads(); }
139
+ }
140
+ load_input<Ktraits>(u + r * params.u_d_stride, u_vals[r], smem_load, params.seqlen - chunk * kChunkSize);
141
+ if constexpr (!kDirectIO) { __syncthreads(); }
142
+ load_input<Ktraits>(delta + r * params.delta_d_stride, delta_vals_load[r], smem_load, params.seqlen - chunk * kChunkSize);
143
+ }
144
+ u += kChunkSize;
145
+ delta += kChunkSize;
146
+
147
+ float delta_vals[kNRows][kNItems], delta_u_vals[kNRows][kNItems], out_vals[kNRows][kNItems];
148
+ #pragma unroll
149
+ for (int r = 0; r < kNRows; ++r) {
150
+ #pragma unroll
151
+ for (int i = 0; i < kNItems; ++i) {
152
+ float u_val = float(u_vals[r][i]);
153
+ delta_vals[r][i] = float(delta_vals_load[r][i]) + delta_bias[r];
154
+ if (params.delta_softplus) {
155
+ delta_vals[r][i] = delta_vals[r][i] <= 20.f ? log1pf(expf(delta_vals[r][i])) : delta_vals[r][i];
156
+ }
157
+ delta_u_vals[r][i] = delta_vals[r][i] * u_val;
158
+ out_vals[r][i] = D_val[r] * u_val;
159
+ }
160
+ }
161
+
162
+ __syncthreads();
163
+ for (int state_idx = 0; state_idx < params.dstate; ++state_idx) {
164
+ weight_t A_val[kNRows];
165
+ #pragma unroll
166
+ for (int r = 0; r < kNRows; ++r) {
167
+ A_val[r] = A[state_idx * params.A_dstate_stride + r * params.A_d_stride];
168
+ // Multiply the real part of A with LOG2E so we can use exp2f instead of expf.
169
+ constexpr float kLog2e = M_LOG2E;
170
+ if constexpr (!kIsComplex) {
171
+ A_val[r] *= kLog2e;
172
+ } else {
173
+ A_val[r].real_ *= kLog2e;
174
+ }
175
+ }
176
+ // This variable holds B * C if both B and C are constant across seqlen. If only B varies
177
+ // across seqlen, this holds C. If only C varies across seqlen, this holds B.
178
+ // If both B and C vary, this is unused.
179
+ weight_t BC_val[kNRows];
180
+ weight_t B_vals[kNItems], C_vals[kNItems];
181
+ if constexpr (kIsVariableB) {
182
+ load_weight<Ktraits>(Bvar + state_idx * params.B_dstate_stride, B_vals,
183
+ smem_load_weight, (params.seqlen - chunk * kChunkSize) * (!kIsComplex ? 1 : 2));
184
+ if constexpr (!kIsVariableC) {
185
+ #pragma unroll
186
+ for (int r = 0; r < kNRows; ++r) {
187
+ BC_val[r] = C[state_idx * params.C_dstate_stride + r * params.C_d_stride];
188
+ }
189
+ }
190
+ }
191
+ if constexpr (kIsVariableC) {
192
+ auto &smem_load_weight_C = !kIsVariableB ? smem_load_weight : smem_load_weight1;
193
+ load_weight<Ktraits>(Cvar + state_idx * params.C_dstate_stride, C_vals,
194
+ smem_load_weight_C, (params.seqlen - chunk * kChunkSize) * (!kIsComplex ? 1 : 2));
195
+ if constexpr (!kIsVariableB) {
196
+ #pragma unroll
197
+ for (int r = 0; r < kNRows; ++r) {
198
+ BC_val[r] = B[state_idx * params.B_dstate_stride + r * params.B_d_stride];
199
+ }
200
+ }
201
+ }
202
+ if constexpr (!kIsVariableB && !kIsVariableC) {
203
+ #pragma unroll
204
+ for (int r = 0; r < kNRows; ++r) {
205
+ 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];
206
+ }
207
+ }
208
+
209
+ #pragma unroll
210
+ for (int r = 0; r < kNRows; ++r) {
211
+ if (r > 0) { __syncthreads(); } // Scan could be using the same smem
212
+ scan_t thread_data[kNItems];
213
+ #pragma unroll
214
+ for (int i = 0; i < kNItems; ++i) {
215
+ if constexpr (!kIsComplex) {
216
+ thread_data[i] = make_float2(exp2f(delta_vals[r][i] * A_val[r]),
217
+ !kIsVariableB ? delta_u_vals[r][i] : B_vals[i] * delta_u_vals[r][i]);
218
+ if constexpr (!Ktraits::kIsEvenLen) { // So that the last state is correct
219
+ if (threadIdx.x * kNItems + i >= params.seqlen - chunk * kChunkSize) {
220
+ thread_data[i] = make_float2(1.f, 0.f);
221
+ }
222
+ }
223
+ } else {
224
+ // Pytorch's implementation of complex exp (which calls thrust) is very slow
225
+ complex_t delta_a_exp = cexp2f(delta_vals[r][i] * A_val[r]);
226
+ weight_t B_delta_u_val = !kIsVariableB ? delta_u_vals[r][i] : B_vals[i] * delta_u_vals[r][i];
227
+ thread_data[i] = make_float4(delta_a_exp.real_, delta_a_exp.imag_, B_delta_u_val.real_, B_delta_u_val.imag_);
228
+ if constexpr (!Ktraits::kIsEvenLen) { // So that the last state is correct
229
+ if (threadIdx.x * kNItems + i >= params.seqlen - chunk * kChunkSize) {
230
+ thread_data[i] = make_float4(1.f, 0.f, 0.f, 0.f);
231
+ }
232
+ }
233
+ }
234
+ }
235
+ // Initialize running total
236
+ scan_t running_prefix;
237
+ if constexpr (!kIsComplex) {
238
+ // If we use WARP_SCAN then all lane 0 of all warps (not just thread 0) needs to read
239
+ running_prefix = chunk > 0 && threadIdx.x % 32 == 0 ? smem_running_prefix[state_idx + r * MAX_DSTATE] : make_float2(1.f, 0.f);
240
+ // running_prefix = chunk > 0 && threadIdx.x == 0 ? smem_running_prefix[state_idx] : make_float2(1.f, 0.f);
241
+ } else {
242
+ 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);
243
+ // running_prefix = chunk > 0 && threadIdx.x == 0 ? smem_running_prefix[state_idx] : make_float4(1.f, 0.f, 0.f, 0.f);
244
+ }
245
+ SSMScanPrefixCallbackOp<weight_t> prefix_op(running_prefix);
246
+ Ktraits::BlockScanT(smem_scan).InclusiveScan(
247
+ thread_data, thread_data, SSMScanOp<weight_t>(), prefix_op
248
+ );
249
+ // There's a syncthreads in the scan op, so we don't need to sync here.
250
+ // Unless there's only 1 warp, but then it's the same thread (0) reading and writing.
251
+ if (threadIdx.x == 0) {
252
+ smem_running_prefix[state_idx] = prefix_op.running_prefix;
253
+ x[(r * params.n_chunks + chunk) * params.dstate + state_idx] = prefix_op.running_prefix;
254
+ }
255
+ #pragma unroll
256
+ for (int i = 0; i < kNItems; ++i) {
257
+ const weight_t C_val = !kIsVariableC
258
+ ? BC_val[r]
259
+ : (!kIsVariableB ? BC_val[r] * C_vals[i] : C_vals[i]);
260
+ if constexpr (!kIsComplex) {
261
+ out_vals[r][i] += thread_data[i].y * C_val;
262
+ } else {
263
+ out_vals[r][i] += (complex_t(thread_data[i].z, thread_data[i].w) * C_val).real_ * 2;
264
+ }
265
+ }
266
+ }
267
+ }
268
+
269
+ input_t *out = reinterpret_cast<input_t *>(params.out_ptr) + batch_id * params.out_batch_stride
270
+ + dim_id * kNRows * params.out_d_stride + chunk * kChunkSize;
271
+ __syncthreads();
272
+ #pragma unroll
273
+ for (int r = 0; r < kNRows; ++r) {
274
+ if constexpr (!kDirectIO) {
275
+ if (r > 0) { __syncthreads(); }
276
+ }
277
+ store_output<Ktraits>(out + r * params.out_d_stride, out_vals[r], smem_store, params.seqlen - chunk * kChunkSize);
278
+ }
279
+
280
+ if constexpr (kHasZ) {
281
+ input_t *z = reinterpret_cast<input_t *>(params.z_ptr) + batch_id * params.z_batch_stride
282
+ + dim_id * kNRows * params.z_d_stride + chunk * kChunkSize;
283
+ input_t *out_z = reinterpret_cast<input_t *>(params.out_z_ptr) + batch_id * params.out_z_batch_stride
284
+ + dim_id * kNRows * params.out_z_d_stride + chunk * kChunkSize;
285
+ #pragma unroll
286
+ for (int r = 0; r < kNRows; ++r) {
287
+ input_t z_vals[kNItems];
288
+ __syncthreads();
289
+ load_input<Ktraits>(z + r * params.z_d_stride, z_vals, smem_load, params.seqlen - chunk * kChunkSize);
290
+ #pragma unroll
291
+ for (int i = 0; i < kNItems; ++i) {
292
+ float z_val = z_vals[i];
293
+ out_vals[r][i] *= z_val / (1 + expf(-z_val));
294
+ }
295
+ __syncthreads();
296
+ store_output<Ktraits>(out_z + r * params.out_z_d_stride, out_vals[r], smem_store, params.seqlen - chunk * kChunkSize);
297
+ }
298
+ }
299
+
300
+ Bvar += kChunkSize * (!kIsComplex ? 1 : 2);
301
+ Cvar += kChunkSize * (!kIsComplex ? 1 : 2);
302
+ }
303
+ }
304
+
305
+ template<int kNThreads, int kNItems, typename input_t, typename weight_t>
306
+ void selective_scan_fwd_launch(SSMParamsBase &params, cudaStream_t stream) {
307
+ // Only kNRows == 1 is tested for now, which ofc doesn't differ from previously when we had each block
308
+ // processing 1 row.
309
+ constexpr int kNRows = 1;
310
+ BOOL_SWITCH(params.seqlen % (kNThreads * kNItems) == 0, kIsEvenLen, [&] {
311
+ BOOL_SWITCH(params.is_variable_B, kIsVariableB, [&] {
312
+ BOOL_SWITCH(params.is_variable_C, kIsVariableC, [&] {
313
+ BOOL_SWITCH(params.z_ptr != nullptr , kHasZ, [&] {
314
+ using Ktraits = Selective_Scan_fwd_kernel_traits<kNThreads, kNItems, kNRows, kIsEvenLen, kIsVariableB, kIsVariableC, kHasZ, input_t, weight_t>;
315
+ // constexpr int kSmemSize = Ktraits::kSmemSize;
316
+ constexpr int kSmemSize = Ktraits::kSmemSize + kNRows * MAX_DSTATE * sizeof(typename Ktraits::scan_t);
317
+ // printf("smem_size = %d\n", kSmemSize);
318
+ dim3 grid(params.batch, params.dim / kNRows);
319
+ auto kernel = &selective_scan_fwd_kernel<Ktraits>;
320
+ if (kSmemSize >= 48 * 1024) {
321
+ C10_CUDA_CHECK(cudaFuncSetAttribute(
322
+ kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kSmemSize));
323
+ }
324
+ kernel<<<grid, Ktraits::kNThreads, kSmemSize, stream>>>(params);
325
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
326
+ });
327
+ });
328
+ });
329
+ });
330
+ }
331
+
332
+ template<typename input_t, typename weight_t>
333
+ void selective_scan_fwd_cuda(SSMParamsBase &params, cudaStream_t stream) {
334
+ if (params.seqlen <= 128) {
335
+ selective_scan_fwd_launch<32, 4, input_t, weight_t>(params, stream);
336
+ } else if (params.seqlen <= 256) {
337
+ selective_scan_fwd_launch<32, 8, input_t, weight_t>(params, stream);
338
+ } else if (params.seqlen <= 512) {
339
+ selective_scan_fwd_launch<32, 16, input_t, weight_t>(params, stream);
340
+ } else if (params.seqlen <= 1024) {
341
+ selective_scan_fwd_launch<64, 16, input_t, weight_t>(params, stream);
342
+ } else {
343
+ selective_scan_fwd_launch<128, 16, input_t, weight_t>(params, stream);
344
+ }
345
+ }
source_code/SegMamba/mamba/csrc/selective_scan/static_switch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Inspired by https://github.com/NVIDIA/DALI/blob/main/include/dali/core/static_switch.h
2
+ // and https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Dispatch.h
3
+
4
+ #pragma once
5
+
6
+ /// @param COND - a boolean expression to switch by
7
+ /// @param CONST_NAME - a name given for the constexpr bool variable.
8
+ /// @param ... - code to execute for true and false
9
+ ///
10
+ /// Usage:
11
+ /// ```
12
+ /// BOOL_SWITCH(flag, BoolConst, [&] {
13
+ /// some_function<BoolConst>(...);
14
+ /// });
15
+ /// ```
16
+ #define BOOL_SWITCH(COND, CONST_NAME, ...) \
17
+ [&] { \
18
+ if (COND) { \
19
+ constexpr bool CONST_NAME = true; \
20
+ return __VA_ARGS__(); \
21
+ } else { \
22
+ constexpr bool CONST_NAME = false; \
23
+ return __VA_ARGS__(); \
24
+ } \
25
+ }()
source_code/SegMamba/mamba/csrc/selective_scan/uninitialized_copy.cuh ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved.
3
+ *
4
+ * Redistribution and use in source and binary forms, with or without
5
+ * modification, are permitted provided that the following conditions are met:
6
+ * * Redistributions of source code must retain the above copyright
7
+ * notice, this list of conditions and the following disclaimer.
8
+ * * Redistributions in binary form must reproduce the above copyright
9
+ * notice, this list of conditions and the following disclaimer in the
10
+ * documentation and/or other materials provided with the distribution.
11
+ * * Neither the name of the NVIDIA CORPORATION nor the
12
+ * names of its contributors may be used to endorse or promote products
13
+ * derived from this software without specific prior written permission.
14
+ *
15
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18
+ * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
19
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
+ *
26
+ ******************************************************************************/
27
+
28
+ #pragma once
29
+
30
+ #include <cub/config.cuh>
31
+
32
+ #include <cuda/std/type_traits>
33
+
34
+
35
+ namespace detail
36
+ {
37
+
38
+ #if defined(_NVHPC_CUDA)
39
+ template <typename T, typename U>
40
+ __host__ __device__ void uninitialized_copy(T *ptr, U &&val)
41
+ {
42
+ // NVBug 3384810
43
+ new (ptr) T(::cuda::std::forward<U>(val));
44
+ }
45
+ #else
46
+ template <typename T,
47
+ typename U,
48
+ typename ::cuda::std::enable_if<
49
+ ::cuda::std::is_trivially_copyable<T>::value,
50
+ int
51
+ >::type = 0>
52
+ __host__ __device__ void uninitialized_copy(T *ptr, U &&val)
53
+ {
54
+ *ptr = ::cuda::std::forward<U>(val);
55
+ }
56
+
57
+ template <typename T,
58
+ typename U,
59
+ typename ::cuda::std::enable_if<
60
+ !::cuda::std::is_trivially_copyable<T>::value,
61
+ int
62
+ >::type = 0>
63
+ __host__ __device__ void uninitialized_copy(T *ptr, U &&val)
64
+ {
65
+ new (ptr) T(::cuda::std::forward<U>(val));
66
+ }
67
+ #endif
68
+
69
+ } // namespace detail
source_code/SegMamba/mamba/mamba_ssm/models/mixer_seq_simple.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Albert Gu, Tri Dao.
2
+
3
+ import math
4
+ from functools import partial
5
+
6
+ from collections import namedtuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ from mamba_ssm.modules.mamba_simple import Mamba, Block
12
+ from mamba_ssm.utils.generation import GenerationMixin
13
+ from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
14
+
15
+ try:
16
+ from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
17
+ except ImportError:
18
+ RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
19
+
20
+
21
+ def create_block(
22
+ d_model,
23
+ ssm_cfg=None,
24
+ norm_epsilon=1e-5,
25
+ rms_norm=False,
26
+ residual_in_fp32=False,
27
+ fused_add_norm=False,
28
+ layer_idx=None,
29
+ device=None,
30
+ dtype=None,
31
+ ):
32
+ if ssm_cfg is None:
33
+ ssm_cfg = {}
34
+ factory_kwargs = {"device": device, "dtype": dtype}
35
+ mixer_cls = partial(Mamba, layer_idx=layer_idx, **ssm_cfg, **factory_kwargs)
36
+ norm_cls = partial(
37
+ nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
38
+ )
39
+ block = Block(
40
+ d_model,
41
+ mixer_cls,
42
+ norm_cls=norm_cls,
43
+ fused_add_norm=fused_add_norm,
44
+ residual_in_fp32=residual_in_fp32,
45
+ )
46
+ block.layer_idx = layer_idx
47
+ return block
48
+
49
+
50
+ # https://github.com/huggingface/transformers/blob/c28d04e9e252a1a099944e325685f14d242ecdcd/src/transformers/models/gpt2/modeling_gpt2.py#L454
51
+ def _init_weights(
52
+ module,
53
+ n_layer,
54
+ initializer_range=0.02, # Now only used for embedding layer.
55
+ rescale_prenorm_residual=True,
56
+ n_residuals_per_layer=1, # Change to 2 if we have MLP
57
+ ):
58
+ if isinstance(module, nn.Linear):
59
+ if module.bias is not None:
60
+ if not getattr(module.bias, "_no_reinit", False):
61
+ nn.init.zeros_(module.bias)
62
+ elif isinstance(module, nn.Embedding):
63
+ nn.init.normal_(module.weight, std=initializer_range)
64
+
65
+ if rescale_prenorm_residual:
66
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
67
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
68
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
69
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
70
+ #
71
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
72
+ for name, p in module.named_parameters():
73
+ if name in ["out_proj.weight", "fc2.weight"]:
74
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
75
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
76
+ # We need to reinit p since this code could be called multiple times
77
+ # Having just p *= scale would repeatedly scale it down
78
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
79
+ with torch.no_grad():
80
+ p /= math.sqrt(n_residuals_per_layer * n_layer)
81
+
82
+
83
+ class MixerModel(nn.Module):
84
+ def __init__(
85
+ self,
86
+ d_model: int,
87
+ n_layer: int,
88
+ vocab_size: int,
89
+ ssm_cfg=None,
90
+ norm_epsilon: float = 1e-5,
91
+ rms_norm: bool = False,
92
+ initializer_cfg=None,
93
+ fused_add_norm=False,
94
+ residual_in_fp32=False,
95
+ device=None,
96
+ dtype=None,
97
+ ) -> None:
98
+ factory_kwargs = {"device": device, "dtype": dtype}
99
+ super().__init__()
100
+ self.residual_in_fp32 = residual_in_fp32
101
+
102
+ self.embedding = nn.Embedding(vocab_size, d_model, **factory_kwargs)
103
+
104
+ # We change the order of residual and layer norm:
105
+ # Instead of LN -> Attn / MLP -> Add, we do:
106
+ # Add -> LN -> Attn / MLP / Mixer, returning both the residual branch (output of Add) and
107
+ # the main branch (output of MLP / Mixer). The model definition is unchanged.
108
+ # This is for performance reason: we can fuse add + layer_norm.
109
+ self.fused_add_norm = fused_add_norm
110
+ if self.fused_add_norm:
111
+ if layer_norm_fn is None or rms_norm_fn is None:
112
+ raise ImportError("Failed to import Triton LayerNorm / RMSNorm kernels")
113
+
114
+ self.layers = nn.ModuleList(
115
+ [
116
+ create_block(
117
+ d_model,
118
+ ssm_cfg=ssm_cfg,
119
+ norm_epsilon=norm_epsilon,
120
+ rms_norm=rms_norm,
121
+ residual_in_fp32=residual_in_fp32,
122
+ fused_add_norm=fused_add_norm,
123
+ layer_idx=i,
124
+ **factory_kwargs,
125
+ )
126
+ for i in range(n_layer)
127
+ ]
128
+ )
129
+
130
+ self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
131
+ d_model, eps=norm_epsilon, **factory_kwargs
132
+ )
133
+
134
+ self.apply(
135
+ partial(
136
+ _init_weights,
137
+ n_layer=n_layer,
138
+ **(initializer_cfg if initializer_cfg is not None else {}),
139
+ )
140
+ )
141
+
142
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
143
+ return {
144
+ i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
145
+ for i, layer in enumerate(self.layers)
146
+ }
147
+
148
+ def forward(self, input_ids, inference_params=None):
149
+ hidden_states = self.embedding(input_ids)
150
+ residual = None
151
+ for layer in self.layers:
152
+ hidden_states, residual = layer(
153
+ hidden_states, residual, inference_params=inference_params
154
+ )
155
+ if not self.fused_add_norm:
156
+ residual = (hidden_states + residual) if residual is not None else hidden_states
157
+ hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
158
+ else:
159
+ # Set prenorm=False here since we don't need the residual
160
+ fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
161
+ hidden_states = fused_add_norm_fn(
162
+ hidden_states,
163
+ self.norm_f.weight,
164
+ self.norm_f.bias,
165
+ eps=self.norm_f.eps,
166
+ residual=residual,
167
+ prenorm=False,
168
+ residual_in_fp32=self.residual_in_fp32,
169
+ )
170
+ return hidden_states
171
+
172
+
173
+ class MambaLMHeadModel(nn.Module, GenerationMixin):
174
+
175
+ def __init__(
176
+ self,
177
+ d_model: int,
178
+ n_layer: int,
179
+ vocab_size: int,
180
+ initializer_cfg=None,
181
+ pad_vocab_size_multiple: int = 1,
182
+ device=None,
183
+ dtype=None,
184
+ **backbone_kwargs,
185
+ ) -> None:
186
+ factory_kwargs = {"device": device, "dtype": dtype}
187
+ super().__init__()
188
+ if vocab_size % pad_vocab_size_multiple != 0:
189
+ vocab_size += pad_vocab_size_multiple - (vocab_size % pad_vocab_size_multiple)
190
+ self.backbone = MixerModel(
191
+ d_model=d_model,
192
+ n_layer=n_layer,
193
+ vocab_size=vocab_size,
194
+ initializer_cfg=initializer_cfg,
195
+ **backbone_kwargs,
196
+ **factory_kwargs,
197
+ )
198
+ self.lm_head = nn.Linear(d_model, vocab_size, bias=False, **factory_kwargs)
199
+
200
+ # Initialize weights and apply final processing
201
+ self.apply(
202
+ partial(
203
+ _init_weights,
204
+ n_layer=n_layer,
205
+ **(initializer_cfg if initializer_cfg is not None else {}),
206
+ )
207
+ )
208
+ self.tie_weights()
209
+
210
+ def tie_weights(self):
211
+ self.lm_head.weight = self.backbone.embedding.weight
212
+
213
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
214
+ return self.backbone.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
215
+
216
+ def forward(self, input_ids, position_ids=None, inference_params=None, num_last_tokens=0):
217
+ """
218
+ "position_ids" is just to be compatible with Transformer generation. We don't use it.
219
+ num_last_tokens: if > 0, only return the logits for the last n tokens
220
+ """
221
+ hidden_states = self.backbone(input_ids, inference_params=inference_params)
222
+ if num_last_tokens > 0:
223
+ hidden_states = hidden_states[:, -num_last_tokens:]
224
+ lm_logits = self.lm_head(hidden_states)
225
+ CausalLMOutput = namedtuple("CausalLMOutput", ["logits"])
226
+ return CausalLMOutput(logits=lm_logits)
227
+
228
+ @classmethod
229
+ def from_pretrained(cls, pretrained_model_name, device=None, dtype=None, **kwargs):
230
+ config = load_config_hf(pretrained_model_name)
231
+ model = cls(**config, device=device, dtype=dtype, **kwargs)
232
+ model.load_state_dict(load_state_dict_hf(pretrained_model_name, device=device, dtype=dtype))
233
+ return model
source_code/SegMamba/mamba/mamba_ssm/ops/triton/layernorm.py ADDED
@@ -0,0 +1,636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+ # Implement residual + layer_norm / rms_norm.
3
+
4
+ # Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
5
+ # For the backward pass, we keep weight_grad and bias_grad in registers and accumulate.
6
+ # This is faster for dimensions up to 8k, but after that it's much slower due to register spilling.
7
+ # The models we train have hidden dim up to 8k anyway (e.g. Llama 70B), so this is fine.
8
+
9
+ import math
10
+
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from torch.cuda.amp import custom_fwd, custom_bwd
14
+
15
+ import triton
16
+ import triton.language as tl
17
+
18
+
19
+ def layer_norm_ref(x, weight, bias, residual=None, eps=1e-6, prenorm=False, upcast=False):
20
+ dtype = x.dtype
21
+ if upcast:
22
+ weight = weight.float()
23
+ bias = bias.float() if bias is not None else None
24
+ if upcast:
25
+ x = x.float()
26
+ residual = residual.float() if residual is not None else residual
27
+ if residual is not None:
28
+ x = (x + residual).to(x.dtype)
29
+ out = F.layer_norm(x.to(weight.dtype), x.shape[-1:], weight=weight, bias=bias, eps=eps).to(
30
+ dtype
31
+ )
32
+ return out if not prenorm else (out, x)
33
+
34
+
35
+ def rms_norm_ref(x, weight, bias, residual=None, eps=1e-6, prenorm=False, upcast=False):
36
+ dtype = x.dtype
37
+ if upcast:
38
+ weight = weight.float()
39
+ bias = bias.float() if bias is not None else None
40
+ if upcast:
41
+ x = x.float()
42
+ residual = residual.float() if residual is not None else residual
43
+ if residual is not None:
44
+ x = (x + residual).to(x.dtype)
45
+ rstd = 1 / torch.sqrt((x.square()).mean(dim=-1, keepdim=True) + eps)
46
+ out = (x * rstd * weight) + bias if bias is not None else (x * rstd * weight)
47
+ out = out.to(dtype)
48
+ return out if not prenorm else (out, x)
49
+
50
+
51
+ @triton.autotune(
52
+ configs=[
53
+ triton.Config({}, num_warps=1),
54
+ triton.Config({}, num_warps=2),
55
+ triton.Config({}, num_warps=4),
56
+ triton.Config({}, num_warps=8),
57
+ triton.Config({}, num_warps=16),
58
+ triton.Config({}, num_warps=32),
59
+ ],
60
+ key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS"],
61
+ )
62
+ # @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None})
63
+ # @triton.heuristics({"HAS_RESIDUAL": lambda args: args["RESIDUAL"] is not None})
64
+ @triton.jit
65
+ def _layer_norm_fwd_1pass_kernel(
66
+ X, # pointer to the input
67
+ Y, # pointer to the output
68
+ W, # pointer to the weights
69
+ B, # pointer to the biases
70
+ RESIDUAL, # pointer to the residual
71
+ RESIDUAL_OUT, # pointer to the residual
72
+ Mean, # pointer to the mean
73
+ Rstd, # pointer to the 1/std
74
+ stride_x_row, # how much to increase the pointer when moving by 1 row
75
+ stride_y_row,
76
+ stride_res_row,
77
+ stride_res_out_row,
78
+ N, # number of columns in X
79
+ eps, # epsilon to avoid division by zero
80
+ IS_RMS_NORM: tl.constexpr,
81
+ BLOCK_N: tl.constexpr,
82
+ HAS_RESIDUAL: tl.constexpr,
83
+ STORE_RESIDUAL_OUT: tl.constexpr,
84
+ HAS_BIAS: tl.constexpr,
85
+ ):
86
+ # Map the program id to the row of X and Y it should compute.
87
+ row = tl.program_id(0)
88
+ X += row * stride_x_row
89
+ Y += row * stride_y_row
90
+ if HAS_RESIDUAL:
91
+ RESIDUAL += row * stride_res_row
92
+ if STORE_RESIDUAL_OUT:
93
+ RESIDUAL_OUT += row * stride_res_out_row
94
+ # Compute mean and variance
95
+ cols = tl.arange(0, BLOCK_N)
96
+ x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32)
97
+ if HAS_RESIDUAL:
98
+ residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32)
99
+ x += residual
100
+ if STORE_RESIDUAL_OUT:
101
+ tl.store(RESIDUAL_OUT + cols, x, mask=cols < N)
102
+ if not IS_RMS_NORM:
103
+ mean = tl.sum(x, axis=0) / N
104
+ tl.store(Mean + row, mean)
105
+ xbar = tl.where(cols < N, x - mean, 0.0)
106
+ var = tl.sum(xbar * xbar, axis=0) / N
107
+ else:
108
+ xbar = tl.where(cols < N, x, 0.0)
109
+ var = tl.sum(xbar * xbar, axis=0) / N
110
+ rstd = 1 / tl.sqrt(var + eps)
111
+ tl.store(Rstd + row, rstd)
112
+ # Normalize and apply linear transformation
113
+ mask = cols < N
114
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
115
+ if HAS_BIAS:
116
+ b = tl.load(B + cols, mask=mask).to(tl.float32)
117
+ x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
118
+ y = x_hat * w + b if HAS_BIAS else x_hat * w
119
+ # Write output
120
+ tl.store(Y + cols, y, mask=mask)
121
+
122
+
123
+ def _layer_norm_fwd(
124
+ x, weight, bias, eps, residual=None, out_dtype=None, residual_dtype=None, is_rms_norm=False
125
+ ):
126
+ if residual is not None:
127
+ residual_dtype = residual.dtype
128
+ M, N = x.shape
129
+ assert x.stride(-1) == 1
130
+ if residual is not None:
131
+ assert residual.stride(-1) == 1
132
+ assert residual.shape == (M, N)
133
+ assert weight.shape == (N,)
134
+ assert weight.stride(-1) == 1
135
+ if bias is not None:
136
+ assert bias.stride(-1) == 1
137
+ assert bias.shape == (N,)
138
+ # allocate output
139
+ y = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype)
140
+ assert y.stride(-1) == 1
141
+ if residual is not None or (residual_dtype is not None and residual_dtype != x.dtype):
142
+ residual_out = torch.empty(M, N, device=x.device, dtype=residual_dtype)
143
+ assert residual_out.stride(-1) == 1
144
+ else:
145
+ residual_out = None
146
+ mean = torch.empty((M,), dtype=torch.float32, device="cuda") if not is_rms_norm else None
147
+ rstd = torch.empty((M,), dtype=torch.float32, device="cuda")
148
+ # Less than 64KB per feature: enqueue fused kernel
149
+ MAX_FUSED_SIZE = 65536 // x.element_size()
150
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
151
+ if N > BLOCK_N:
152
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
153
+ # heuristics for number of warps
154
+ with torch.cuda.device(x.device.index):
155
+ _layer_norm_fwd_1pass_kernel[(M,)](
156
+ x,
157
+ y,
158
+ weight,
159
+ bias,
160
+ residual,
161
+ residual_out,
162
+ mean,
163
+ rstd,
164
+ x.stride(0),
165
+ y.stride(0),
166
+ residual.stride(0) if residual is not None else 0,
167
+ residual_out.stride(0) if residual_out is not None else 0,
168
+ N,
169
+ eps,
170
+ is_rms_norm,
171
+ BLOCK_N,
172
+ residual is not None,
173
+ residual_out is not None,
174
+ bias is not None,
175
+ )
176
+ # residual_out is None if residual is None and residual_dtype == input_dtype
177
+ return y, mean, rstd, residual_out if residual_out is not None else x
178
+
179
+
180
+ @triton.autotune(
181
+ configs=[
182
+ triton.Config({}, num_warps=1),
183
+ triton.Config({}, num_warps=2),
184
+ triton.Config({}, num_warps=4),
185
+ triton.Config({}, num_warps=8),
186
+ triton.Config({}, num_warps=16),
187
+ triton.Config({}, num_warps=32),
188
+ ],
189
+ key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS"],
190
+ )
191
+ # @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None})
192
+ # @triton.heuristics({"HAS_DRESIDUAL": lambda args: args["DRESIDUAL"] is not None})
193
+ # @triton.heuristics({"STORE_DRESIDUAL": lambda args: args["DRESIDUAL_IN"] is not None})
194
+ @triton.heuristics({"RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None})
195
+ @triton.jit
196
+ def _layer_norm_bwd_kernel(
197
+ X, # pointer to the input
198
+ W, # pointer to the weights
199
+ B, # pointer to the biases
200
+ Y, # pointer to the output to be recomputed
201
+ DY, # pointer to the output gradient
202
+ DX, # pointer to the input gradient
203
+ DW, # pointer to the partial sum of weights gradient
204
+ DB, # pointer to the partial sum of biases gradient
205
+ DRESIDUAL,
206
+ DRESIDUAL_IN,
207
+ Mean, # pointer to the mean
208
+ Rstd, # pointer to the 1/std
209
+ stride_x_row, # how much to increase the pointer when moving by 1 row
210
+ stride_y_row,
211
+ stride_dy_row,
212
+ stride_dx_row,
213
+ stride_dres_row,
214
+ stride_dres_in_row,
215
+ M, # number of rows in X
216
+ N, # number of columns in X
217
+ eps, # epsilon to avoid division by zero
218
+ rows_per_program,
219
+ IS_RMS_NORM: tl.constexpr,
220
+ BLOCK_N: tl.constexpr,
221
+ HAS_DRESIDUAL: tl.constexpr,
222
+ STORE_DRESIDUAL: tl.constexpr,
223
+ HAS_BIAS: tl.constexpr,
224
+ RECOMPUTE_OUTPUT: tl.constexpr,
225
+ ):
226
+ # Map the program id to the elements of X, DX, and DY it should compute.
227
+ row_block_id = tl.program_id(0)
228
+ row_start = row_block_id * rows_per_program
229
+ cols = tl.arange(0, BLOCK_N)
230
+ mask = cols < N
231
+ X += row_start * stride_x_row
232
+ if HAS_DRESIDUAL:
233
+ DRESIDUAL += row_start * stride_dres_row
234
+ if STORE_DRESIDUAL:
235
+ DRESIDUAL_IN += row_start * stride_dres_in_row
236
+ DY += row_start * stride_dy_row
237
+ DX += row_start * stride_dx_row
238
+ if RECOMPUTE_OUTPUT:
239
+ Y += row_start * stride_y_row
240
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
241
+ if RECOMPUTE_OUTPUT and HAS_BIAS:
242
+ b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32)
243
+ dw = tl.zeros((BLOCK_N,), dtype=tl.float32)
244
+ if HAS_BIAS:
245
+ db = tl.zeros((BLOCK_N,), dtype=tl.float32)
246
+ row_end = min((row_block_id + 1) * rows_per_program, M)
247
+ for row in range(row_start, row_end):
248
+ # Load data to SRAM
249
+ x = tl.load(X + cols, mask=mask, other=0).to(tl.float32)
250
+ dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32)
251
+ if not IS_RMS_NORM:
252
+ mean = tl.load(Mean + row)
253
+ rstd = tl.load(Rstd + row)
254
+ # Compute dx
255
+ xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
256
+ xhat = tl.where(mask, xhat, 0.0)
257
+ if RECOMPUTE_OUTPUT:
258
+ y = xhat * w + b if HAS_BIAS else xhat * w
259
+ tl.store(Y + cols, y, mask=mask)
260
+ wdy = w * dy
261
+ dw += dy * xhat
262
+ if HAS_BIAS:
263
+ db += dy
264
+ if not IS_RMS_NORM:
265
+ c1 = tl.sum(xhat * wdy, axis=0) / N
266
+ c2 = tl.sum(wdy, axis=0) / N
267
+ dx = (wdy - (xhat * c1 + c2)) * rstd
268
+ else:
269
+ c1 = tl.sum(xhat * wdy, axis=0) / N
270
+ dx = (wdy - xhat * c1) * rstd
271
+ if HAS_DRESIDUAL:
272
+ dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32)
273
+ dx += dres
274
+ # Write dx
275
+ if STORE_DRESIDUAL:
276
+ tl.store(DRESIDUAL_IN + cols, dx, mask=mask)
277
+ tl.store(DX + cols, dx, mask=mask)
278
+
279
+ X += stride_x_row
280
+ if HAS_DRESIDUAL:
281
+ DRESIDUAL += stride_dres_row
282
+ if STORE_DRESIDUAL:
283
+ DRESIDUAL_IN += stride_dres_in_row
284
+ if RECOMPUTE_OUTPUT:
285
+ Y += stride_y_row
286
+ DY += stride_dy_row
287
+ DX += stride_dx_row
288
+ tl.store(DW + row_block_id * N + cols, dw, mask=mask)
289
+ if HAS_BIAS:
290
+ tl.store(DB + row_block_id * N + cols, db, mask=mask)
291
+
292
+
293
+ def _layer_norm_bwd(
294
+ dy,
295
+ x,
296
+ weight,
297
+ bias,
298
+ eps,
299
+ mean,
300
+ rstd,
301
+ dresidual=None,
302
+ has_residual=False,
303
+ is_rms_norm=False,
304
+ x_dtype=None,
305
+ recompute_output=False,
306
+ ):
307
+ M, N = x.shape
308
+ assert x.stride(-1) == 1
309
+ assert dy.stride(-1) == 1
310
+ assert dy.shape == (M, N)
311
+ if dresidual is not None:
312
+ assert dresidual.stride(-1) == 1
313
+ assert dresidual.shape == (M, N)
314
+ assert weight.shape == (N,)
315
+ assert weight.stride(-1) == 1
316
+ if bias is not None:
317
+ assert bias.stride(-1) == 1
318
+ assert bias.shape == (N,)
319
+ # allocate output
320
+ dx = (
321
+ torch.empty_like(x)
322
+ if x_dtype is None
323
+ else torch.empty(M, N, dtype=x_dtype, device=x.device)
324
+ )
325
+ dresidual_in = torch.empty_like(x) if has_residual and dx.dtype != x.dtype else None
326
+ y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None
327
+
328
+ # Less than 64KB per feature: enqueue fused kernel
329
+ MAX_FUSED_SIZE = 65536 // x.element_size()
330
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
331
+ if N > BLOCK_N:
332
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
333
+ sm_count = torch.cuda.get_device_properties(x.device).multi_processor_count
334
+ _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device)
335
+ _db = (
336
+ torch.empty((sm_count, N), dtype=torch.float32, device=bias.device)
337
+ if bias is not None
338
+ else None
339
+ )
340
+ rows_per_program = math.ceil(M / sm_count)
341
+ grid = (sm_count,)
342
+ with torch.cuda.device(x.device.index):
343
+ _layer_norm_bwd_kernel[grid](
344
+ x,
345
+ weight,
346
+ bias,
347
+ y,
348
+ dy,
349
+ dx,
350
+ _dw,
351
+ _db,
352
+ dresidual,
353
+ dresidual_in,
354
+ mean,
355
+ rstd,
356
+ x.stride(0),
357
+ 0 if not recompute_output else y.stride(0),
358
+ dy.stride(0),
359
+ dx.stride(0),
360
+ dresidual.stride(0) if dresidual is not None else 0,
361
+ dresidual_in.stride(0) if dresidual_in is not None else 0,
362
+ M,
363
+ N,
364
+ eps,
365
+ rows_per_program,
366
+ is_rms_norm,
367
+ BLOCK_N,
368
+ dresidual is not None,
369
+ dresidual_in is not None,
370
+ bias is not None,
371
+ )
372
+ dw = _dw.sum(0).to(weight.dtype)
373
+ db = _db.sum(0).to(bias.dtype) if bias is not None else None
374
+ # Don't need to compute dresidual_in separately in this case
375
+ if has_residual and dx.dtype == x.dtype:
376
+ dresidual_in = dx
377
+ return (dx, dw, db, dresidual_in) if not recompute_output else (dx, dw, db, dresidual_in, y)
378
+
379
+
380
+ class LayerNormFn(torch.autograd.Function):
381
+ @staticmethod
382
+ def forward(
383
+ ctx,
384
+ x,
385
+ weight,
386
+ bias,
387
+ residual=None,
388
+ eps=1e-6,
389
+ prenorm=False,
390
+ residual_in_fp32=False,
391
+ is_rms_norm=False,
392
+ ):
393
+ x_shape_og = x.shape
394
+ # reshape input data into 2D tensor
395
+ x = x.reshape(-1, x.shape[-1])
396
+ if x.stride(-1) != 1:
397
+ x = x.contiguous()
398
+ if residual is not None:
399
+ assert residual.shape == x_shape_og
400
+ residual = residual.reshape(-1, residual.shape[-1])
401
+ if residual.stride(-1) != 1:
402
+ residual = residual.contiguous()
403
+ weight = weight.contiguous()
404
+ if bias is not None:
405
+ bias = bias.contiguous()
406
+ residual_dtype = (
407
+ residual.dtype
408
+ if residual is not None
409
+ else (torch.float32 if residual_in_fp32 else None)
410
+ )
411
+ y, mean, rstd, residual_out = _layer_norm_fwd(
412
+ x, weight, bias, eps, residual, residual_dtype=residual_dtype, is_rms_norm=is_rms_norm
413
+ )
414
+ ctx.save_for_backward(residual_out, weight, bias, mean, rstd)
415
+ ctx.x_shape_og = x_shape_og
416
+ ctx.eps = eps
417
+ ctx.is_rms_norm = is_rms_norm
418
+ ctx.has_residual = residual is not None
419
+ ctx.prenorm = prenorm
420
+ ctx.x_dtype = x.dtype
421
+ y = y.reshape(x_shape_og)
422
+ return y if not prenorm else (y, residual_out.reshape(x_shape_og))
423
+
424
+ @staticmethod
425
+ def backward(ctx, dy, *args):
426
+ x, weight, bias, mean, rstd = ctx.saved_tensors
427
+ dy = dy.reshape(-1, dy.shape[-1])
428
+ if dy.stride(-1) != 1:
429
+ dy = dy.contiguous()
430
+ assert dy.shape == x.shape
431
+ if ctx.prenorm:
432
+ dresidual = args[0]
433
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
434
+ if dresidual.stride(-1) != 1:
435
+ dresidual = dresidual.contiguous()
436
+ assert dresidual.shape == x.shape
437
+ else:
438
+ dresidual = None
439
+ dx, dw, db, dresidual_in = _layer_norm_bwd(
440
+ dy,
441
+ x,
442
+ weight,
443
+ bias,
444
+ ctx.eps,
445
+ mean,
446
+ rstd,
447
+ dresidual,
448
+ ctx.has_residual,
449
+ ctx.is_rms_norm,
450
+ x_dtype=ctx.x_dtype,
451
+ )
452
+ return (
453
+ dx.reshape(ctx.x_shape_og),
454
+ dw,
455
+ db,
456
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
457
+ None,
458
+ None,
459
+ None,
460
+ None,
461
+ )
462
+
463
+
464
+ def layer_norm_fn(
465
+ x,
466
+ weight,
467
+ bias,
468
+ residual=None,
469
+ eps=1e-6,
470
+ prenorm=False,
471
+ residual_in_fp32=False,
472
+ is_rms_norm=False,
473
+ ):
474
+ return LayerNormFn.apply(x, weight, bias, residual, eps, prenorm, residual_in_fp32, is_rms_norm)
475
+
476
+
477
+ def rms_norm_fn(x, weight, bias, residual=None, prenorm=False, residual_in_fp32=False, eps=1e-6):
478
+ return LayerNormFn.apply(x, weight, bias, residual, eps, prenorm, residual_in_fp32, True)
479
+
480
+
481
+ class RMSNorm(torch.nn.Module):
482
+ def __init__(self, hidden_size, eps=1e-5, device=None, dtype=None):
483
+ factory_kwargs = {"device": device, "dtype": dtype}
484
+ super().__init__()
485
+ self.eps = eps
486
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
487
+ self.register_parameter("bias", None)
488
+ self.reset_parameters()
489
+
490
+ def reset_parameters(self):
491
+ torch.nn.init.ones_(self.weight)
492
+
493
+ def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False):
494
+ return rms_norm_fn(
495
+ x,
496
+ self.weight,
497
+ self.bias,
498
+ residual=residual,
499
+ eps=self.eps,
500
+ prenorm=prenorm,
501
+ residual_in_fp32=residual_in_fp32,
502
+ is_rms_norm=True,
503
+ )
504
+
505
+
506
+ class LayerNormLinearFn(torch.autograd.Function):
507
+ @staticmethod
508
+ @custom_fwd
509
+ def forward(
510
+ ctx,
511
+ x,
512
+ norm_weight,
513
+ norm_bias,
514
+ linear_weight,
515
+ linear_bias,
516
+ residual=None,
517
+ eps=1e-6,
518
+ prenorm=False,
519
+ residual_in_fp32=False,
520
+ is_rms_norm=False,
521
+ ):
522
+ x_shape_og = x.shape
523
+ # reshape input data into 2D tensor
524
+ x = x.reshape(-1, x.shape[-1])
525
+ if x.stride(-1) != 1:
526
+ x = x.contiguous()
527
+ if residual is not None:
528
+ assert residual.shape == x_shape_og
529
+ residual = residual.reshape(-1, residual.shape[-1])
530
+ if residual.stride(-1) != 1:
531
+ residual = residual.contiguous()
532
+ norm_weight = norm_weight.contiguous()
533
+ if norm_bias is not None:
534
+ norm_bias = norm_bias.contiguous()
535
+ residual_dtype = (
536
+ residual.dtype
537
+ if residual is not None
538
+ else (torch.float32 if residual_in_fp32 else None)
539
+ )
540
+ y, mean, rstd, residual_out = _layer_norm_fwd(
541
+ x,
542
+ norm_weight,
543
+ norm_bias,
544
+ eps,
545
+ residual,
546
+ out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype(),
547
+ residual_dtype=residual_dtype,
548
+ is_rms_norm=is_rms_norm,
549
+ )
550
+ y = y.reshape(x_shape_og)
551
+ dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else y.dtype
552
+ linear_weight = linear_weight.to(dtype)
553
+ linear_bias = linear_bias.to(dtype) if linear_bias is not None else None
554
+ out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias)
555
+ # We don't store y, will be recomputed in the backward pass to save memory
556
+ ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd)
557
+ ctx.x_shape_og = x_shape_og
558
+ ctx.eps = eps
559
+ ctx.is_rms_norm = is_rms_norm
560
+ ctx.has_residual = residual is not None
561
+ ctx.prenorm = prenorm
562
+ ctx.x_dtype = x.dtype
563
+ ctx.linear_bias_is_none = linear_bias is None
564
+ return out if not prenorm else (out, residual_out.reshape(x_shape_og))
565
+
566
+ @staticmethod
567
+ @custom_bwd
568
+ def backward(ctx, dout, *args):
569
+ x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors
570
+ dout = dout.reshape(-1, dout.shape[-1])
571
+ dy = F.linear(dout, linear_weight.t())
572
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
573
+ if dy.stride(-1) != 1:
574
+ dy = dy.contiguous()
575
+ assert dy.shape == x.shape
576
+ if ctx.prenorm:
577
+ dresidual = args[0]
578
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
579
+ if dresidual.stride(-1) != 1:
580
+ dresidual = dresidual.contiguous()
581
+ assert dresidual.shape == x.shape
582
+ else:
583
+ dresidual = None
584
+ dx, dnorm_weight, dnorm_bias, dresidual_in, y = _layer_norm_bwd(
585
+ dy,
586
+ x,
587
+ norm_weight,
588
+ norm_bias,
589
+ ctx.eps,
590
+ mean,
591
+ rstd,
592
+ dresidual,
593
+ ctx.has_residual,
594
+ ctx.is_rms_norm,
595
+ x_dtype=ctx.x_dtype,
596
+ recompute_output=True,
597
+ )
598
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, y)
599
+ return (
600
+ dx.reshape(ctx.x_shape_og),
601
+ dnorm_weight,
602
+ dnorm_bias,
603
+ dlinear_weight,
604
+ dlinear_bias,
605
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
606
+ None,
607
+ None,
608
+ None,
609
+ None,
610
+ )
611
+
612
+
613
+ def layer_norm_linear_fn(
614
+ x,
615
+ norm_weight,
616
+ norm_bias,
617
+ linear_weight,
618
+ linear_bias,
619
+ residual=None,
620
+ eps=1e-6,
621
+ prenorm=False,
622
+ residual_in_fp32=False,
623
+ is_rms_norm=False,
624
+ ):
625
+ return LayerNormLinearFn.apply(
626
+ x,
627
+ norm_weight,
628
+ norm_bias,
629
+ linear_weight,
630
+ linear_bias,
631
+ residual,
632
+ eps,
633
+ prenorm,
634
+ residual_in_fp32,
635
+ is_rms_norm,
636
+ )
source_code/SegMamba/mamba/mamba_ssm/ops/triton/selective_state_update.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ """We want triton==2.1.0 for this
4
+ """
5
+
6
+ import math
7
+ import torch
8
+ import torch.nn.functional as F
9
+
10
+ import triton
11
+ import triton.language as tl
12
+
13
+ from einops import rearrange, repeat
14
+
15
+
16
+ @triton.heuristics({"HAS_DT_BIAS": lambda args: args["dt_bias_ptr"] is not None})
17
+ @triton.heuristics({"HAS_D": lambda args: args["D_ptr"] is not None})
18
+ @triton.heuristics({"HAS_Z": lambda args: args["z_ptr"] is not None})
19
+ @triton.heuristics({"BLOCK_SIZE_DSTATE": lambda args: triton.next_power_of_2(args["dstate"])})
20
+ @triton.jit
21
+ def _selective_scan_update_kernel(
22
+ # Pointers to matrices
23
+ state_ptr, x_ptr, dt_ptr, dt_bias_ptr, A_ptr, B_ptr, C_ptr, D_ptr, z_ptr, out_ptr,
24
+ # Matrix dimensions
25
+ batch, dim, dstate,
26
+ # Strides
27
+ stride_state_batch, stride_state_dim, stride_state_dstate,
28
+ stride_x_batch, stride_x_dim,
29
+ stride_dt_batch, stride_dt_dim,
30
+ stride_dt_bias_dim,
31
+ stride_A_dim, stride_A_dstate,
32
+ stride_B_batch, stride_B_dstate,
33
+ stride_C_batch, stride_C_dstate,
34
+ stride_D_dim,
35
+ stride_z_batch, stride_z_dim,
36
+ stride_out_batch, stride_out_dim,
37
+ # Meta-parameters
38
+ DT_SOFTPLUS: tl.constexpr,
39
+ BLOCK_SIZE_M: tl.constexpr,
40
+ HAS_DT_BIAS: tl.constexpr,
41
+ HAS_D: tl.constexpr,
42
+ HAS_Z: tl.constexpr,
43
+ BLOCK_SIZE_DSTATE: tl.constexpr,
44
+ ):
45
+ pid_m = tl.program_id(axis=0)
46
+ pid_b = tl.program_id(axis=1)
47
+ state_ptr += pid_b * stride_state_batch
48
+ x_ptr += pid_b * stride_x_batch
49
+ dt_ptr += pid_b * stride_dt_batch
50
+ B_ptr += pid_b * stride_B_batch
51
+ C_ptr += pid_b * stride_C_batch
52
+ if HAS_Z:
53
+ z_ptr += pid_b * stride_z_batch
54
+ out_ptr += pid_b * stride_out_batch
55
+
56
+ offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
57
+ offs_n = tl.arange(0, BLOCK_SIZE_DSTATE)
58
+ state_ptrs = state_ptr + (offs_m[:, None] * stride_state_dim + offs_n[None, :] * stride_state_dstate)
59
+ x_ptrs = x_ptr + offs_m * stride_x_dim
60
+ dt_ptrs = dt_ptr + offs_m * stride_dt_dim
61
+ if HAS_DT_BIAS:
62
+ dt_bias_ptrs = dt_bias_ptr + offs_m * stride_dt_bias_dim
63
+ A_ptrs = A_ptr + (offs_m[:, None] * stride_A_dim + offs_n[None, :] * stride_A_dstate)
64
+ B_ptrs = B_ptr + offs_n * stride_B_dstate
65
+ C_ptrs = C_ptr + offs_n * stride_C_dstate
66
+ if HAS_D:
67
+ D_ptrs = D_ptr + offs_m * stride_D_dim
68
+ if HAS_Z:
69
+ z_ptrs = z_ptr + offs_m * stride_z_dim
70
+ out_ptrs = out_ptr + offs_m * stride_out_dim
71
+
72
+ state = tl.load(state_ptrs, mask=(offs_m[:, None] < dim) & (offs_n[None, :] < dstate), other=0.0)
73
+ x = tl.load(x_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32)
74
+ dt = tl.load(dt_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32)
75
+ if HAS_DT_BIAS:
76
+ dt += tl.load(dt_bias_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32)
77
+ if DT_SOFTPLUS:
78
+ dt = tl.log(1.0 + tl.exp(dt))
79
+ A = tl.load(A_ptrs, mask=(offs_m[:, None] < dim) & (offs_n[None, :] < dstate), other=0.0).to(tl.float32)
80
+ dA = tl.exp(A * dt[:, None])
81
+ B = tl.load(B_ptrs, mask=offs_n < dstate, other=0.0).to(tl.float32)
82
+ C = tl.load(C_ptrs, mask=offs_n < dstate, other=0.0).to(tl.float32)
83
+ if HAS_D:
84
+ D = tl.load(D_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32)
85
+ if HAS_Z:
86
+ z = tl.load(z_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32)
87
+
88
+ dB = B[None, :] * dt[:, None]
89
+ state = state * dA + dB * x[:, None]
90
+ tl.store(state_ptrs, state, mask=(offs_m[:, None] < dim) & (offs_n[None, :] < dstate))
91
+ out = tl.sum(state * C[None, :], axis=1)
92
+ if HAS_D:
93
+ out += x * D
94
+ if HAS_Z:
95
+ out *= z * tl.sigmoid(z)
96
+ tl.store(out_ptrs, out, mask=offs_m < dim)
97
+
98
+
99
+ def selective_state_update(state, x, dt, A, B, C, D=None, z=None, dt_bias=None, dt_softplus=False):
100
+ """
101
+ Argument:
102
+ state: (batch, dim, dstate)
103
+ x: (batch, dim)
104
+ dt: (batch, dim)
105
+ A: (dim, dstate)
106
+ B: (batch, dstate)
107
+ C: (batch, dstate)
108
+ D: (dim,)
109
+ z: (batch, dim)
110
+ dt_bias: (dim,)
111
+ Return:
112
+ out: (batch, dim)
113
+ """
114
+ batch, dim, dstate = state.shape
115
+ assert x.shape == (batch, dim)
116
+ assert dt.shape == x.shape
117
+ assert A.shape == (dim, dstate)
118
+ assert B.shape == (batch, dstate)
119
+ assert C.shape == B.shape
120
+ if D is not None:
121
+ assert D.shape == (dim,)
122
+ if z is not None:
123
+ assert z.shape == x.shape
124
+ if dt_bias is not None:
125
+ assert dt_bias.shape == (dim,)
126
+ out = torch.empty_like(x)
127
+ grid = lambda META: (triton.cdiv(dim, META['BLOCK_SIZE_M']), batch)
128
+ z_strides = ((z.stride(0), z.stride(1)) if z is not None else (0, 0))
129
+ # We don't want autotune since it will overwrite the state
130
+ # We instead tune by hand.
131
+ BLOCK_SIZE_M, num_warps = ((32, 4) if dstate <= 16
132
+ else ((16, 4) if dstate <= 32 else
133
+ ((8, 4) if dstate <= 64 else
134
+ ((4, 4) if dstate <= 128 else
135
+ ((4, 8))))))
136
+ with torch.cuda.device(x.device.index):
137
+ _selective_scan_update_kernel[grid](
138
+ state, x, dt, dt_bias, A, B, C, D, z, out,
139
+ batch, dim, dstate,
140
+ state.stride(0), state.stride(1), state.stride(2),
141
+ x.stride(0), x.stride(1),
142
+ dt.stride(0), dt.stride(1),
143
+ dt_bias.stride(0) if dt_bias is not None else 0,
144
+ A.stride(0), A.stride(1),
145
+ B.stride(0), B.stride(1),
146
+ C.stride(0), C.stride(1),
147
+ D.stride(0) if D is not None else 0,
148
+ z_strides[0], z_strides[1],
149
+ out.stride(0), out.stride(1),
150
+ dt_softplus,
151
+ BLOCK_SIZE_M,
152
+ num_warps=num_warps,
153
+ )
154
+ return out
155
+
156
+
157
+ def selective_state_update_ref(state, x, dt, A, B, C, D=None, z=None, dt_bias=None, dt_softplus=False):
158
+ """
159
+ Argument:
160
+ state: (batch, dim, dstate)
161
+ x: (batch, dim)
162
+ dt: (batch, dim)
163
+ A: (dim, dstate)
164
+ B: (batch, dstate)
165
+ C: (batch, dstate)
166
+ D: (dim,)
167
+ z: (batch, dim)
168
+ dt_bias: (dim,)
169
+ Return:
170
+ out: (batch, dim)
171
+ """
172
+ batch, dim, dstate = state.shape
173
+ assert x.shape == (batch, dim)
174
+ assert dt.shape == x.shape
175
+ assert A.shape == (dim, dstate)
176
+ assert B.shape == (batch, dstate)
177
+ assert C.shape == B.shape
178
+ if D is not None:
179
+ assert D.shape == (dim,)
180
+ if z is not None:
181
+ assert z.shape == x.shape
182
+ if dt_bias is not None:
183
+ assert dt_bias.shape == (dim,)
184
+ dt = dt + dt_bias
185
+ dt = F.softplus(dt) if dt_softplus else dt
186
+ dA = torch.exp(rearrange(dt, "b d -> b d 1") * A) # (batch, dim, dstate)
187
+ dB = rearrange(dt, "b d -> b d 1") * rearrange(B, "b n -> b 1 n") # (batch, dim, dstate)
188
+ state.copy_(state * dA + dB * rearrange(x, "b d -> b d 1")) # (batch, dim, dstate
189
+ out = torch.einsum("bdn,bn->bd", state.to(C.dtype), C)
190
+ if D is not None:
191
+ out += (x * D).to(out.dtype)
192
+ return (out if z is None else out * F.silu(z)).to(x.dtype)
source_code/SegMamba/mamba/mamba_ssm/utils/generation.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Albert Gu, Tri Dao.
2
+ import gc
3
+ import time
4
+ from collections import namedtuple
5
+ from dataclasses import dataclass, field
6
+ from functools import partial
7
+ from typing import Callable, Optional, Sequence, Union
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from einops import rearrange, repeat
12
+ from torch import Tensor
13
+ from torch.profiler import ProfilerActivity, profile, record_function
14
+ from transformers.generation import GreedySearchDecoderOnlyOutput, SampleDecoderOnlyOutput
15
+
16
+
17
+ @dataclass
18
+ class InferenceParams:
19
+ """Inference parameters that are passed to the main model in order
20
+ to efficienly calculate and store the context during inference."""
21
+
22
+ max_seqlen: int
23
+ max_batch_size: int
24
+ seqlen_offset: int = 0
25
+ batch_size_offset: int = 0
26
+ key_value_memory_dict: dict = field(default_factory=dict)
27
+ lengths_per_sample: Optional[Tensor] = None
28
+
29
+ def reset(self, max_seqlen, max_batch_size):
30
+ self.max_seqlen = max_seqlen
31
+ self.max_batch_size = max_batch_size
32
+ self.seqlen_offset = 0
33
+ if self.lengths_per_sample is not None:
34
+ self.lengths_per_sample.zero_()
35
+
36
+
37
+ # https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/sampling.py
38
+ # https://github.com/huggingface/transformers/blob/a44985b41cfa2de48a5e1de7f1f93b7483da25d1/src/transformers/generation/logits_process.py#L231
39
+ def modify_logits_for_top_k_filtering(logits, top_k):
40
+ """Set the logits for none top-k values to -inf. Done in-place."""
41
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
42
+ logits.masked_fill_(indices_to_remove, float("-Inf"))
43
+
44
+
45
+ # https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/sampling.py
46
+ # https://github.com/huggingface/transformers/blob/a44985b41cfa2de48a5e1de7f1f93b7483da25d1/src/transformers/generation/logits_process.py#L170
47
+ def modify_logits_for_top_p_filtering(logits, top_p):
48
+ """Set the logits for none top-p values to -inf. Done in-place."""
49
+ if top_p <= 0.0 or top_p >= 1.0:
50
+ return
51
+ # First sort and calculate cumulative sum of probabilities.
52
+ sorted_logits, sorted_indices = torch.sort(logits, descending=False)
53
+ cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
54
+ # Remove tokens with cumulative top_p above the threshold (token with 0 are kept)
55
+ sorted_indices_to_remove = cumulative_probs <= (1 - top_p)
56
+ # scatter sorted tensors to original indexing
57
+ indices_to_remove = sorted_indices_to_remove.scatter(
58
+ 1, sorted_indices, sorted_indices_to_remove
59
+ )
60
+ logits.masked_fill_(indices_to_remove, float("-inf"))
61
+
62
+
63
+ def sample(logits, top_k=1, top_p=0.0, temperature=1.0):
64
+ """Sample from top-k logits.
65
+ Arguments:
66
+ logits: Tensor of shape (batch_size, vocab_size)
67
+ """
68
+ if top_k == 1: # Short-circuit for greedy decoding
69
+ return logits.argmax(dim=-1)
70
+ else:
71
+ if top_p > 0.0:
72
+ assert top_p <= 1.0, "top-p should be in (0, 1]."
73
+ if top_k > 0:
74
+ top_k = min(top_k, logits.size(-1)) # Safety check
75
+ logits_top, indices = torch.topk(logits, top_k, dim=-1)
76
+ if temperature != 1.0:
77
+ logits_top /= temperature
78
+ modify_logits_for_top_p_filtering(logits_top, top_p)
79
+ return indices[
80
+ torch.arange(indices.shape[0], device=indices.device),
81
+ torch.multinomial(torch.softmax(logits_top, dim=-1), num_samples=1).squeeze(dim=-1),
82
+ ]
83
+ else:
84
+ # Clone so that when we modify for top_p we don't change the original logits
85
+ logits_top = logits / temperature if temperature != 1.0 else logits.clone()
86
+ modify_logits_for_top_p_filtering(logits_top, top_p)
87
+ return torch.multinomial(torch.softmax(logits_top, dim=-1), num_samples=1).squeeze(
88
+ dim=-1
89
+ )
90
+
91
+
92
+ @torch.inference_mode()
93
+ def decode(
94
+ input_ids,
95
+ model,
96
+ max_length,
97
+ top_k=1,
98
+ top_p=0.0,
99
+ temperature=1.0,
100
+ eos_token_id=None,
101
+ teacher_outputs=None,
102
+ vocab_size=None,
103
+ tensor_parallel=1,
104
+ cg=False,
105
+ enable_timing=False,
106
+ ):
107
+ """Decoding, either greedy or with top-k or top-p sampling.
108
+ If top-k = 0, don't limit the number of candidates (pure sampling).
109
+ Top-k and top-p can be used together. If top_k > 0 and top_p > 0, then top-k is applied first,
110
+ then top-p.
111
+ We assume that all sequences in the same batch have the same length.
112
+
113
+ Arguments:
114
+ input_ids: (batch, seq_len)
115
+ max_length: int
116
+ teacher_outputs (optional): (batch, seq_len). If provided, instead of sampling from the
117
+ logits, the next token is taken from the teacher_outputs. Useful for testing.
118
+ Returns: GreedySearchDecoderOnlyOutput or SampleDecoderOnlyOutput, with the following fields:
119
+ sequences: (batch, max_length)
120
+ scores: tuples of (batch, vocab_size)
121
+ """
122
+ batch_size, seqlen_og = input_ids.shape
123
+ teacher_output_len = teacher_outputs.shape[1] if teacher_outputs is not None else 0
124
+ if cg:
125
+ if not hasattr(model, "_decoding_cache"):
126
+ model._decoding_cache = None
127
+ model._decoding_cache = update_graph_cache(
128
+ model,
129
+ model._decoding_cache,
130
+ batch_size,
131
+ seqlen_og,
132
+ max_length,
133
+ tensor_parallel=tensor_parallel,
134
+ )
135
+ inference_params = model._decoding_cache.inference_params
136
+ inference_params.reset(max_length, batch_size)
137
+ else:
138
+ inference_params = InferenceParams(max_seqlen=max_length, max_batch_size=batch_size)
139
+
140
+ def get_logits(input_ids, inference_params):
141
+ decoding = inference_params.seqlen_offset > 0
142
+ if decoding:
143
+ position_ids = torch.full(
144
+ (batch_size, 1),
145
+ inference_params.seqlen_offset,
146
+ dtype=torch.long,
147
+ device=input_ids.device,
148
+ )
149
+ else:
150
+ position_ids = None
151
+ if not cg or not decoding:
152
+ logits = model(
153
+ input_ids,
154
+ position_ids=position_ids,
155
+ inference_params=inference_params,
156
+ num_last_tokens=1,
157
+ ).logits.squeeze(dim=1)
158
+ else:
159
+ logits = model._decoding_cache.run(
160
+ input_ids, position_ids, inference_params.seqlen_offset
161
+ ).squeeze(dim=1)
162
+ return logits[..., :vocab_size] if vocab_size is not None else logits
163
+
164
+ def sample_tokens(logits, inference_params):
165
+ if teacher_outputs is None or teacher_output_len <= inference_params.seqlen_offset:
166
+ token = sample(logits, top_k=top_k, top_p=top_p, temperature=temperature)
167
+ else:
168
+ token = teacher_outputs[:, inference_params.seqlen_offset]
169
+ # return rearrange(token, "b -> b 1")
170
+ return token.unsqueeze(1)
171
+
172
+ def should_stop(current_token, inference_params):
173
+ if inference_params.seqlen_offset == 0:
174
+ return False
175
+ if eos_token_id is not None and (current_token == eos_token_id).all():
176
+ return True
177
+ if inference_params.seqlen_offset >= max_length - 1:
178
+ return True
179
+ return False
180
+
181
+ start = torch.cuda.Event(enable_timing=enable_timing)
182
+ end = torch.cuda.Event(enable_timing=enable_timing)
183
+
184
+ if enable_timing:
185
+ if tensor_parallel > 1:
186
+ torch.distributed.barrier()
187
+ start.record()
188
+ scores, sequences = [], [input_ids]
189
+ while not should_stop(sequences[-1], inference_params):
190
+ scores.append(get_logits(sequences[-1], inference_params))
191
+ inference_params.seqlen_offset += sequences[-1].shape[1]
192
+ sequences.append(sample_tokens(scores[-1], inference_params))
193
+ if enable_timing:
194
+ end.record()
195
+ if tensor_parallel > 1:
196
+ torch.distributed.barrier()
197
+ torch.cuda.synchronize()
198
+ print(f"Prompt processing + decoding time: {(start.elapsed_time(end)):.0f}ms")
199
+ output_cls = GreedySearchDecoderOnlyOutput if top_k == 1 else SampleDecoderOnlyOutput
200
+ return output_cls(sequences=torch.cat(sequences, dim=1), scores=tuple(scores))
201
+
202
+
203
+ class GenerationMixin:
204
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
205
+ raise NotImplementedError
206
+
207
+ def generate(
208
+ self,
209
+ input_ids,
210
+ max_length,
211
+ top_k=1,
212
+ top_p=0.0,
213
+ temperature=1.0,
214
+ return_dict_in_generate=False,
215
+ output_scores=False,
216
+ **kwargs,
217
+ ):
218
+ output = decode(
219
+ input_ids, self, max_length, top_k=top_k, top_p=top_p, temperature=temperature, **kwargs
220
+ )
221
+ if not output_scores:
222
+ output.scores = None
223
+ return output if return_dict_in_generate else output.sequences
224
+
225
+
226
+ def allocate_inference_cache(
227
+ max_batch_size,
228
+ max_seqlen,
229
+ nheads,
230
+ headdim,
231
+ layers: Union[int, Sequence],
232
+ device,
233
+ dtype=torch.float16,
234
+ ):
235
+ assert dtype in [torch.float16, torch.bfloat16, torch.float32]
236
+ kv_cache_shape = (max_batch_size, max_seqlen, 2, nheads, headdim)
237
+ if isinstance(layers, int):
238
+ layers = range(layers)
239
+ return {i: torch.empty(kv_cache_shape, device=device, dtype=dtype) for i in layers}
240
+
241
+
242
+ @dataclass
243
+ class DecodingCGCache:
244
+ max_batch_size: int = 0
245
+ max_seqlen: int = 0
246
+ device = None
247
+ dtype = None
248
+ callables: dict = field(default_factory=dict)
249
+ mempool = None
250
+ inference_params: Optional[InferenceParams] = None
251
+ run: Optional[Callable] = None
252
+
253
+
254
+ @torch.inference_mode()
255
+ def update_graph_cache(
256
+ model,
257
+ cache,
258
+ batch_size,
259
+ seqlen_og,
260
+ max_seqlen,
261
+ decoding_seqlens=(1,),
262
+ tensor_parallel=1,
263
+ dtype=None,
264
+ n_warmups=2,
265
+ ):
266
+ if cache is None:
267
+ cache = DecodingCGCache()
268
+ param_example = next(iter(model.parameters()))
269
+ device = param_example.device
270
+ if dtype is None:
271
+ dtype = param_example.dtype
272
+ if (
273
+ (device, dtype) != (cache.device, cache.dtype)
274
+ or batch_size > cache.max_batch_size
275
+ or max_seqlen > cache.max_seqlen
276
+ ): # Invalidate the cache
277
+ cache.callables = {}
278
+ cache.mempool = None
279
+ cache.inference_params = None
280
+ gc.collect()
281
+ cache.device, cache.dtype = device, dtype
282
+ cache.max_batch_size, cache.max_seqlen = batch_size, max_seqlen
283
+ if hasattr(model, "allocate_inference_cache"):
284
+ inf_cache = model.allocate_inference_cache(batch_size, max_seqlen, dtype)
285
+ else:
286
+ headdim = getattr(
287
+ model.config,
288
+ "head_dim",
289
+ model.config.hidden_size // model.config.num_attention_heads,
290
+ )
291
+ inf_cache = allocate_inference_cache(
292
+ batch_size,
293
+ max_seqlen,
294
+ model.config.num_attention_heads // tensor_parallel,
295
+ headdim,
296
+ model.config.num_hidden_layers,
297
+ device,
298
+ dtype,
299
+ )
300
+ lengths_per_sample = torch.full((batch_size,), seqlen_og, dtype=torch.int32, device=device)
301
+ cache.inference_params = InferenceParams(
302
+ max_seqlen=max_seqlen,
303
+ max_batch_size=batch_size,
304
+ seqlen_offset=seqlen_og,
305
+ key_value_memory_dict=inf_cache,
306
+ lengths_per_sample=lengths_per_sample,
307
+ )
308
+ cache.mempool = torch.cuda.graphs.graph_pool_handle()
309
+ for decoding_seqlen in decoding_seqlens:
310
+ if (batch_size, decoding_seqlen) not in cache.callables:
311
+ cache.callables[batch_size, decoding_seqlen] = capture_graph(
312
+ model,
313
+ cache.inference_params,
314
+ batch_size,
315
+ max_seqlen,
316
+ decoding_seqlen=decoding_seqlen,
317
+ mempool=cache.mempool,
318
+ n_warmups=n_warmups,
319
+ )
320
+
321
+ def dispatch(input_ids, position_ids, seqlen):
322
+ batch_size, decoding_seqlen = input_ids.shape[:2]
323
+ return cache.callables[batch_size, decoding_seqlen](input_ids, position_ids, seqlen)
324
+
325
+ cache.run = dispatch
326
+ cache.inference_params.seqlen_offset = 0 # Reset so it's not confusing
327
+ return cache
328
+
329
+
330
+ def capture_graph(
331
+ model, inference_params, batch_size, max_seqlen, decoding_seqlen=1, mempool=None, n_warmups=2
332
+ ):
333
+ device = next(iter(model.parameters())).device
334
+ input_ids = torch.full((batch_size, decoding_seqlen), 0, dtype=torch.long, device=device)
335
+ position_ids = torch.full((batch_size, decoding_seqlen), 0, dtype=torch.long, device=device)
336
+ seqlen_offset_og = inference_params.seqlen_offset
337
+ inference_params.seqlen_offset = max_seqlen - decoding_seqlen
338
+ inference_params.lengths_per_sample[:] = inference_params.seqlen_offset
339
+
340
+ # Warmup before capture
341
+ s = torch.cuda.Stream()
342
+ s.wait_stream(torch.cuda.current_stream())
343
+ with torch.cuda.stream(s):
344
+ for _ in range(n_warmups):
345
+ logits = model(
346
+ input_ids,
347
+ position_ids=position_ids,
348
+ inference_params=inference_params,
349
+ num_last_tokens=decoding_seqlen,
350
+ ).logits
351
+ s.synchronize()
352
+ # This might be needed for correctness if we run with NCCL_GRAPH_MIXING_SUPPORT=0,
353
+ # which requires that graph launch and non-captured launch to not overlap (I think,
354
+ # that's how I interpret the documentation). I'm not sure if this is required.
355
+ if torch.distributed.is_initialized():
356
+ torch.distributed.barrier()
357
+ torch.cuda.current_stream().wait_stream(s)
358
+ # Captures the graph
359
+ # To allow capture, automatically sets a side stream as the current stream in the context
360
+ graph = torch.cuda.CUDAGraph()
361
+ with torch.cuda.graph(graph, pool=mempool):
362
+ logits = model(
363
+ input_ids,
364
+ position_ids=position_ids,
365
+ inference_params=inference_params,
366
+ num_last_tokens=decoding_seqlen,
367
+ ).logits
368
+
369
+ def run(new_input_ids, new_position_ids, seqlen):
370
+ inference_params.lengths_per_sample[:] = seqlen
371
+ input_ids.copy_(new_input_ids)
372
+ position_ids.copy_(new_position_ids)
373
+ graph.replay()
374
+ return logits.clone()
375
+
376
+ inference_params.seqlen_offset = seqlen_offset_og
377
+ return run
source_code/SegMamba/mamba/tests/ops/test_selective_scan.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2023, Tri Dao.
2
+
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch.autograd import gradcheck
8
+ import pytest
9
+
10
+ from einops import rearrange
11
+
12
+ from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_ref
13
+ from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, mamba_inner_ref
14
+ from mamba_ssm.ops.selective_scan_interface import bimamba_inner_fn, bimamba_inner_ref
15
+
16
+
17
+ # @pytest.mark.parametrize('wtype', [torch.float32, torch.complex64])
18
+ @pytest.mark.parametrize('wtype', [torch.float32])
19
+ # @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16])
20
+ @pytest.mark.parametrize('itype', [torch.float32])
21
+ # @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096])
22
+ @pytest.mark.parametrize('seqlen', [128, 256, 512, 1024, 2048, 4096])
23
+ # @pytest.mark.parametrize('seqlen', [128])
24
+ # @pytest.mark.parametrize("return_last_state", [False, True])
25
+ @pytest.mark.parametrize("return_last_state", [True])
26
+ # @pytest.mark.parametrize('has_delta_bias', [False, True])
27
+ @pytest.mark.parametrize('has_delta_bias', [True])
28
+ # @pytest.mark.parametrize('delta_softplus', [False, True])
29
+ @pytest.mark.parametrize('delta_softplus', [True])
30
+ # @pytest.mark.parametrize('has_z', [False, True])
31
+ @pytest.mark.parametrize('has_z', [True])
32
+ # @pytest.mark.parametrize('has_D', [False, True])
33
+ @pytest.mark.parametrize('has_D', [True])
34
+ @pytest.mark.parametrize("varBC_groups", [1, 2])
35
+ # @pytest.mark.parametrize("varBC_groups", [1])
36
+ # @pytest.mark.parametrize("is_variable_C", [False, True])
37
+ @pytest.mark.parametrize("is_variable_C", [True])
38
+ # @pytest.mark.parametrize("is_variable_B", [False, True])
39
+ @pytest.mark.parametrize("is_variable_B", [True])
40
+ def test_selective_scan(is_variable_B, is_variable_C, varBC_groups, has_D, has_z, has_delta_bias,
41
+ delta_softplus, return_last_state, seqlen, itype, wtype):
42
+ if varBC_groups > 1 and (not is_variable_B or not is_variable_C):
43
+ pytest.skip() # This config is not applicable
44
+ device = 'cuda'
45
+ rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3)
46
+ if itype == torch.bfloat16:
47
+ rtol, atol = 3e-2, 5e-2
48
+ rtolw, atolw = (1e-3, 1e-3)
49
+ if has_z: # If we have z, the errors on the weights seem higher
50
+ rtolw = max(rtolw, rtol)
51
+ atolw = max(atolw, atol)
52
+ # set seed
53
+ torch.random.manual_seed(0)
54
+ batch_size = 2
55
+ dim = 4
56
+ dstate = 8
57
+ is_complex = wtype == torch.complex64
58
+ A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_()
59
+ if not is_variable_B:
60
+ B_shape = (dim, dstate)
61
+ elif varBC_groups == 1:
62
+ B_shape = (batch_size, dstate, seqlen if not is_complex else seqlen * 2)
63
+ else:
64
+ B_shape = (batch_size, varBC_groups, dstate, seqlen if not is_complex else seqlen * 2)
65
+ B = torch.randn(*B_shape, device=device, dtype=wtype if not is_variable_B else itype,
66
+ requires_grad=True)
67
+ if not is_variable_C:
68
+ C_shape = (dim, dstate)
69
+ elif varBC_groups == 1:
70
+ C_shape = (batch_size, dstate, seqlen if not is_complex else seqlen * 2)
71
+ else:
72
+ C_shape = (batch_size, varBC_groups, dstate, seqlen if not is_complex else seqlen * 2)
73
+ C = torch.randn(*C_shape, device=device, dtype=wtype if not is_variable_C else itype,
74
+ requires_grad=True)
75
+ if has_D:
76
+ D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True)
77
+ else:
78
+ D = None
79
+ if has_z:
80
+ z = torch.randn(batch_size, dim, seqlen, device=device, dtype=itype, requires_grad=True)
81
+ else:
82
+ z = None
83
+ if has_delta_bias:
84
+ delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_()
85
+ else:
86
+ delta_bias = None
87
+ u = torch.randn(batch_size, dim, seqlen, device=device, dtype=itype, requires_grad=True)
88
+ delta = (0.5 * torch.rand(batch_size, dim, seqlen, device=device, dtype=itype)).requires_grad_()
89
+ A_ref = A.detach().clone().requires_grad_()
90
+ B_ref = B.detach().clone().requires_grad_()
91
+ C_ref = C.detach().clone().requires_grad_()
92
+ D_ref = D.detach().clone().requires_grad_() if D is not None else None
93
+ z_ref = z.detach().clone().requires_grad_() if z is not None else None
94
+ u_ref = u.detach().clone().requires_grad_()
95
+ delta_ref = delta.detach().clone().requires_grad_()
96
+ delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None
97
+ out, *rest = selective_scan_fn(
98
+ u, delta, A, B, C, D, z=z,
99
+ delta_bias=delta_bias, delta_softplus=delta_softplus,
100
+ return_last_state=return_last_state
101
+ )
102
+ if return_last_state:
103
+ state = rest[0]
104
+ out_ref, *rest = selective_scan_ref(
105
+ u_ref, delta_ref, A_ref, B_ref, C_ref, D_ref, z=z_ref,
106
+ delta_bias=delta_bias_ref, delta_softplus=delta_softplus,
107
+ return_last_state=return_last_state
108
+ )
109
+ if return_last_state:
110
+ state_ref = rest[0]
111
+ # dA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A))
112
+ # dt_u = delta * u
113
+
114
+ print(f'Output max diff: {(out - out_ref).abs().max().item()}')
115
+ print(f'Output mean diff: {(out - out_ref).abs().mean().item()}')
116
+ assert torch.allclose(out, out_ref, rtol=rtol, atol=atol)
117
+ if return_last_state:
118
+ print(f'State max diff: {(state - state_ref).abs().max().item()}')
119
+ assert torch.allclose(state, state_ref, rtol=rtol, atol=atol)
120
+
121
+ g = torch.randn_like(out)
122
+ out_ref.backward(g)
123
+ out.backward(g)
124
+
125
+ print(f'du max diff: {(u.grad - u_ref.grad).abs().max().item()}')
126
+ print(f'ddelta max diff: {(delta.grad - delta_ref.grad).abs().max().item()}')
127
+ print(f'dA max diff: {(A.grad - A_ref.grad).abs().max().item()}')
128
+ print(f'dB max diff: {(B.grad - B_ref.grad).abs().max().item()}')
129
+ print(f'dC max diff: {(C.grad - C_ref.grad).abs().max().item()}')
130
+ if has_D:
131
+ print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}')
132
+ if has_z:
133
+ print(f'dz max diff: {(z.grad - z_ref.grad).abs().max().item()}')
134
+ if has_delta_bias:
135
+ print(f'ddelta_bias max diff: {(delta_bias.grad - delta_bias_ref.grad).abs().max().item()}')
136
+
137
+ assert torch.allclose(u.grad, u_ref.grad.to(dtype=itype), rtol=rtol * 2, atol=atol * 2)
138
+ assert torch.allclose(delta.grad, delta_ref.grad.to(dtype=itype), rtol=rtol * 5, atol=atol * 10)
139
+ assert torch.allclose(A.grad, A_ref.grad, rtol=rtolw, atol=atolw * 5)
140
+ assert torch.allclose(B.grad, B_ref.grad, rtol=rtolw if not is_variable_B else rtol,
141
+ atol=atolw if not is_variable_B else atol)
142
+ assert torch.allclose(C.grad, C_ref.grad, rtol=rtolw if not is_variable_C else rtol,
143
+ atol=atolw if not is_variable_C else atol)
144
+ if has_D:
145
+ assert torch.allclose(D.grad, D_ref.grad, rtol=rtolw, atol=atolw)
146
+ if has_z:
147
+ assert torch.allclose(z.grad, z_ref.grad, rtol=rtolw, atol=atolw)
148
+ if has_delta_bias:
149
+ assert torch.allclose(delta_bias.grad, delta_bias_ref.grad, rtol=rtolw, atol=atolw)
150
+
151
+
152
+ @pytest.mark.parametrize('wtype', [torch.float32, torch.complex64])
153
+ # @pytest.mark.parametrize('wtype', [torch.complex64])
154
+ # @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16])
155
+ @pytest.mark.parametrize('itype', [torch.float32])
156
+ # @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096])
157
+ @pytest.mark.parametrize('seqlen', [128])
158
+ @pytest.mark.parametrize("is_variable_C", [False, True])
159
+ # @pytest.mark.parametrize("is_variable_C", [False])
160
+ @pytest.mark.parametrize("is_variable_B", [False, True])
161
+ # @pytest.mark.parametrize("is_variable_B", [True])
162
+ def test_mamba_inner_fn(is_variable_B, is_variable_C, seqlen, itype, wtype):
163
+ device = 'cuda'
164
+ rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3)
165
+ if itype == torch.bfloat16:
166
+ rtol, atol = 3e-2, 5e-2
167
+ rtolw, atolw = (1e-3, 1e-3)
168
+ # If we have z, the errors on the weights seem higher
169
+ rtolw = max(rtolw, rtol)
170
+ atolw = max(atolw, atol)
171
+ # set seed
172
+ torch.random.manual_seed(0)
173
+ batch_size = 2
174
+ dim = 768
175
+ dstate = 8
176
+ dt_rank = 48
177
+ is_complex = wtype == torch.complex64
178
+ xz = torch.randn(batch_size, 2 * dim, seqlen, device=device, dtype=itype, requires_grad=True)
179
+ conv1d_weight = torch.randn(dim, 1, 3, device=device, dtype=torch.float32, requires_grad=True)
180
+ conv1d_bias = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True)
181
+ x_proj_weight = torch.randn(dt_rank + (bool(is_variable_B) + bool(is_variable_C)) * dstate
182
+ * (1 if not is_complex else 2),
183
+ dim, device=device, dtype=itype, requires_grad=True)
184
+ delta_proj_weight = torch.randn(dim, dt_rank, device=device, dtype=itype, requires_grad=True)
185
+ out_proj_weight = torch.randn(dim // 2, dim, device=device, dtype=itype, requires_grad=True)
186
+ out_proj_bias = None
187
+ A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_()
188
+ B = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True)
189
+ if not is_variable_B else None)
190
+ C = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True)
191
+ if not is_variable_C else None)
192
+ D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True)
193
+ delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_()
194
+ B_proj_bias = None
195
+ C_proj_bias = None
196
+ xz_ref = xz.detach().clone().requires_grad_()
197
+ conv1d_weight_ref = conv1d_weight.detach().clone().requires_grad_()
198
+ conv1d_bias_ref = conv1d_bias.detach().clone().requires_grad_()
199
+ x_proj_weight_ref = x_proj_weight.detach().clone().requires_grad_()
200
+ delta_proj_weight_ref = delta_proj_weight.detach().clone().requires_grad_()
201
+ out_proj_weight_ref = out_proj_weight.detach().clone().requires_grad_()
202
+ out_proj_bias_ref = (out_proj_bias.detach().clone().requires_grad_()
203
+ if out_proj_bias is not None else None)
204
+ A_ref = A.detach().clone().requires_grad_()
205
+ B_ref = B.detach().clone().requires_grad_() if B is not None else None
206
+ C_ref = C.detach().clone().requires_grad_() if C is not None else None
207
+ D_ref = D.detach().clone().requires_grad_()
208
+ delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None
209
+ out = mamba_inner_fn(xz, conv1d_weight, conv1d_bias, x_proj_weight, delta_proj_weight,
210
+ out_proj_weight, out_proj_bias,
211
+ A, B, C, D, delta_bias=delta_bias, delta_softplus=True)
212
+ out_ref = mamba_inner_ref(xz_ref, conv1d_weight_ref, conv1d_bias_ref, x_proj_weight_ref,
213
+ delta_proj_weight_ref, out_proj_weight_ref, out_proj_bias_ref,
214
+ A_ref, B_ref, C_ref, D_ref,
215
+ delta_bias=delta_bias_ref, delta_softplus=True)
216
+ # dA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A))
217
+ # dt_u = delta * u
218
+ print("mamba_inner_fn")
219
+ print(f'Output max diff: {(out - out_ref).abs().max().item()}')
220
+ print(f'Output mean diff: {(out - out_ref).abs().mean().item()}')
221
+ assert torch.allclose(out, out_ref, rtol=rtol, atol=atol)
222
+
223
+ g = torch.randn_like(out)
224
+ out_ref.backward(g)
225
+ out.backward(g)
226
+
227
+ print(f'dxz max diff: {(xz.grad - xz_ref.grad).abs().max().item()}')
228
+ print(f'dA max diff: {(A.grad - A_ref.grad).abs().max().item()}')
229
+ if not is_variable_B:
230
+ print(f'dB max diff: {(B.grad - B_ref.grad).abs().max().item()}')
231
+ if not is_variable_C:
232
+ print(f'dC max diff: {(C.grad - C_ref.grad).abs().max().item()}')
233
+ print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}')
234
+ print(f'ddelta_bias max diff: {(delta_bias.grad - delta_bias_ref.grad).abs().max().item()}')
235
+ print(f'dout_proj_weight max diff: {(out_proj_weight.grad - out_proj_weight_ref.grad).abs().max().item()}')
236
+ print(f'ddelta_proj_weight max diff: {(delta_proj_weight.grad - delta_proj_weight_ref.grad).abs().max().item()}')
237
+ print(f'dx_proj_weight max diff: {(x_proj_weight.grad - x_proj_weight_ref.grad).abs().max().item()}')
238
+ print(f'dconv1d_weight max diff: {(conv1d_weight.grad - conv1d_weight_ref.grad).abs().max().item()}')
239
+ print(f'dconv1d_bias max diff: {(conv1d_bias.grad - conv1d_bias_ref.grad).abs().max().item()}')
240
+
241
+ # assert torch.allclose(xz.grad, xz_ref.grad.to(dtype=itype), rtol=rtol * 2, atol=atol * 2)
242
+ # assert torch.allclose(delta.grad, delta_ref.grad.to(dtype=itype), rtol=rtol * 5, atol=atol * 10)
243
+ # assert torch.allclose(A.grad, A_ref.grad, rtol=rtolw, atol=atolw * 5)
244
+ # assert torch.allclose(B.grad, B_ref.grad, rtol=rtolw if not is_variable_B else rtol,
245
+ # atol=atolw if not is_variable_B else atol)
246
+ # assert torch.allclose(C.grad, C_ref.grad, rtol=rtolw if not is_variable_C else rtol,
247
+ # atol=atolw if not is_variable_C else atol)
248
+ # assert torch.allclose(D.grad, D_ref.grad, rtol=rtolw, atol=atolw)
249
+ # assert torch.allclose(delta_bias.grad, delta_bias_ref.grad, rtol=rtolw, atol=atolw)
250
+
251
+
252
+ # test_mamba_inner_fn(False, False, 128, torch.float32, torch.float32)
253
+
254
+
255
+ @pytest.mark.parametrize('wtype', [torch.float32, torch.complex64])
256
+ # @pytest.mark.parametrize('wtype', [torch.complex64])
257
+ # @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16])
258
+ @pytest.mark.parametrize('itype', [torch.float32])
259
+ # @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096])
260
+ @pytest.mark.parametrize('seqlen', [128])
261
+ @pytest.mark.parametrize("is_variable_C", [False, True])
262
+ # @pytest.mark.parametrize("is_variable_C", [False])
263
+ @pytest.mark.parametrize("is_variable_B", [False, True])
264
+ # @pytest.mark.parametrize("is_variable_B", [True])
265
+ def test_bimamba_inner_fn(is_variable_B, is_variable_C, seqlen, itype, wtype):
266
+ device = 'cuda'
267
+ rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3)
268
+ if itype == torch.bfloat16:
269
+ rtol, atol = 3e-2, 5e-2
270
+ rtolw, atolw = (1e-3, 1e-3)
271
+ # If we have z, the errors on the weights seem higher
272
+ rtolw = max(rtolw, rtol)
273
+ atolw = max(atolw, atol)
274
+ # set seed
275
+ torch.random.manual_seed(0)
276
+ batch_size = 2
277
+ dim = 768
278
+ dstate = 8
279
+ dt_rank = 48
280
+ is_complex = wtype == torch.complex64
281
+ xz = torch.randn(batch_size, 2 * dim, seqlen, device=device, dtype=itype, requires_grad=True)
282
+ conv1d_weight = torch.randn(dim, 1, 3, device=device, dtype=torch.float32, requires_grad=True)
283
+ conv1d_bias = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True)
284
+ x_proj_weight = torch.randn(dt_rank + (bool(is_variable_B) + bool(is_variable_C)) * dstate
285
+ * (1 if not is_complex else 2),
286
+ dim, device=device, dtype=itype, requires_grad=True)
287
+ delta_proj_weight = torch.randn(dim, dt_rank, device=device, dtype=itype, requires_grad=True)
288
+ out_proj_weight = torch.randn(dim // 2, dim, device=device, dtype=itype, requires_grad=True)
289
+ out_proj_bias = None
290
+ A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_()
291
+ A_b = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_()
292
+ B = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True)
293
+ if not is_variable_B else None)
294
+ C = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True)
295
+ if not is_variable_C else None)
296
+ D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True)
297
+ delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_()
298
+ B_proj_bias = None
299
+ C_proj_bias = None
300
+ xz_ref = xz.detach().clone().requires_grad_()
301
+ conv1d_weight_ref = conv1d_weight.detach().clone().requires_grad_()
302
+ conv1d_bias_ref = conv1d_bias.detach().clone().requires_grad_()
303
+ x_proj_weight_ref = x_proj_weight.detach().clone().requires_grad_()
304
+ delta_proj_weight_ref = delta_proj_weight.detach().clone().requires_grad_()
305
+ out_proj_weight_ref = out_proj_weight.detach().clone().requires_grad_()
306
+ out_proj_bias_ref = (out_proj_bias.detach().clone().requires_grad_()
307
+ if out_proj_bias is not None else None)
308
+ A_ref = A.detach().clone().requires_grad_()
309
+ A_b_ref = A_b.detach().clone().requires_grad_()
310
+ B_ref = B.detach().clone().requires_grad_() if B is not None else None
311
+ C_ref = C.detach().clone().requires_grad_() if C is not None else None
312
+ D_ref = D.detach().clone().requires_grad_()
313
+ delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None
314
+ out = bimamba_inner_fn(xz, conv1d_weight, conv1d_bias, x_proj_weight, delta_proj_weight,
315
+ out_proj_weight, out_proj_bias,
316
+ A, A_b, B, C, D, delta_bias=delta_bias, delta_softplus=True)
317
+ out_ref = bimamba_inner_fn(xz_ref, conv1d_weight_ref, conv1d_bias_ref, x_proj_weight_ref,
318
+ delta_proj_weight_ref, out_proj_weight_ref, out_proj_bias_ref,
319
+ A_ref, A_b_ref, B_ref, C_ref, D_ref,
320
+ delta_bias=delta_bias_ref, delta_softplus=True)
321
+ # dA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A))
322
+ # dt_u = delta * u
323
+ print("bimamba_inner_fn")
324
+ print(f'Output max diff: {(out - out_ref).abs().max().item()}')
325
+ print(f'Output mean diff: {(out - out_ref).abs().mean().item()}')
326
+ assert torch.allclose(out, out_ref, rtol=rtol, atol=atol)
327
+
328
+ g = torch.randn_like(out)
329
+ out_ref.backward(g)
330
+ out.backward(g)
331
+
332
+ print(f'dxz max diff: {(xz.grad - xz_ref.grad).abs().max().item()}')
333
+ print(f'dA max diff: {(A.grad - A_ref.grad).abs().max().item()}')
334
+ print(f'dA_b max diff: {(A_b.grad - A_b_ref.grad).abs().max().item()}')
335
+ if not is_variable_B:
336
+ print(f'dB max diff: {(B.grad - B_ref.grad).abs().max().item()}')
337
+ if not is_variable_C:
338
+ print(f'dC max diff: {(C.grad - C_ref.grad).abs().max().item()}')
339
+ print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}')
340
+ print(f'ddelta_bias max diff: {(delta_bias.grad - delta_bias_ref.grad).abs().max().item()}')
341
+ print(f'dout_proj_weight max diff: {(out_proj_weight.grad - out_proj_weight_ref.grad).abs().max().item()}')
342
+ print(f'ddelta_proj_weight max diff: {(delta_proj_weight.grad - delta_proj_weight_ref.grad).abs().max().item()}')
343
+ print(f'dx_proj_weight max diff: {(x_proj_weight.grad - x_proj_weight_ref.grad).abs().max().item()}')
344
+ print(f'dconv1d_weight max diff: {(conv1d_weight.grad - conv1d_weight_ref.grad).abs().max().item()}')
345
+ print(f'dconv1d_bias max diff: {(conv1d_bias.grad - conv1d_bias_ref.grad).abs().max().item()}')
346
+
347
+ @pytest.mark.parametrize('wtype', [torch.float32, torch.complex64])
348
+ # @pytest.mark.parametrize('wtype', [torch.complex64])
349
+ # @pytest.mark.parametrize('itype', [torch.float32, torch.float16, torch.bfloat16])
350
+ @pytest.mark.parametrize('itype', [torch.float32])
351
+ # @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096])
352
+ @pytest.mark.parametrize('seqlen', [128])
353
+ @pytest.mark.parametrize("is_variable_C", [False, True])
354
+ # @pytest.mark.parametrize("is_variable_C", [False])
355
+ @pytest.mark.parametrize("is_variable_B", [False, True])
356
+ # @pytest.mark.parametrize("is_variable_B", [True])
357
+ def test_bimamba_inner_fn_grad_check(is_variable_B, is_variable_C, seqlen, itype, wtype):
358
+ device = 'cuda'
359
+ rtol, atol = (6e-4, 2e-3) if itype == torch.float32 else (3e-3, 5e-3)
360
+ if itype == torch.bfloat16:
361
+ rtol, atol = 3e-2, 5e-2
362
+ rtolw, atolw = (1e-3, 1e-3)
363
+ # If we have z, the errors on the weights seem higher
364
+ rtolw = max(rtolw, rtol)
365
+ atolw = max(atolw, atol)
366
+ # set seed
367
+ torch.random.manual_seed(0)
368
+ batch_size = 2 // 2
369
+ dim = 768 // 8
370
+ dstate = 8 // 8
371
+ dt_rank = 48 // 8
372
+ is_complex = wtype == torch.complex64
373
+ xz = torch.randn(batch_size, 2 * dim, seqlen, device=device, dtype=itype, requires_grad=True)
374
+ conv1d_weight = torch.randn(dim, 1, 3, device=device, dtype=torch.float32, requires_grad=True)
375
+ conv1d_bias = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True)
376
+ x_proj_weight = torch.randn(dt_rank + (bool(is_variable_B) + bool(is_variable_C)) * dstate
377
+ * (1 if not is_complex else 2),
378
+ dim, device=device, dtype=itype, requires_grad=True)
379
+ delta_proj_weight = torch.randn(dim, dt_rank, device=device, dtype=itype, requires_grad=True)
380
+ out_proj_weight = torch.randn(dim // 2, dim, device=device, dtype=itype, requires_grad=True)
381
+ out_proj_bias = None
382
+ A = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_()
383
+ A_b = (-0.5 * torch.rand(dim, dstate, device=device, dtype=wtype)).requires_grad_()
384
+ B = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True)
385
+ if not is_variable_B else None)
386
+ C = (torch.randn(dim, dstate, device=device, dtype=wtype, requires_grad=True)
387
+ if not is_variable_C else None)
388
+ D = torch.randn(dim, device=device, dtype=torch.float32, requires_grad=True)
389
+ delta_bias = (0.5 * torch.rand(dim, device=device, dtype=torch.float32)).requires_grad_()
390
+ B_proj_bias = None
391
+ C_proj_bias = None
392
+ xz_ref = xz.detach().clone().requires_grad_()
393
+ conv1d_weight_ref = conv1d_weight.detach().clone().requires_grad_()
394
+ conv1d_bias_ref = conv1d_bias.detach().clone().requires_grad_()
395
+ x_proj_weight_ref = x_proj_weight.detach().clone().requires_grad_()
396
+ delta_proj_weight_ref = delta_proj_weight.detach().clone().requires_grad_()
397
+ out_proj_weight_ref = out_proj_weight.detach().clone().requires_grad_()
398
+ out_proj_bias_ref = (out_proj_bias.detach().clone().requires_grad_()
399
+ if out_proj_bias is not None else None)
400
+ A_ref = A.detach().clone().requires_grad_()
401
+ A_b_ref = A_b.detach().clone().requires_grad_()
402
+ B_ref = B.detach().clone().requires_grad_() if B is not None else None
403
+ C_ref = C.detach().clone().requires_grad_() if C is not None else None
404
+ D_ref = D.detach().clone().requires_grad_()
405
+ delta_bias_ref = delta_bias.detach().clone().requires_grad_() if delta_bias is not None else None
406
+
407
+ # func = bimamba_inner_fn
408
+ # func = mamba_inner_fn
409
+ func = mamba_inner_ref
410
+
411
+ # 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))
412
+ 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.)
413
+ print(f'* {gradok} check_gradient_numerical bimamba_inner_fn')
414
+
415
+
416
+
417
+ # test_bimamba_inner_fn(True, True, 128, torch.float32, torch.float32)
418
+ # test_mamba_inner_fn(True, True, 128, torch.float32, torch.float32)
419
+ test_bimamba_inner_fn_grad_check(True, True, 128, torch.float32, torch.float32)
420
+
421
+ # input = (torch.randn(20,20,dtype=torch.double,requires_grad=True), torch.randn(30,20,dtype=torch.double,requires_grad=True))
422
+ # test = gradcheck(torch.nn.functional.linear, input, eps=1e-6, atol=1e-4)
423
+ # print(test)
source_code/SegMamba/monai/_extensions/loader.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import platform
15
+ from _thread import interrupt_main
16
+ from contextlib import contextmanager
17
+ from glob import glob
18
+ from os import path
19
+ from threading import Timer
20
+ from types import ModuleType
21
+
22
+ import torch
23
+
24
+ from monai.utils.module import get_torch_version_tuple, optional_import
25
+
26
+ dir_path = path.dirname(path.realpath(__file__))
27
+
28
+
29
+ @contextmanager
30
+ def timeout(time, message):
31
+ timer = None
32
+ try:
33
+ timer = Timer(time, interrupt_main)
34
+ timer.daemon = True
35
+ timer.start()
36
+ yield
37
+ except KeyboardInterrupt as e:
38
+ if timer is not None and timer.is_alive():
39
+ raise e # interrupt from user?
40
+ raise TimeoutError(message) from e
41
+ finally:
42
+ if timer is not None:
43
+ try:
44
+ timer.cancel()
45
+ finally:
46
+ pass
47
+
48
+
49
+ def load_module(
50
+ module_name: str, defines: dict | None = None, verbose_build: bool = False, build_timeout: int = 300
51
+ ) -> ModuleType:
52
+ """
53
+ Handles the loading of c++ extension modules.
54
+
55
+ Args:
56
+ module_name: Name of the module to load.
57
+ Must match the name of the relevant source directory in the `_extensions` directory.
58
+ defines: Dictionary containing names and values of compilation defines.
59
+ verbose_build: Set to true to enable build logging.
60
+ build_timeout: Time in seconds before the build will throw an exception to prevent hanging.
61
+ """
62
+
63
+ # Ensuring named module exists in _extensions directory.
64
+ module_dir = path.join(dir_path, module_name)
65
+ if not path.exists(module_dir):
66
+ raise ValueError(f"No extension module named {module_name}")
67
+
68
+ platform_str = f"_{platform.system()}_{platform.python_version()}_"
69
+ platform_str += "".join(f"{v}" for v in get_torch_version_tuple()[:2])
70
+ # Adding configuration to module name.
71
+ if defines is not None:
72
+ module_name = "_".join([module_name] + [f"{v}" for v in defines.values()])
73
+
74
+ # Gathering source files.
75
+ source = glob(path.join(module_dir, "**", "*.cpp"), recursive=True)
76
+ if torch.cuda.is_available():
77
+ source += glob(path.join(module_dir, "**", "*.cu"), recursive=True)
78
+ platform_str += f"_{torch.version.cuda}"
79
+
80
+ # Constructing compilation argument list.
81
+ define_args = [] if not defines else [f"-D {key}={defines[key]}" for key in defines]
82
+
83
+ # Ninja may be blocked by something out of our control.
84
+ # This will error if the build takes longer than expected.
85
+ with timeout(build_timeout, "Build appears to be blocked. Is there a stopped process building the same extension?"):
86
+ load, _ = optional_import("torch.utils.cpp_extension", name="load") # main trigger some JIT config in pytorch
87
+ # This will either run the build or return the existing .so object.
88
+ name = module_name + platform_str.replace(".", "_")
89
+ module = load(
90
+ name=name, sources=source, extra_cflags=define_args, extra_cuda_cflags=define_args, verbose=verbose_build
91
+ )
92
+
93
+ return module # type: ignore[no-any-return]
source_code/SegMamba/monai/apps/datasets.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import shutil
16
+ import sys
17
+ import warnings
18
+ from collections.abc import Callable, Sequence
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+
24
+ from monai.apps.tcia import (
25
+ DCM_FILENAME_REGEX,
26
+ download_tcia_series_instance,
27
+ get_tcia_metadata,
28
+ get_tcia_ref_uid,
29
+ match_tcia_ref_uid_in_study,
30
+ )
31
+ from monai.apps.utils import download_and_extract
32
+ from monai.config.type_definitions import PathLike
33
+ from monai.data import (
34
+ CacheDataset,
35
+ PydicomReader,
36
+ load_decathlon_datalist,
37
+ load_decathlon_properties,
38
+ partition_dataset,
39
+ select_cross_validation_folds,
40
+ )
41
+ from monai.transforms import LoadImaged, Randomizable
42
+ from monai.utils import ensure_tuple
43
+
44
+ __all__ = ["MedNISTDataset", "DecathlonDataset", "CrossValidation", "TciaDataset"]
45
+
46
+
47
+ class MedNISTDataset(Randomizable, CacheDataset):
48
+ """
49
+ The Dataset to automatically download MedNIST data and generate items for training, validation or test.
50
+ It's based on `CacheDataset` to accelerate the training process.
51
+
52
+ Args:
53
+ root_dir: target directory to download and load MedNIST dataset.
54
+ section: expected data section, can be: `training`, `validation` or `test`.
55
+ transform: transforms to execute operations on input data.
56
+ download: whether to download and extract the MedNIST from resource link, default is False.
57
+ if expected file already exists, skip downloading even set it to True.
58
+ user can manually copy `MedNIST.tar.gz` file or `MedNIST` folder to root directory.
59
+ seed: random seed to randomly split training, validation and test datasets, default is 0.
60
+ val_frac: percentage of validation fraction in the whole dataset, default is 0.1.
61
+ test_frac: percentage of test fraction in the whole dataset, default is 0.1.
62
+ cache_num: number of items to be cached. Default is `sys.maxsize`.
63
+ will take the minimum of (cache_num, data_length x cache_rate, data_length).
64
+ cache_rate: percentage of cached data in total, default is 1.0 (cache all).
65
+ will take the minimum of (cache_num, data_length x cache_rate, data_length).
66
+ num_workers: the number of worker threads if computing cache in the initialization.
67
+ If num_workers is None then the number returned by os.cpu_count() is used.
68
+ If a value less than 1 is specified, 1 will be used instead.
69
+ progress: whether to display a progress bar when downloading dataset and computing the transform cache content.
70
+ copy_cache: whether to `deepcopy` the cache content before applying the random transforms,
71
+ default to `True`. if the random transforms don't modify the cached content
72
+ (for example, randomly crop from the cached image and deepcopy the crop region)
73
+ or if every cache item is only used once in a `multi-processing` environment,
74
+ may set `copy=False` for better performance.
75
+ as_contiguous: whether to convert the cached NumPy array or PyTorch tensor to be contiguous.
76
+ it may help improve the performance of following logic.
77
+ runtime_cache: whether to compute cache at the runtime, default to `False` to prepare
78
+ the cache content at initialization. See: :py:class:`monai.data.CacheDataset`.
79
+
80
+ Raises:
81
+ ValueError: When ``root_dir`` is not a directory.
82
+ RuntimeError: When ``dataset_dir`` doesn't exist and downloading is not selected (``download=False``).
83
+
84
+ """
85
+
86
+ resource = "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/MedNIST.tar.gz"
87
+ md5 = "0bc7306e7427e00ad1c5526a6677552d"
88
+ compressed_file_name = "MedNIST.tar.gz"
89
+ dataset_folder_name = "MedNIST"
90
+
91
+ def __init__(
92
+ self,
93
+ root_dir: PathLike,
94
+ section: str,
95
+ transform: Sequence[Callable] | Callable = (),
96
+ download: bool = False,
97
+ seed: int = 0,
98
+ val_frac: float = 0.1,
99
+ test_frac: float = 0.1,
100
+ cache_num: int = sys.maxsize,
101
+ cache_rate: float = 1.0,
102
+ num_workers: int | None = 1,
103
+ progress: bool = True,
104
+ copy_cache: bool = True,
105
+ as_contiguous: bool = True,
106
+ runtime_cache: bool = False,
107
+ ) -> None:
108
+ root_dir = Path(root_dir)
109
+ if not root_dir.is_dir():
110
+ raise ValueError("Root directory root_dir must be a directory.")
111
+ self.section = section
112
+ self.val_frac = val_frac
113
+ self.test_frac = test_frac
114
+ self.set_random_state(seed=seed)
115
+ tarfile_name = root_dir / self.compressed_file_name
116
+ dataset_dir = root_dir / self.dataset_folder_name
117
+ self.num_class = 0
118
+ if download:
119
+ download_and_extract(
120
+ url=self.resource,
121
+ filepath=tarfile_name,
122
+ output_dir=root_dir,
123
+ hash_val=self.md5,
124
+ hash_type="md5",
125
+ progress=progress,
126
+ )
127
+
128
+ if not dataset_dir.is_dir():
129
+ raise RuntimeError(
130
+ f"Cannot find dataset directory: {dataset_dir}, please use download=True to download it."
131
+ )
132
+ data = self._generate_data_list(dataset_dir)
133
+ if transform == ():
134
+ transform = LoadImaged("image")
135
+ CacheDataset.__init__(
136
+ self,
137
+ data=data,
138
+ transform=transform,
139
+ cache_num=cache_num,
140
+ cache_rate=cache_rate,
141
+ num_workers=num_workers,
142
+ progress=progress,
143
+ copy_cache=copy_cache,
144
+ as_contiguous=as_contiguous,
145
+ runtime_cache=runtime_cache,
146
+ )
147
+
148
+ def randomize(self, data: np.ndarray) -> None:
149
+ self.R.shuffle(data)
150
+
151
+ def get_num_classes(self) -> int:
152
+ """Get number of classes."""
153
+ return self.num_class
154
+
155
+ def _generate_data_list(self, dataset_dir: PathLike) -> list[dict]:
156
+ """
157
+ Raises:
158
+ ValueError: When ``section`` is not one of ["training", "validation", "test"].
159
+
160
+ """
161
+ dataset_dir = Path(dataset_dir)
162
+ class_names = sorted(f"{x.name}" for x in dataset_dir.iterdir() if x.is_dir()) # folder name as the class name
163
+ self.num_class = len(class_names)
164
+ image_files = [[f"{x}" for x in (dataset_dir / class_names[i]).iterdir()] for i in range(self.num_class)]
165
+ num_each = [len(image_files[i]) for i in range(self.num_class)]
166
+ image_files_list = []
167
+ image_class = []
168
+ class_name = []
169
+ for i in range(self.num_class):
170
+ image_files_list.extend(image_files[i])
171
+ image_class.extend([i] * num_each[i])
172
+ class_name.extend([class_names[i]] * num_each[i])
173
+
174
+ length = len(image_files_list)
175
+ indices = np.arange(length)
176
+ self.randomize(indices)
177
+
178
+ test_length = int(length * self.test_frac)
179
+ val_length = int(length * self.val_frac)
180
+ if self.section == "test":
181
+ section_indices = indices[:test_length]
182
+ elif self.section == "validation":
183
+ section_indices = indices[test_length : test_length + val_length]
184
+ elif self.section == "training":
185
+ section_indices = indices[test_length + val_length :]
186
+ else:
187
+ raise ValueError(
188
+ f'Unsupported section: {self.section}, available options are ["training", "validation", "test"].'
189
+ )
190
+ # the types of label and class name should be compatible with the pytorch dataloader
191
+ return [
192
+ {"image": image_files_list[i], "label": image_class[i], "class_name": class_name[i]}
193
+ for i in section_indices
194
+ ]
195
+
196
+
197
+ class DecathlonDataset(Randomizable, CacheDataset):
198
+ """
199
+ The Dataset to automatically download the data of Medical Segmentation Decathlon challenge
200
+ (http://medicaldecathlon.com/) and generate items for training, validation or test.
201
+ It will also load these properties from the JSON config file of dataset. user can call `get_properties()`
202
+ to get specified properties or all the properties loaded.
203
+ It's based on :py:class:`monai.data.CacheDataset` to accelerate the training process.
204
+
205
+ Args:
206
+ root_dir: user's local directory for caching and loading the MSD datasets.
207
+ task: which task to download and execute: one of list ("Task01_BrainTumour", "Task02_Heart",
208
+ "Task03_Liver", "Task04_Hippocampus", "Task05_Prostate", "Task06_Lung", "Task07_Pancreas",
209
+ "Task08_HepaticVessel", "Task09_Spleen", "Task10_Colon").
210
+ section: expected data section, can be: `training`, `validation` or `test`.
211
+ transform: transforms to execute operations on input data.
212
+ for further usage, use `EnsureChannelFirstd` to convert the shape to [C, H, W, D].
213
+ download: whether to download and extract the Decathlon from resource link, default is False.
214
+ if expected file already exists, skip downloading even set it to True.
215
+ user can manually copy tar file or dataset folder to the root directory.
216
+ val_frac: percentage of validation fraction in the whole dataset, default is 0.2.
217
+ seed: random seed to randomly shuffle the datalist before splitting into training and validation, default is 0.
218
+ note to set same seed for `training` and `validation` sections.
219
+ cache_num: number of items to be cached. Default is `sys.maxsize`.
220
+ will take the minimum of (cache_num, data_length x cache_rate, data_length).
221
+ cache_rate: percentage of cached data in total, default is 1.0 (cache all).
222
+ will take the minimum of (cache_num, data_length x cache_rate, data_length).
223
+ num_workers: the number of worker threads if computing cache in the initialization.
224
+ If num_workers is None then the number returned by os.cpu_count() is used.
225
+ If a value less than 1 is specified, 1 will be used instead.
226
+ progress: whether to display a progress bar when downloading dataset and computing the transform cache content.
227
+ copy_cache: whether to `deepcopy` the cache content before applying the random transforms,
228
+ default to `True`. if the random transforms don't modify the cached content
229
+ (for example, randomly crop from the cached image and deepcopy the crop region)
230
+ or if every cache item is only used once in a `multi-processing` environment,
231
+ may set `copy=False` for better performance.
232
+ as_contiguous: whether to convert the cached NumPy array or PyTorch tensor to be contiguous.
233
+ it may help improve the performance of following logic.
234
+ runtime_cache: whether to compute cache at the runtime, default to `False` to prepare
235
+ the cache content at initialization. See: :py:class:`monai.data.CacheDataset`.
236
+
237
+ Raises:
238
+ ValueError: When ``root_dir`` is not a directory.
239
+ ValueError: When ``task`` is not one of ["Task01_BrainTumour", "Task02_Heart",
240
+ "Task03_Liver", "Task04_Hippocampus", "Task05_Prostate", "Task06_Lung", "Task07_Pancreas",
241
+ "Task08_HepaticVessel", "Task09_Spleen", "Task10_Colon"].
242
+ RuntimeError: When ``dataset_dir`` doesn't exist and downloading is not selected (``download=False``).
243
+
244
+ Example::
245
+
246
+ transform = Compose(
247
+ [
248
+ LoadImaged(keys=["image", "label"]),
249
+ EnsureChannelFirstd(keys=["image", "label"]),
250
+ ScaleIntensityd(keys="image"),
251
+ ToTensord(keys=["image", "label"]),
252
+ ]
253
+ )
254
+
255
+ val_data = DecathlonDataset(
256
+ root_dir="./", task="Task09_Spleen", transform=transform, section="validation", seed=12345, download=True
257
+ )
258
+
259
+ print(val_data[0]["image"], val_data[0]["label"])
260
+
261
+ """
262
+
263
+ resource = {
264
+ "Task01_BrainTumour": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task01_BrainTumour.tar",
265
+ "Task02_Heart": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task02_Heart.tar",
266
+ "Task03_Liver": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task03_Liver.tar",
267
+ "Task04_Hippocampus": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task04_Hippocampus.tar",
268
+ "Task05_Prostate": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task05_Prostate.tar",
269
+ "Task06_Lung": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task06_Lung.tar",
270
+ "Task07_Pancreas": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task07_Pancreas.tar",
271
+ "Task08_HepaticVessel": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task08_HepaticVessel.tar",
272
+ "Task09_Spleen": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task09_Spleen.tar",
273
+ "Task10_Colon": "https://msd-for-monai.s3-us-west-2.amazonaws.com/Task10_Colon.tar",
274
+ }
275
+ md5 = {
276
+ "Task01_BrainTumour": "240a19d752f0d9e9101544901065d872",
277
+ "Task02_Heart": "06ee59366e1e5124267b774dbd654057",
278
+ "Task03_Liver": "a90ec6c4aa7f6a3d087205e23d4e6397",
279
+ "Task04_Hippocampus": "9d24dba78a72977dbd1d2e110310f31b",
280
+ "Task05_Prostate": "35138f08b1efaef89d7424d2bcc928db",
281
+ "Task06_Lung": "8afd997733c7fc0432f71255ba4e52dc",
282
+ "Task07_Pancreas": "4f7080cfca169fa8066d17ce6eb061e4",
283
+ "Task08_HepaticVessel": "641d79e80ec66453921d997fbf12a29c",
284
+ "Task09_Spleen": "410d4a301da4e5b2f6f86ec3ddba524e",
285
+ "Task10_Colon": "bad7a188931dc2f6acf72b08eb6202d0",
286
+ }
287
+
288
+ def __init__(
289
+ self,
290
+ root_dir: PathLike,
291
+ task: str,
292
+ section: str,
293
+ transform: Sequence[Callable] | Callable = (),
294
+ download: bool = False,
295
+ seed: int = 0,
296
+ val_frac: float = 0.2,
297
+ cache_num: int = sys.maxsize,
298
+ cache_rate: float = 1.0,
299
+ num_workers: int = 1,
300
+ progress: bool = True,
301
+ copy_cache: bool = True,
302
+ as_contiguous: bool = True,
303
+ runtime_cache: bool = False,
304
+ ) -> None:
305
+ root_dir = Path(root_dir)
306
+ if not root_dir.is_dir():
307
+ raise ValueError("Root directory root_dir must be a directory.")
308
+ self.section = section
309
+ self.val_frac = val_frac
310
+ self.set_random_state(seed=seed)
311
+ if task not in self.resource:
312
+ raise ValueError(f"Unsupported task: {task}, available options are: {list(self.resource.keys())}.")
313
+ dataset_dir = root_dir / task
314
+ tarfile_name = f"{dataset_dir}.tar"
315
+ if download:
316
+ download_and_extract(
317
+ url=self.resource[task],
318
+ filepath=tarfile_name,
319
+ output_dir=root_dir,
320
+ hash_val=self.md5[task],
321
+ hash_type="md5",
322
+ progress=progress,
323
+ )
324
+
325
+ if not dataset_dir.exists():
326
+ raise RuntimeError(
327
+ f"Cannot find dataset directory: {dataset_dir}, please use download=True to download it."
328
+ )
329
+ self.indices: np.ndarray = np.array([])
330
+ data = self._generate_data_list(dataset_dir)
331
+ # as `release` key has typo in Task04 config file, ignore it.
332
+ property_keys = [
333
+ "name",
334
+ "description",
335
+ "reference",
336
+ "licence",
337
+ "tensorImageSize",
338
+ "modality",
339
+ "labels",
340
+ "numTraining",
341
+ "numTest",
342
+ ]
343
+ self._properties = load_decathlon_properties(dataset_dir / "dataset.json", property_keys)
344
+ if transform == ():
345
+ transform = LoadImaged(["image", "label"])
346
+ CacheDataset.__init__(
347
+ self,
348
+ data=data,
349
+ transform=transform,
350
+ cache_num=cache_num,
351
+ cache_rate=cache_rate,
352
+ num_workers=num_workers,
353
+ progress=progress,
354
+ copy_cache=copy_cache,
355
+ as_contiguous=as_contiguous,
356
+ runtime_cache=runtime_cache,
357
+ )
358
+
359
+ def get_indices(self) -> np.ndarray:
360
+ """
361
+ Get the indices of datalist used in this dataset.
362
+
363
+ """
364
+ return self.indices
365
+
366
+ def randomize(self, data: np.ndarray) -> None:
367
+ self.R.shuffle(data)
368
+
369
+ def get_properties(self, keys: Sequence[str] | str | None = None) -> dict:
370
+ """
371
+ Get the loaded properties of dataset with specified keys.
372
+ If no keys specified, return all the loaded properties.
373
+
374
+ """
375
+ if keys is None:
376
+ return self._properties
377
+ if self._properties is not None:
378
+ return {key: self._properties[key] for key in ensure_tuple(keys)}
379
+ return {}
380
+
381
+ def _generate_data_list(self, dataset_dir: PathLike) -> list[dict]:
382
+ # the types of the item in data list should be compatible with the dataloader
383
+ dataset_dir = Path(dataset_dir)
384
+ section = "training" if self.section in ["training", "validation"] else "test"
385
+ datalist = load_decathlon_datalist(dataset_dir / "dataset.json", True, section)
386
+ return self._split_datalist(datalist)
387
+
388
+ def _split_datalist(self, datalist: list[dict]) -> list[dict]:
389
+ if self.section == "test":
390
+ return datalist
391
+ length = len(datalist)
392
+ indices = np.arange(length)
393
+ self.randomize(indices)
394
+
395
+ val_length = int(length * self.val_frac)
396
+ if self.section == "training":
397
+ self.indices = indices[val_length:]
398
+ else:
399
+ self.indices = indices[:val_length]
400
+
401
+ return [datalist[i] for i in self.indices]
402
+
403
+
404
+ class TciaDataset(Randomizable, CacheDataset):
405
+ """
406
+ The Dataset to automatically download the data from a public The Cancer Imaging Archive (TCIA) dataset
407
+ and generate items for training, validation or test.
408
+
409
+ The Highdicom library is used to load dicom data with modality "SEG", but only a part of collections are
410
+ supported, such as: "C4KC-KiTS", "NSCLC-Radiomics", "NSCLC-Radiomics-Interobserver1", " QIN-PROSTATE-Repeatability"
411
+ and "PROSTATEx". Therefore, if "seg" is included in `keys` of the `LoadImaged` transform and loading some
412
+ other collections, errors may be raised. For supported collections, the original "SEG" information may not
413
+ always be consistent for each dicom file. Therefore, to avoid creating different format of labels, please use
414
+ the `label_dict` argument of `PydicomReader` when calling the `LoadImaged` transform. The prepared label dicts
415
+ of collections that are mentioned above is also saved in: `monai.apps.tcia.TCIA_LABEL_DICT`. You can also refer
416
+ to the second example bellow.
417
+
418
+
419
+ This class is based on :py:class:`monai.data.CacheDataset` to accelerate the training process.
420
+
421
+ Args:
422
+ root_dir: user's local directory for caching and loading the TCIA dataset.
423
+ collection: name of a TCIA collection.
424
+ a TCIA dataset is defined as a collection. Please check the following list to browse
425
+ the collection list (only public collections can be downloaded):
426
+ https://www.cancerimagingarchive.net/collections/
427
+ section: expected data section, can be: `training`, `validation` or `test`.
428
+ transform: transforms to execute operations on input data.
429
+ for further usage, use `EnsureChannelFirstd` to convert the shape to [C, H, W, D].
430
+ If not specified, `LoadImaged(reader="PydicomReader", keys=["image"])` will be used as the default
431
+ transform. In addition, we suggest to set the argument `labels` for `PydicomReader` if segmentations
432
+ are needed to be loaded. The original labels for each dicom series may be different, using this argument
433
+ is able to unify the format of labels.
434
+ download: whether to download and extract the dataset, default is False.
435
+ if expected file already exists, skip downloading even set it to True.
436
+ user can manually copy tar file or dataset folder to the root directory.
437
+ download_len: number of series that will be downloaded, the value should be larger than 0 or -1, where -1 means
438
+ all series will be downloaded. Default is -1.
439
+ seg_type: modality type of segmentation that is used to do the first step download. Default is "SEG".
440
+ modality_tag: tag of modality. Default is (0x0008, 0x0060).
441
+ ref_series_uid_tag: tag of referenced Series Instance UID. Default is (0x0020, 0x000e).
442
+ ref_sop_uid_tag: tag of referenced SOP Instance UID. Default is (0x0008, 0x1155).
443
+ specific_tags: tags that will be loaded for "SEG" series. This argument will be used in
444
+ `monai.data.PydicomReader`. Default is [(0x0008, 0x1115), (0x0008,0x1140), (0x3006, 0x0010),
445
+ (0x0020,0x000D), (0x0010,0x0010), (0x0010,0x0020), (0x0020,0x0011), (0x0020,0x0012)].
446
+ fname_regex: a regular expression to match the file names when the input is a folder.
447
+ If provided, only the matched files will be included. For example, to include the file name
448
+ "image_0001.dcm", the regular expression could be `".*image_(\\d+).dcm"`.
449
+ Default to `"^(?!.*LICENSE).*"`, ignoring any file name containing `"LICENSE"`.
450
+ val_frac: percentage of validation fraction in the whole dataset, default is 0.2.
451
+ seed: random seed to randomly shuffle the datalist before splitting into training and validation, default is 0.
452
+ note to set same seed for `training` and `validation` sections.
453
+ cache_num: number of items to be cached. Default is `sys.maxsize`.
454
+ will take the minimum of (cache_num, data_length x cache_rate, data_length).
455
+ cache_rate: percentage of cached data in total, default is 0.0 (no cache).
456
+ will take the minimum of (cache_num, data_length x cache_rate, data_length).
457
+ num_workers: the number of worker threads if computing cache in the initialization.
458
+ If num_workers is None then the number returned by os.cpu_count() is used.
459
+ If a value less than 1 is specified, 1 will be used instead.
460
+ progress: whether to display a progress bar when downloading dataset and computing the transform cache content.
461
+ copy_cache: whether to `deepcopy` the cache content before applying the random transforms,
462
+ default to `True`. if the random transforms don't modify the cached content
463
+ (for example, randomly crop from the cached image and deepcopy the crop region)
464
+ or if every cache item is only used once in a `multi-processing` environment,
465
+ may set `copy=False` for better performance.
466
+ as_contiguous: whether to convert the cached NumPy array or PyTorch tensor to be contiguous.
467
+ it may help improve the performance of following logic.
468
+ runtime_cache: whether to compute cache at the runtime, default to `False` to prepare
469
+ the cache content at initialization. See: :py:class:`monai.data.CacheDataset`.
470
+
471
+ Example::
472
+
473
+ # collection is "Pancreatic-CT-CBCT-SEG", seg_type is "RTSTRUCT"
474
+ data = TciaDataset(
475
+ root_dir="./", collection="Pancreatic-CT-CBCT-SEG", seg_type="RTSTRUCT", download=True
476
+ )
477
+
478
+ # collection is "C4KC-KiTS", seg_type is "SEG", and load both images and segmentations
479
+ from monai.apps.tcia import TCIA_LABEL_DICT
480
+ transform = Compose(
481
+ [
482
+ LoadImaged(reader="PydicomReader", keys=["image", "seg"], label_dict=TCIA_LABEL_DICT["C4KC-KiTS"]),
483
+ EnsureChannelFirstd(keys=["image", "seg"]),
484
+ ResampleToMatchd(keys="image", key_dst="seg"),
485
+ ]
486
+ )
487
+ data = TciaDataset(
488
+ root_dir="./", collection="C4KC-KiTS", section="validation", seed=12345, download=True
489
+ )
490
+
491
+ print(data[0]["seg"].shape)
492
+
493
+ """
494
+
495
+ def __init__(
496
+ self,
497
+ root_dir: PathLike,
498
+ collection: str,
499
+ section: str,
500
+ transform: Sequence[Callable] | Callable = (),
501
+ download: bool = False,
502
+ download_len: int = -1,
503
+ seg_type: str = "SEG",
504
+ modality_tag: tuple = (0x0008, 0x0060),
505
+ ref_series_uid_tag: tuple = (0x0020, 0x000E),
506
+ ref_sop_uid_tag: tuple = (0x0008, 0x1155),
507
+ specific_tags: tuple = (
508
+ (0x0008, 0x1115), # Referenced Series Sequence
509
+ (0x0008, 0x1140), # Referenced Image Sequence
510
+ (0x3006, 0x0010), # Referenced Frame of Reference Sequence
511
+ (0x0020, 0x000D), # Study Instance UID
512
+ (0x0010, 0x0010), # Patient's Name
513
+ (0x0010, 0x0020), # Patient ID
514
+ (0x0020, 0x0011), # Series Number
515
+ (0x0020, 0x0012), # Acquisition Number
516
+ ),
517
+ fname_regex: str = DCM_FILENAME_REGEX,
518
+ seed: int = 0,
519
+ val_frac: float = 0.2,
520
+ cache_num: int = sys.maxsize,
521
+ cache_rate: float = 0.0,
522
+ num_workers: int = 1,
523
+ progress: bool = True,
524
+ copy_cache: bool = True,
525
+ as_contiguous: bool = True,
526
+ runtime_cache: bool = False,
527
+ ) -> None:
528
+ root_dir = Path(root_dir)
529
+ if not root_dir.is_dir():
530
+ raise ValueError("Root directory root_dir must be a directory.")
531
+
532
+ self.section = section
533
+ self.val_frac = val_frac
534
+ self.seg_type = seg_type
535
+ self.modality_tag = modality_tag
536
+ self.ref_series_uid_tag = ref_series_uid_tag
537
+ self.ref_sop_uid_tag = ref_sop_uid_tag
538
+
539
+ self.set_random_state(seed=seed)
540
+ download_dir = os.path.join(root_dir, collection)
541
+ load_tags = list(specific_tags)
542
+ load_tags += [modality_tag]
543
+ self.load_tags = load_tags
544
+ if download:
545
+ seg_series_list = get_tcia_metadata(
546
+ query=f"getSeries?Collection={collection}&Modality={seg_type}", attribute="SeriesInstanceUID"
547
+ )
548
+ if download_len > 0:
549
+ seg_series_list = seg_series_list[:download_len]
550
+ if len(seg_series_list) == 0:
551
+ raise ValueError(f"Cannot find data with collection: {collection} seg_type: {seg_type}")
552
+ for series_uid in seg_series_list:
553
+ self._download_series_reference_data(series_uid, download_dir)
554
+
555
+ if not os.path.exists(download_dir):
556
+ raise RuntimeError(f"Cannot find dataset directory: {download_dir}.")
557
+ self.fname_regex = fname_regex
558
+
559
+ self.indices: np.ndarray = np.array([])
560
+ self.datalist = self._generate_data_list(download_dir)
561
+
562
+ if transform == ():
563
+ transform = LoadImaged(keys=["image"], reader="PydicomReader", fname_regex=self.fname_regex)
564
+ CacheDataset.__init__(
565
+ self,
566
+ data=self.datalist,
567
+ transform=transform,
568
+ cache_num=cache_num,
569
+ cache_rate=cache_rate,
570
+ num_workers=num_workers,
571
+ progress=progress,
572
+ copy_cache=copy_cache,
573
+ as_contiguous=as_contiguous,
574
+ runtime_cache=runtime_cache,
575
+ )
576
+
577
+ def get_indices(self) -> np.ndarray:
578
+ """
579
+ Get the indices of datalist used in this dataset.
580
+
581
+ """
582
+ return self.indices
583
+
584
+ def randomize(self, data: np.ndarray) -> None:
585
+ self.R.shuffle(data)
586
+
587
+ def _download_series_reference_data(self, series_uid: str, download_dir: str) -> None:
588
+ """
589
+ First of all, download a series from TCIA according to `series_uid`.
590
+ Then find all referenced series and download.
591
+ """
592
+ seg_first_dir = os.path.join(download_dir, "raw", series_uid)
593
+ download_tcia_series_instance(
594
+ series_uid=series_uid, download_dir=download_dir, output_dir=seg_first_dir, check_md5=False
595
+ )
596
+ dicom_files = [f for f in sorted(os.listdir(seg_first_dir)) if f.endswith(".dcm")]
597
+ # achieve series number and patient id from the first dicom file
598
+ dcm_path = os.path.join(seg_first_dir, dicom_files[0])
599
+ ds = PydicomReader(stop_before_pixels=True, specific_tags=self.load_tags).read(dcm_path)
600
+ # (0x0010,0x0020) and (0x0010,0x0010), better to be contained in `specific_tags`
601
+ patient_id = ds.PatientID if ds.PatientID else ds.PatientName
602
+ if not patient_id:
603
+ warnings.warn(f"unable to find patient name of dicom file: {dcm_path}, use 'patient' instead.")
604
+ patient_id = "patient"
605
+ # (0x0020,0x0011) and (0x0020,0x0012), better to be contained in `specific_tags`
606
+ series_num = ds.SeriesNumber if ds.SeriesNumber else ds.AcquisitionNumber
607
+ if not series_num:
608
+ warnings.warn(f"unable to find series number of dicom file: {dcm_path}, use '0' instead.")
609
+ series_num = 0
610
+
611
+ series_num = str(series_num)
612
+ seg_dir = os.path.join(download_dir, patient_id, series_num, self.seg_type.lower())
613
+ dcm_dir = os.path.join(download_dir, patient_id, series_num, "image")
614
+
615
+ # get ref uuid
616
+ ref_uid_list = []
617
+ for dcm_file in dicom_files:
618
+ dcm_path = os.path.join(seg_first_dir, dcm_file)
619
+ ds = PydicomReader(stop_before_pixels=True, specific_tags=self.load_tags).read(dcm_path)
620
+ if ds[self.modality_tag].value == self.seg_type:
621
+ ref_uid = get_tcia_ref_uid(
622
+ ds, find_sop=False, ref_series_uid_tag=self.ref_series_uid_tag, ref_sop_uid_tag=self.ref_sop_uid_tag
623
+ )
624
+ if ref_uid == "":
625
+ ref_sop_uid = get_tcia_ref_uid(
626
+ ds,
627
+ find_sop=True,
628
+ ref_series_uid_tag=self.ref_series_uid_tag,
629
+ ref_sop_uid_tag=self.ref_sop_uid_tag,
630
+ )
631
+ ref_uid = match_tcia_ref_uid_in_study(ds.StudyInstanceUID, ref_sop_uid)
632
+ if ref_uid != "":
633
+ ref_uid_list.append(ref_uid)
634
+ if not ref_uid_list:
635
+ warnings.warn(f"Cannot find the referenced Series Instance UID from series: {series_uid}.")
636
+ else:
637
+ download_tcia_series_instance(
638
+ series_uid=ref_uid_list[0], download_dir=download_dir, output_dir=dcm_dir, check_md5=False
639
+ )
640
+ if not os.path.exists(seg_dir):
641
+ shutil.copytree(seg_first_dir, seg_dir)
642
+
643
+ def _generate_data_list(self, dataset_dir: PathLike) -> list[dict]:
644
+ # the types of the item in data list should be compatible with the dataloader
645
+ dataset_dir = Path(dataset_dir)
646
+ datalist = []
647
+ patient_list = [f.name for f in os.scandir(dataset_dir) if f.is_dir() and f.name != "raw"]
648
+ for patient_id in patient_list:
649
+ series_list = [f.name for f in os.scandir(os.path.join(dataset_dir, patient_id)) if f.is_dir()]
650
+ for series_num in series_list:
651
+ seg_key = self.seg_type.lower()
652
+ image_path = os.path.join(dataset_dir, patient_id, series_num, "image")
653
+ mask_path = os.path.join(dataset_dir, patient_id, series_num, seg_key)
654
+
655
+ if os.path.exists(image_path):
656
+ datalist.append({"image": image_path, seg_key: mask_path})
657
+ else:
658
+ datalist.append({seg_key: mask_path})
659
+
660
+ return self._split_datalist(datalist)
661
+
662
+ def _split_datalist(self, datalist: list[dict]) -> list[dict]:
663
+ if self.section == "test":
664
+ return datalist
665
+ length = len(datalist)
666
+ indices = np.arange(length)
667
+ self.randomize(indices)
668
+
669
+ val_length = int(length * self.val_frac)
670
+ if self.section == "training":
671
+ self.indices = indices[val_length:]
672
+ else:
673
+ self.indices = indices[:val_length]
674
+
675
+ return [datalist[i] for i in self.indices]
676
+
677
+
678
+ class CrossValidation:
679
+ """
680
+ Cross validation dataset based on the general dataset which must have `_split_datalist` API.
681
+
682
+ Args:
683
+ dataset_cls: dataset class to be used to create the cross validation partitions.
684
+ It must have `_split_datalist` API.
685
+ nfolds: number of folds to split the data for cross validation.
686
+ seed: random seed to randomly shuffle the datalist before splitting into N folds, default is 0.
687
+ dataset_params: other additional parameters for the dataset_cls base class.
688
+
689
+ Example of 5 folds cross validation training::
690
+
691
+ cvdataset = CrossValidation(
692
+ dataset_cls=DecathlonDataset,
693
+ nfolds=5,
694
+ seed=12345,
695
+ root_dir="./",
696
+ task="Task09_Spleen",
697
+ section="training",
698
+ transform=train_transform,
699
+ download=True,
700
+ )
701
+ dataset_fold0_train = cvdataset.get_dataset(folds=[1, 2, 3, 4])
702
+ dataset_fold0_val = cvdataset.get_dataset(folds=0, transform=val_transform, download=False)
703
+ # execute training for fold 0 ...
704
+
705
+ dataset_fold1_train = cvdataset.get_dataset(folds=[0, 2, 3, 4])
706
+ dataset_fold1_val = cvdataset.get_dataset(folds=1, transform=val_transform, download=False)
707
+ # execute training for fold 1 ...
708
+
709
+ ...
710
+
711
+ dataset_fold4_train = ...
712
+ # execute training for fold 4 ...
713
+
714
+ """
715
+
716
+ def __init__(self, dataset_cls: object, nfolds: int = 5, seed: int = 0, **dataset_params: Any) -> None:
717
+ if not hasattr(dataset_cls, "_split_datalist"):
718
+ raise ValueError("dataset class must have _split_datalist API.")
719
+ self.dataset_cls = dataset_cls
720
+ self.nfolds = nfolds
721
+ self.seed = seed
722
+ self.dataset_params = dataset_params
723
+
724
+ def get_dataset(self, folds: Sequence[int] | int, **dataset_params: Any) -> object:
725
+ """
726
+ Generate dataset based on the specified fold indices in the cross validation group.
727
+
728
+ Args:
729
+ folds: index of folds for training or validation, if a list of values, concatenate the data.
730
+ dataset_params: other additional parameters for the dataset_cls base class, will override
731
+ the same parameters in `self.dataset_params`.
732
+
733
+ """
734
+ nfolds = self.nfolds
735
+ seed = self.seed
736
+ dataset_params_ = dict(self.dataset_params)
737
+ dataset_params_.update(dataset_params)
738
+
739
+ class _NsplitsDataset(self.dataset_cls): # type: ignore
740
+
741
+ def _split_datalist(self, datalist: list[dict]) -> list[dict]:
742
+ data = partition_dataset(data=datalist, num_partitions=nfolds, shuffle=True, seed=seed)
743
+ return select_cross_validation_folds(partitions=data, folds=folds)
744
+
745
+ return _NsplitsDataset(**dataset_params_)
source_code/SegMamba/monai/apps/utils.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ import logging
17
+ import os
18
+ import shutil
19
+ import sys
20
+ import tarfile
21
+ import tempfile
22
+ import warnings
23
+ import zipfile
24
+ from pathlib import Path
25
+ from typing import TYPE_CHECKING, Any
26
+ from urllib.error import ContentTooShortError, HTTPError, URLError
27
+ from urllib.parse import urlparse
28
+ from urllib.request import urlopen, urlretrieve
29
+
30
+ from monai.config.type_definitions import PathLike
31
+ from monai.utils import look_up_option, min_version, optional_import
32
+
33
+ gdown, has_gdown = optional_import("gdown", "4.7.3")
34
+
35
+ if TYPE_CHECKING:
36
+ from tqdm import tqdm
37
+
38
+ has_tqdm = True
39
+ else:
40
+ tqdm, has_tqdm = optional_import("tqdm", "4.47.0", min_version, "tqdm")
41
+
42
+ __all__ = ["check_hash", "download_url", "extractall", "download_and_extract", "get_logger", "SUPPORTED_HASH_TYPES"]
43
+
44
+ DEFAULT_FMT = "%(asctime)s - %(levelname)s - %(message)s"
45
+ SUPPORTED_HASH_TYPES = {"md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512}
46
+
47
+
48
+ def get_logger(
49
+ module_name: str = "monai.apps",
50
+ fmt: str = DEFAULT_FMT,
51
+ datefmt: str | None = None,
52
+ logger_handler: logging.Handler | None = None,
53
+ ) -> logging.Logger:
54
+ """
55
+ Get a `module_name` logger with the specified format and date format.
56
+ By default, the logger will print to `stdout` at the INFO level.
57
+ If `module_name` is `None`, return the root logger.
58
+ `fmt` and `datafmt` are passed to a `logging.Formatter` object
59
+ (https://docs.python.org/3/library/logging.html#formatter-objects).
60
+ `logger_handler` can be used to add an additional handler.
61
+ """
62
+ adds_stdout_handler = module_name is not None and module_name not in logging.root.manager.loggerDict
63
+ logger = logging.getLogger(module_name)
64
+ logger.propagate = False
65
+ logger.setLevel(logging.INFO)
66
+ if adds_stdout_handler: # don't add multiple stdout or add to the root
67
+ handler = logging.StreamHandler(sys.stdout)
68
+ formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
69
+ handler.setFormatter(formatter)
70
+ logger.addHandler(handler)
71
+ if logger_handler is not None:
72
+ logger.addHandler(logger_handler)
73
+ return logger
74
+
75
+
76
+ # apps module-level default logger
77
+ logger = get_logger("monai.apps")
78
+ __all__.append("logger")
79
+
80
+
81
+ def _basename(p: PathLike) -> str:
82
+ """get the last part of the path (removing the trailing slash if it exists)"""
83
+ sep = os.path.sep + (os.path.altsep or "") + "/ "
84
+ return Path(f"{p}".rstrip(sep)).name
85
+
86
+
87
+ def _download_with_progress(url: str, filepath: Path, progress: bool = True) -> None:
88
+ """
89
+ Retrieve file from `url` to `filepath`, optionally showing a progress bar.
90
+ """
91
+ try:
92
+ if has_tqdm and progress:
93
+
94
+ class TqdmUpTo(tqdm):
95
+ """
96
+ Provides `update_to(n)` which uses `tqdm.update(delta_n)`.
97
+ Inspired by the example in https://github.com/tqdm/tqdm.
98
+ """
99
+
100
+ def update_to(self, b: int = 1, bsize: int = 1, tsize: int | None = None) -> None:
101
+ """
102
+ Args:
103
+ b: number of blocks transferred so far, default: 1.
104
+ bsize: size of each block (in tqdm units), default: 1.
105
+ tsize: total size (in tqdm units). if None, remains unchanged.
106
+ """
107
+ if tsize is not None:
108
+ self.total = tsize
109
+ self.update(b * bsize - self.n) # will also set self.n = b * bsize
110
+
111
+ with TqdmUpTo(unit="B", unit_scale=True, unit_divisor=1024, miniters=1, desc=_basename(filepath)) as t:
112
+ urlretrieve(url, filepath, reporthook=t.update_to)
113
+ else:
114
+ if not has_tqdm and progress:
115
+ warnings.warn("tqdm is not installed, will not show the downloading progress bar.")
116
+ urlretrieve(url, filepath)
117
+ except (URLError, HTTPError, ContentTooShortError, OSError) as e:
118
+ logger.error(f"Download failed from {url} to {filepath}.")
119
+ raise e
120
+
121
+
122
+ def check_hash(filepath: PathLike, val: str | None = None, hash_type: str = "md5") -> bool:
123
+ """
124
+ Verify hash signature of specified file.
125
+
126
+ Args:
127
+ filepath: path of source file to verify hash value.
128
+ val: expected hash value of the file.
129
+ hash_type: type of hash algorithm to use, default is `"md5"`.
130
+ The supported hash types are `"md5"`, `"sha1"`, `"sha256"`, `"sha512"`.
131
+ See also: :py:data:`monai.apps.utils.SUPPORTED_HASH_TYPES`.
132
+
133
+ """
134
+ if val is None:
135
+ logger.info(f"Expected {hash_type} is None, skip {hash_type} check for file {filepath}.")
136
+ return True
137
+ actual_hash_func = look_up_option(hash_type.lower(), SUPPORTED_HASH_TYPES)
138
+
139
+ if sys.version_info >= (3, 9):
140
+ actual_hash = actual_hash_func(usedforsecurity=False) # allows checks on FIPS enabled machines
141
+ else:
142
+ actual_hash = actual_hash_func()
143
+
144
+ try:
145
+ with open(filepath, "rb") as f:
146
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
147
+ actual_hash.update(chunk)
148
+ except Exception as e:
149
+ logger.error(f"Exception in check_hash: {e}")
150
+ return False
151
+ if val != actual_hash.hexdigest():
152
+ logger.error(f"check_hash failed {actual_hash.hexdigest()}.")
153
+ return False
154
+
155
+ logger.info(f"Verified '{_basename(filepath)}', {hash_type}: {val}.")
156
+ return True
157
+
158
+
159
+ def download_url(
160
+ url: str,
161
+ filepath: PathLike = "",
162
+ hash_val: str | None = None,
163
+ hash_type: str = "md5",
164
+ progress: bool = True,
165
+ **gdown_kwargs: Any,
166
+ ) -> None:
167
+ """
168
+ Download file from specified URL link, support process bar and hash check.
169
+
170
+ Args:
171
+ url: source URL link to download file.
172
+ filepath: target filepath to save the downloaded file (including the filename).
173
+ If undefined, `os.path.basename(url)` will be used.
174
+ hash_val: expected hash value to validate the downloaded file.
175
+ if None, skip hash validation.
176
+ hash_type: 'md5' or 'sha1', defaults to 'md5'.
177
+ progress: whether to display a progress bar.
178
+ gdown_kwargs: other args for `gdown` except for the `url`, `output` and `quiet`.
179
+ these args will only be used if download from google drive.
180
+ details of the args of it:
181
+ https://github.com/wkentaro/gdown/blob/main/gdown/download.py
182
+
183
+ Raises:
184
+ RuntimeError: When the hash validation of the ``filepath`` existing file fails.
185
+ RuntimeError: When a network issue or denied permission prevents the
186
+ file download from ``url`` to ``filepath``.
187
+ URLError: See urllib.request.urlretrieve.
188
+ HTTPError: See urllib.request.urlretrieve.
189
+ ContentTooShortError: See urllib.request.urlretrieve.
190
+ IOError: See urllib.request.urlretrieve.
191
+ RuntimeError: When the hash validation of the ``url`` downloaded file fails.
192
+
193
+ """
194
+ if not filepath:
195
+ filepath = Path(".", _basename(url)).resolve()
196
+ logger.info(f"Default downloading to '{filepath}'")
197
+ filepath = Path(filepath)
198
+ if filepath.exists():
199
+ if not check_hash(filepath, hash_val, hash_type):
200
+ raise RuntimeError(
201
+ f"{hash_type} check of existing file failed: filepath={filepath}, expected {hash_type}={hash_val}."
202
+ )
203
+ logger.info(f"File exists: {filepath}, skipped downloading.")
204
+ return
205
+ try:
206
+ with tempfile.TemporaryDirectory() as tmp_dir:
207
+ tmp_name = Path(tmp_dir, _basename(filepath))
208
+ if urlparse(url).netloc == "drive.google.com":
209
+ if not has_gdown:
210
+ raise RuntimeError("To download files from Google Drive, please install the gdown dependency.")
211
+ if "fuzzy" not in gdown_kwargs:
212
+ gdown_kwargs["fuzzy"] = True # default to true for flexible url
213
+ gdown.download(url, f"{tmp_name}", quiet=not progress, **gdown_kwargs)
214
+ elif urlparse(url).netloc == "cloud-api.yandex.net":
215
+ with urlopen(url) as response:
216
+ code = response.getcode()
217
+ if code == 200:
218
+ download_url = json.load(response)["href"]
219
+ _download_with_progress(download_url, tmp_name, progress=progress)
220
+ else:
221
+ raise RuntimeError(
222
+ f"Download of file from {download_url}, received from {url} "
223
+ + f" to {filepath} failed due to network issue or denied permission."
224
+ )
225
+ else:
226
+ _download_with_progress(url, tmp_name, progress=progress)
227
+ if not tmp_name.exists():
228
+ raise RuntimeError(
229
+ f"Download of file from {url} to {filepath} failed due to network issue or denied permission."
230
+ )
231
+ file_dir = filepath.parent
232
+ if file_dir:
233
+ os.makedirs(file_dir, exist_ok=True)
234
+ shutil.move(f"{tmp_name}", f"{filepath}") # copy the downloaded to a user-specified cache.
235
+ except (PermissionError, NotADirectoryError): # project-monai/monai issue #3613 #3757 for windows
236
+ pass
237
+ logger.info(f"Downloaded: {filepath}")
238
+ if not check_hash(filepath, hash_val, hash_type):
239
+ raise RuntimeError(
240
+ f"{hash_type} check of downloaded file failed: URL={url}, "
241
+ f"filepath={filepath}, expected {hash_type}={hash_val}."
242
+ )
243
+
244
+
245
+ def extractall(
246
+ filepath: PathLike,
247
+ output_dir: PathLike = ".",
248
+ hash_val: str | None = None,
249
+ hash_type: str = "md5",
250
+ file_type: str = "",
251
+ has_base: bool = True,
252
+ ) -> None:
253
+ """
254
+ Extract file to the output directory.
255
+ Expected file types are: `zip`, `tar.gz` and `tar`.
256
+
257
+ Args:
258
+ filepath: the file path of compressed file.
259
+ output_dir: target directory to save extracted files.
260
+ hash_val: expected hash value to validate the compressed file.
261
+ if None, skip hash validation.
262
+ hash_type: 'md5' or 'sha1', defaults to 'md5'.
263
+ file_type: string of file type for decompressing. Leave it empty to infer the type from the filepath basename.
264
+ has_base: whether the extracted files have a base folder. This flag is used when checking if the existing
265
+ folder is a result of `extractall`, if it is, the extraction is skipped. For example, if A.zip is unzipped
266
+ to folder structure `A/*.png`, this flag should be True; if B.zip is unzipped to `*.png`, this flag should
267
+ be False.
268
+
269
+ Raises:
270
+ RuntimeError: When the hash validation of the ``filepath`` compressed file fails.
271
+ NotImplementedError: When the ``filepath`` file extension is not one of [zip", "tar.gz", "tar"].
272
+
273
+ """
274
+ if has_base:
275
+ # the extracted files will be in this folder
276
+ cache_dir = Path(output_dir, _basename(filepath).split(".")[0])
277
+ else:
278
+ cache_dir = Path(output_dir)
279
+ if cache_dir.exists() and next(cache_dir.iterdir(), None) is not None:
280
+ logger.info(f"Non-empty folder exists in {cache_dir}, skipped extracting.")
281
+ return
282
+ filepath = Path(filepath)
283
+ if hash_val and not check_hash(filepath, hash_val, hash_type):
284
+ raise RuntimeError(
285
+ f"{hash_type} check of compressed file failed: " f"filepath={filepath}, expected {hash_type}={hash_val}."
286
+ )
287
+ logger.info(f"Writing into directory: {output_dir}.")
288
+ _file_type = file_type.lower().strip()
289
+ if filepath.name.endswith("zip") or _file_type == "zip":
290
+ zip_file = zipfile.ZipFile(filepath)
291
+ zip_file.extractall(output_dir)
292
+ zip_file.close()
293
+ return
294
+ if filepath.name.endswith("tar") or filepath.name.endswith("tar.gz") or "tar" in _file_type:
295
+ tar_file = tarfile.open(filepath)
296
+ tar_file.extractall(output_dir)
297
+ tar_file.close()
298
+ return
299
+ raise NotImplementedError(
300
+ f'Unsupported file type, available options are: ["zip", "tar.gz", "tar"]. name={filepath} type={file_type}.'
301
+ )
302
+
303
+
304
+ def download_and_extract(
305
+ url: str,
306
+ filepath: PathLike = "",
307
+ output_dir: PathLike = ".",
308
+ hash_val: str | None = None,
309
+ hash_type: str = "md5",
310
+ file_type: str = "",
311
+ has_base: bool = True,
312
+ progress: bool = True,
313
+ ) -> None:
314
+ """
315
+ Download file from URL and extract it to the output directory.
316
+
317
+ Args:
318
+ url: source URL link to download file.
319
+ filepath: the file path of the downloaded compressed file.
320
+ use this option to keep the directly downloaded compressed file, to avoid further repeated downloads.
321
+ output_dir: target directory to save extracted files.
322
+ default is the current directory.
323
+ hash_val: expected hash value to validate the downloaded file.
324
+ if None, skip hash validation.
325
+ hash_type: 'md5' or 'sha1', defaults to 'md5'.
326
+ file_type: string of file type for decompressing. Leave it empty to infer the type from url's base file name.
327
+ has_base: whether the extracted files have a base folder. This flag is used when checking if the existing
328
+ folder is a result of `extractall`, if it is, the extraction is skipped. For example, if A.zip is unzipped
329
+ to folder structure `A/*.png`, this flag should be True; if B.zip is unzipped to `*.png`, this flag should
330
+ be False.
331
+ progress: whether to display progress bar.
332
+ """
333
+ with tempfile.TemporaryDirectory() as tmp_dir:
334
+ filename = filepath or Path(tmp_dir, _basename(url)).resolve()
335
+ download_url(url=url, filepath=filename, hash_val=hash_val, hash_type=hash_type, progress=progress)
336
+ extractall(filepath=filename, output_dir=output_dir, file_type=file_type, has_base=has_base)
source_code/SegMamba/monai/auto3dseg/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from .algo_gen import Algo, AlgoGen
15
+ from .analyzer import (
16
+ Analyzer,
17
+ FgImageStats,
18
+ FgImageStatsSumm,
19
+ FilenameStats,
20
+ ImageStats,
21
+ ImageStatsSumm,
22
+ LabelStats,
23
+ LabelStatsSumm,
24
+ )
25
+ from .operations import Operations, SampleOperations, SummaryOperations
26
+ from .seg_summarizer import SegSummarizer
27
+ from .utils import (
28
+ algo_from_pickle,
29
+ algo_to_pickle,
30
+ concat_multikeys_to_dict,
31
+ concat_val_to_np,
32
+ datafold_read,
33
+ get_foreground_image,
34
+ get_foreground_label,
35
+ get_label_ccp,
36
+ verify_report_format,
37
+ )
source_code/SegMamba/monai/auto3dseg/algo_gen.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from monai.config import PathLike
15
+ from monai.transforms import Randomizable
16
+
17
+
18
+ class Algo:
19
+ """
20
+ An algorithm in this context is loosely defined as a data processing pipeline consisting of multiple components
21
+ such as image preprocessing, followed by deep learning model training and evaluation.
22
+ """
23
+
24
+ template_path: PathLike | None = None
25
+
26
+ def set_data_stats(self, *args, **kwargs):
27
+ """Provide dataset (and summaries) so that the model creation can depend on the input datasets."""
28
+ pass
29
+
30
+ def train(self, *args, **kwargs):
31
+ """Read training/validation data and output a model."""
32
+ pass
33
+
34
+ def predict(self, *args, **kwargs):
35
+ """Read test data and output model predictions."""
36
+ pass
37
+
38
+ def get_score(self, *args, **kwargs):
39
+ """Returns the model quality measurement based on training and validation datasets."""
40
+ pass
41
+
42
+ def get_output_path(self, *args, **kwargs):
43
+ """Returns the algo output paths for scripts location"""
44
+ pass
45
+
46
+
47
+ class AlgoGen(Randomizable):
48
+ """
49
+ A data-driven algorithm generator. It optionally takes the following inputs:
50
+
51
+ - training dataset properties (such as data statistics from ``monai.auto3dseg.analyzer``),
52
+ - previous algorithm's scores measuring the model quality,
53
+ - computational budgets,
54
+
55
+ and generates ``Algo`` instances. The generated algos are to be trained with the training datasets::
56
+
57
+ scores
58
+ +------------------------+
59
+ | +---------+ |
60
+ +-----------+ +-->| | +-----+----+
61
+ | Dataset, | | AlgoGen |--->| Algo |
62
+ | summaries |------>| | +----------+
63
+ +-----+-----+ +---------+ ^
64
+ | |
65
+ +----------------------------------+
66
+
67
+ This class also maintains a history of previously generated Algo and their corresponding validation scores.
68
+ The Algo generation process may be stochastic (using ``Randomizable.R`` as the source random state).
69
+ """
70
+
71
+ def set_data_stats(self, *args, **kwargs): # type ignore
72
+ """Provide dataset summaries/properties so that the generator can be conditioned on the input datasets."""
73
+ pass
74
+
75
+ def set_budget(self, *args, **kwargs):
76
+ """Provide computational budget so that the generator outputs algorithms that requires reasonable resources."""
77
+ pass
78
+
79
+ def set_score(self, *args, **kwargs):
80
+ """Feedback from the previously generated algo, the score can be used for new Algo generations."""
81
+ pass
82
+
83
+ def get_data_stats(self, *args, **kwargs):
84
+ """Get current dataset summaries."""
85
+ pass
86
+
87
+ def get_budget(self, *args, **kwargs):
88
+ """Get the current computational budget."""
89
+ pass
90
+
91
+ def get_history(self, *args, **kwargs):
92
+ """Get the previously generated algo."""
93
+ pass
94
+
95
+ def generate(self):
96
+ """Generate new Algo -- based on data_stats, budget, and history of previous algo generations."""
97
+ pass
98
+
99
+ def run_algo(self, *args, **kwargs):
100
+ """
101
+ Launch the Algos. This is useful for light-weight Algos where there's no need to distribute the training jobs.
102
+
103
+ If the generated Algos require significant scheduling of parallel executions, a job scheduler/controller
104
+ implemented separately is preferred to run them. In this case the controller should also report back the
105
+ scores and the algo history, so that the future ``AlgoGen.generate`` can leverage the information.
106
+ """
107
+ pass
source_code/SegMamba/monai/auto3dseg/analyzer.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import time
15
+ from abc import ABC, abstractmethod
16
+ from collections.abc import Hashable, Mapping
17
+ from copy import deepcopy
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from monai.apps.utils import get_logger
24
+ from monai.auto3dseg.operations import Operations, SampleOperations, SummaryOperations
25
+ from monai.auto3dseg.utils import (
26
+ concat_multikeys_to_dict,
27
+ concat_val_to_np,
28
+ get_foreground_image,
29
+ get_foreground_label,
30
+ get_label_ccp,
31
+ verify_report_format,
32
+ )
33
+ from monai.bundle.config_parser import ConfigParser
34
+ from monai.bundle.utils import ID_SEP_KEY
35
+ from monai.data import MetaTensor, affine_to_spacing
36
+ from monai.transforms.transform import MapTransform
37
+ from monai.transforms.utils_pytorch_numpy_unification import sum, unique
38
+ from monai.utils import convert_to_numpy
39
+ from monai.utils.enums import DataStatsKeys, ImageStatsKeys, LabelStatsKeys
40
+ from monai.utils.misc import ImageMetaKey, label_union
41
+
42
+ logger = get_logger(module_name=__name__)
43
+
44
+ __all__ = [
45
+ "Analyzer",
46
+ "ImageStats",
47
+ "FgImageStats",
48
+ "LabelStats",
49
+ "ImageStatsSumm",
50
+ "FgImageStatsSumm",
51
+ "LabelStatsSumm",
52
+ "FilenameStats",
53
+ "ImageHistogram",
54
+ "ImageHistogramSumm",
55
+ ]
56
+
57
+
58
+ class Analyzer(MapTransform, ABC):
59
+ """
60
+ The Analyzer component is a base class. Other classes inherit this class will provide a callable
61
+ with the same class name and produces one pre-formatted dictionary for the input data. The format
62
+ is pre-defined by the init function of the class that inherit this base class. Function operations
63
+ can also be registered before the runtime of the callable.
64
+
65
+ Args:
66
+ report_format: a dictionary that outlines the key structures of the report format.
67
+
68
+ """
69
+
70
+ def __init__(self, stats_name: str, report_format: dict) -> None:
71
+ super().__init__(None)
72
+ parser = ConfigParser(report_format, globals=False) # ConfigParser.globals not picklable
73
+ self.report_format = parser.get("")
74
+ self.stats_name = stats_name
75
+ self.ops = ConfigParser({}, globals=False)
76
+
77
+ def update_ops(self, key: str, op: Operations) -> None:
78
+ """
79
+ Register a statistical operation to the Analyzer and update the report_format.
80
+
81
+ Args:
82
+ key: value key in the report.
83
+ op: Operation sub-class object that represents statistical operations.
84
+
85
+ """
86
+ self.ops[key] = op
87
+ parser = ConfigParser(self.report_format)
88
+
89
+ if parser.get(key, "None") != "None":
90
+ parser[key] = op
91
+
92
+ self.report_format = parser.get("")
93
+
94
+ def update_ops_nested_label(self, nested_key: str, op: Operations) -> None:
95
+ """
96
+ Update operations for nested label format. Operation value in report_format will be resolved
97
+ to a dict with only keys.
98
+
99
+ Args:
100
+ nested_key: str that has format of 'key1#0#key2'.
101
+ op: Operation sub-class object that represents statistical operations.
102
+ """
103
+ keys = nested_key.split(ID_SEP_KEY)
104
+ if len(keys) != 3:
105
+ raise ValueError("Nested_key input format is wrong. Please ensure it is like key1#0#key2")
106
+ root: str
107
+ child_key: str
108
+ (root, _, child_key) = keys
109
+ if root not in self.ops:
110
+ self.ops[root] = [{}]
111
+ self.ops[root][0].update({child_key: None})
112
+
113
+ self.ops[nested_key] = op
114
+
115
+ parser = ConfigParser(self.report_format)
116
+ if parser.get(nested_key, "NA") != "NA":
117
+ parser[nested_key] = op
118
+
119
+ def get_report_format(self) -> dict:
120
+ """
121
+ Get the report format by resolving the registered operations recursively.
122
+
123
+ Returns:
124
+ a dictionary with {keys: None} pairs.
125
+
126
+ """
127
+ self.resolve_format(self.report_format)
128
+ return self.report_format # type: ignore[no-any-return]
129
+
130
+ @staticmethod
131
+ def unwrap_ops(func):
132
+ """
133
+ Unwrap a function value and generates the same set keys in a dict when the function is actually
134
+ called in runtime
135
+
136
+ Args:
137
+ func: Operation sub-class object that represents statistical operations. The func object
138
+ should have a `data` dictionary which stores the statistical operation information.
139
+ For some operations (ImageStats for example), it may also contain the data_addon
140
+ property, which is part of the update process.
141
+
142
+ Returns:
143
+ a dict with a set of keys.
144
+
145
+ """
146
+ ret = dict.fromkeys(list(func.data))
147
+ if hasattr(func, "data_addon"):
148
+ for key in func.data_addon:
149
+ ret.update({key: None})
150
+ return ret
151
+
152
+ def resolve_format(self, report: dict) -> None:
153
+ """
154
+ Resolve the format of the pre-defined report.
155
+
156
+ Args:
157
+ report: the dictionary to resolve. Values will be replaced in-place.
158
+
159
+ """
160
+ for k, v in report.items():
161
+ if isinstance(v, Operations):
162
+ report[k] = self.unwrap_ops(v)
163
+ elif isinstance(v, list) and len(v) > 0:
164
+ self.resolve_format(v[0])
165
+ else:
166
+ report[k] = v
167
+
168
+ @abstractmethod
169
+ def __call__(self, data: Any) -> dict:
170
+ """Analyze the dict format dataset, return the summary report"""
171
+ raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.")
172
+
173
+
174
+ class ImageStats(Analyzer):
175
+ """
176
+ Analyzer to extract image stats properties for each case(image).
177
+
178
+ Args:
179
+ image_key: the key to find image data in the callable function input (data)
180
+
181
+ Examples:
182
+
183
+ .. code-block:: python
184
+
185
+ import numpy as np
186
+ from monai.auto3dseg import ImageStats
187
+ from monai.data import MetaTensor
188
+
189
+ input = {}
190
+ input['image'] = np.random.rand(1,30,30,30)
191
+ input['image'] = MetaTensor(np.random.rand(1,30,30,30)) # MetaTensor
192
+ analyzer = ImageStats(image_key="image")
193
+ print(analyzer(input)["image_stats"])
194
+
195
+ Notes:
196
+ if the image data is NumPy array, the spacing stats will be [1.0] * `ndims` of the array,
197
+ where the `ndims` is the lesser value between the image dimension and 3.
198
+
199
+ """
200
+
201
+ def __init__(self, image_key: str, stats_name: str = DataStatsKeys.IMAGE_STATS) -> None:
202
+ if not isinstance(image_key, str):
203
+ raise ValueError("image_key input must be str")
204
+
205
+ self.image_key = image_key
206
+
207
+ report_format = {
208
+ ImageStatsKeys.SHAPE: None,
209
+ ImageStatsKeys.CHANNELS: None,
210
+ ImageStatsKeys.CROPPED_SHAPE: None,
211
+ ImageStatsKeys.SPACING: None,
212
+ ImageStatsKeys.SIZEMM: None,
213
+ ImageStatsKeys.INTENSITY: None,
214
+ }
215
+
216
+ super().__init__(stats_name, report_format)
217
+ self.update_ops(ImageStatsKeys.INTENSITY, SampleOperations())
218
+
219
+ def __call__(self, data):
220
+ """
221
+ Callable to execute the pre-defined functions
222
+
223
+ Returns:
224
+ A dictionary. The dict has the key in self.report_format. The value of
225
+ ImageStatsKeys.INTENSITY is in a list format. Each element of the value list
226
+ has stats pre-defined by SampleOperations (max, min, ....).
227
+
228
+ Raises:
229
+ RuntimeError if the stats report generated is not consistent with the pre-
230
+ defined report_format.
231
+
232
+ Note:
233
+ The stats operation uses numpy and torch to compute max, min, and other
234
+ functions. If the input has nan/inf, the stats results will be nan/inf.
235
+
236
+ """
237
+ d = dict(data)
238
+ start = time.time()
239
+ restore_grad_state = torch.is_grad_enabled()
240
+ torch.set_grad_enabled(False)
241
+
242
+ ndas = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])]
243
+ if "nda_croppeds" not in d:
244
+ nda_croppeds = [get_foreground_image(nda) for nda in ndas]
245
+
246
+ # perform calculation
247
+ report = deepcopy(self.get_report_format())
248
+
249
+ report[ImageStatsKeys.SHAPE] = [list(nda.shape) for nda in ndas]
250
+ report[ImageStatsKeys.CHANNELS] = len(ndas)
251
+ report[ImageStatsKeys.CROPPED_SHAPE] = [list(nda_c.shape) for nda_c in nda_croppeds]
252
+ report[ImageStatsKeys.SPACING] = (
253
+ affine_to_spacing(data[self.image_key].affine).tolist()
254
+ if isinstance(data[self.image_key], MetaTensor)
255
+ else [1.0] * min(3, data[self.image_key].ndim)
256
+ )
257
+
258
+ report[ImageStatsKeys.SIZEMM] = [
259
+ a * b for a, b in zip(report[ImageStatsKeys.SHAPE][0], report[ImageStatsKeys.SPACING])
260
+ ]
261
+
262
+ report[ImageStatsKeys.INTENSITY] = [
263
+ self.ops[ImageStatsKeys.INTENSITY].evaluate(nda_c) for nda_c in nda_croppeds
264
+ ]
265
+
266
+ if not verify_report_format(report, self.get_report_format()):
267
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
268
+
269
+ d[self.stats_name] = report
270
+
271
+ torch.set_grad_enabled(restore_grad_state)
272
+ logger.debug(f"Get image stats spent {time.time()-start}")
273
+ return d
274
+
275
+
276
+ class FgImageStats(Analyzer):
277
+ """
278
+ Analyzer to extract foreground label properties for each case(image and label).
279
+
280
+ Args:
281
+ image_key: the key to find image data in the callable function input (data)
282
+ label_key: the key to find label data in the callable function input (data)
283
+
284
+ Examples:
285
+
286
+ .. code-block:: python
287
+
288
+ import numpy as np
289
+ from monai.auto3dseg import FgImageStats
290
+
291
+ input = {}
292
+ input['image'] = np.random.rand(1,30,30,30)
293
+ input['label'] = np.ones([30,30,30])
294
+ analyzer = FgImageStats(image_key='image', label_key='label')
295
+ print(analyzer(input)["image_foreground_stats"])
296
+
297
+ """
298
+
299
+ def __init__(self, image_key: str, label_key: str, stats_name: str = DataStatsKeys.FG_IMAGE_STATS):
300
+ self.image_key = image_key
301
+ self.label_key = label_key
302
+
303
+ report_format = {ImageStatsKeys.INTENSITY: None}
304
+
305
+ super().__init__(stats_name, report_format)
306
+ self.update_ops(ImageStatsKeys.INTENSITY, SampleOperations())
307
+
308
+ def __call__(self, data: Mapping) -> dict:
309
+ """
310
+ Callable to execute the pre-defined functions
311
+
312
+ Returns:
313
+ A dictionary. The dict has the key in self.report_format and value
314
+ in a list format. Each element of the value list has stats pre-defined
315
+ by SampleOperations (max, min, ....).
316
+
317
+ Raises:
318
+ RuntimeError if the stats report generated is not consistent with the pre-
319
+ defined report_format.
320
+
321
+ Note:
322
+ The stats operation uses numpy and torch to compute max, min, and other
323
+ functions. If the input has nan/inf, the stats results will be nan/inf.
324
+ """
325
+
326
+ d = dict(data)
327
+ start = time.time()
328
+ restore_grad_state = torch.is_grad_enabled()
329
+ torch.set_grad_enabled(False)
330
+
331
+ ndas = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])]
332
+ ndas_label = d[self.label_key] # (H,W,D)
333
+
334
+ if ndas_label.shape != ndas[0].shape:
335
+ raise ValueError(f"Label shape {ndas_label.shape} is different from image shape {ndas[0].shape}")
336
+
337
+ nda_foregrounds = [get_foreground_label(nda, ndas_label) for nda in ndas]
338
+ nda_foregrounds = [nda if nda.numel() > 0 else MetaTensor([0.0]) for nda in nda_foregrounds]
339
+
340
+ # perform calculation
341
+ report = deepcopy(self.get_report_format())
342
+
343
+ report[ImageStatsKeys.INTENSITY] = [
344
+ self.ops[ImageStatsKeys.INTENSITY].evaluate(nda_f) for nda_f in nda_foregrounds
345
+ ]
346
+
347
+ if not verify_report_format(report, self.get_report_format()):
348
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
349
+
350
+ d[self.stats_name] = report
351
+
352
+ torch.set_grad_enabled(restore_grad_state)
353
+ logger.debug(f"Get foreground image stats spent {time.time()-start}")
354
+ return d
355
+
356
+
357
+ class LabelStats(Analyzer):
358
+ """
359
+ Analyzer to extract label stats properties for each case(image and label).
360
+
361
+ Args:
362
+ image_key: the key to find image data in the callable function input (data)
363
+ label_key: the key to find label data in the callable function input (data)
364
+ do_ccp: performs connected component analysis. Default is True.
365
+
366
+ Examples:
367
+
368
+ .. code-block:: python
369
+
370
+ import numpy as np
371
+ from monai.auto3dseg import LabelStats
372
+
373
+ input = {}
374
+ input['image'] = np.random.rand(1,30,30,30)
375
+ input['label'] = np.ones([30,30,30])
376
+ analyzer = LabelStats(image_key='image', label_key='label')
377
+ print(analyzer(input)["label_stats"])
378
+
379
+ """
380
+
381
+ def __init__(
382
+ self, image_key: str, label_key: str, stats_name: str = DataStatsKeys.LABEL_STATS, do_ccp: bool | None = True
383
+ ):
384
+ self.image_key = image_key
385
+ self.label_key = label_key
386
+ self.do_ccp = do_ccp
387
+
388
+ report_format: dict[LabelStatsKeys, Any] = {
389
+ LabelStatsKeys.LABEL_UID: None,
390
+ LabelStatsKeys.IMAGE_INTST: None,
391
+ LabelStatsKeys.LABEL: [{LabelStatsKeys.PIXEL_PCT: None, LabelStatsKeys.IMAGE_INTST: None}],
392
+ }
393
+
394
+ if self.do_ccp:
395
+ report_format[LabelStatsKeys.LABEL][0].update(
396
+ {LabelStatsKeys.LABEL_SHAPE: None, LabelStatsKeys.LABEL_NCOMP: None}
397
+ )
398
+
399
+ super().__init__(stats_name, report_format)
400
+ self.update_ops(LabelStatsKeys.IMAGE_INTST, SampleOperations())
401
+
402
+ id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.IMAGE_INTST])
403
+ self.update_ops_nested_label(id_seq, SampleOperations())
404
+
405
+ def __call__(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTensor | dict]:
406
+ """
407
+ Callable to execute the pre-defined functions.
408
+
409
+ Returns:
410
+ A dictionary. The dict has the key in self.report_format and value
411
+ in a list format. Each element of the value list has stats pre-defined
412
+ by SampleOperations (max, min, ....).
413
+
414
+ Examples:
415
+ output dict contains {
416
+ LabelStatsKeys.LABEL_UID:[0,1,3],
417
+ LabelStatsKeys.IMAGE_INTST: {...},
418
+ LabelStatsKeys.LABEL:[
419
+ {
420
+ LabelStatsKeys.PIXEL_PCT: 0.8,
421
+ LabelStatsKeys.IMAGE_INTST: {...},
422
+ LabelStatsKeys.LABEL_SHAPE: [...],
423
+ LabelStatsKeys.LABEL_NCOMP: 1
424
+ }
425
+ {
426
+ LabelStatsKeys.PIXEL_PCT: 0.1,
427
+ LabelStatsKeys.IMAGE_INTST: {...},
428
+ LabelStatsKeys.LABEL_SHAPE: [...],
429
+ LabelStatsKeys.LABEL_NCOMP: 1
430
+ }
431
+ {
432
+ LabelStatsKeys.PIXEL_PCT: 0.1,
433
+ LabelStatsKeys.IMAGE_INTST: {...},
434
+ LabelStatsKeys.LABEL_SHAPE: [...],
435
+ LabelStatsKeys.LABEL_NCOMP: 1
436
+ }
437
+ ]
438
+ }
439
+
440
+ Raises:
441
+ RuntimeError if the stats report generated is not consistent with the pre-
442
+ defined report_format.
443
+
444
+ Notes:
445
+ The label class_ID of the dictionary in LabelStatsKeys.LABEL IS NOT the
446
+ index. Instead, the class_ID is the LabelStatsKeys.LABEL_UID with the same
447
+ index. For instance, the last dict in LabelStatsKeys.LABEL in the Examples
448
+ is 3, which is the last element under LabelStatsKeys.LABEL_UID.
449
+
450
+ The stats operation uses numpy and torch to compute max, min, and other
451
+ functions. If the input has nan/inf, the stats results will be nan/inf.
452
+ """
453
+ d: dict[Hashable, MetaTensor] = dict(data)
454
+ start = time.time()
455
+ if isinstance(d[self.image_key], (torch.Tensor, MetaTensor)) and d[self.image_key].device.type == "cuda":
456
+ using_cuda = True
457
+ else:
458
+ using_cuda = False
459
+ restore_grad_state = torch.is_grad_enabled()
460
+ torch.set_grad_enabled(False)
461
+
462
+ ndas: list[MetaTensor] = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])] # type: ignore
463
+ ndas_label: MetaTensor = d[self.label_key].astype(torch.int16) # (H,W,D)
464
+
465
+ if ndas_label.shape != ndas[0].shape:
466
+ raise ValueError(f"Label shape {ndas_label.shape} is different from image shape {ndas[0].shape}")
467
+
468
+ nda_foregrounds: list[torch.Tensor] = [get_foreground_label(nda, ndas_label) for nda in ndas]
469
+ nda_foregrounds = [nda if nda.numel() > 0 else torch.Tensor([0]) for nda in nda_foregrounds]
470
+
471
+ unique_label = unique(ndas_label)
472
+ if isinstance(ndas_label, (MetaTensor, torch.Tensor)):
473
+ unique_label = unique_label.data.cpu().numpy()
474
+
475
+ unique_label = unique_label.astype(np.int16).tolist()
476
+
477
+ label_substats = [] # each element is one label
478
+ pixel_sum = 0
479
+ pixel_arr = []
480
+ for index in unique_label:
481
+ start_label = time.time()
482
+ label_dict: dict[str, Any] = {}
483
+ mask_index = ndas_label == index
484
+
485
+ nda_masks = [nda[mask_index] for nda in ndas]
486
+ label_dict[LabelStatsKeys.IMAGE_INTST] = [
487
+ self.ops[LabelStatsKeys.IMAGE_INTST].evaluate(nda_m) for nda_m in nda_masks
488
+ ]
489
+
490
+ pixel_count = sum(mask_index)
491
+ pixel_arr.append(pixel_count)
492
+ pixel_sum += pixel_count
493
+ if self.do_ccp: # apply connected component
494
+ if using_cuda:
495
+ # The back end of get_label_ccp is CuPy
496
+ # which is unable to automatically release CUDA GPU memory held by PyTorch
497
+ del nda_masks
498
+ torch.cuda.empty_cache()
499
+ shape_list, ncomponents = get_label_ccp(mask_index)
500
+ label_dict[LabelStatsKeys.LABEL_SHAPE] = shape_list
501
+ label_dict[LabelStatsKeys.LABEL_NCOMP] = ncomponents
502
+
503
+ label_substats.append(label_dict)
504
+ logger.debug(f" label {index} stats takes {time.time() - start_label}")
505
+
506
+ for i, _ in enumerate(unique_label):
507
+ label_substats[i].update({LabelStatsKeys.PIXEL_PCT: float(pixel_arr[i] / pixel_sum)})
508
+
509
+ report = deepcopy(self.get_report_format())
510
+ report[LabelStatsKeys.LABEL_UID] = unique_label
511
+ report[LabelStatsKeys.IMAGE_INTST] = [
512
+ self.ops[LabelStatsKeys.IMAGE_INTST].evaluate(nda_f) for nda_f in nda_foregrounds
513
+ ]
514
+ report[LabelStatsKeys.LABEL] = label_substats
515
+
516
+ if not verify_report_format(report, self.get_report_format()):
517
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
518
+
519
+ d[self.stats_name] = report # type: ignore[assignment]
520
+
521
+ torch.set_grad_enabled(restore_grad_state)
522
+ logger.debug(f"Get label stats spent {time.time()-start}")
523
+ return d # type: ignore[return-value]
524
+
525
+
526
+ class ImageStatsSumm(Analyzer):
527
+ """
528
+ This summary analyzer processes the values of specific key `stats_name` in a list of dict.
529
+ Typically, the list of dict is the output of case analyzer under the same prefix
530
+ (ImageStats).
531
+
532
+ Args:
533
+ stats_name: the key of the to-process value in the dict.
534
+ average: whether to average the statistical value across different image modalities.
535
+
536
+ """
537
+
538
+ def __init__(self, stats_name: str = DataStatsKeys.IMAGE_STATS, average: bool | None = True):
539
+ self.summary_average = average
540
+ report_format = {
541
+ ImageStatsKeys.SHAPE: None,
542
+ ImageStatsKeys.CHANNELS: None,
543
+ ImageStatsKeys.CROPPED_SHAPE: None,
544
+ ImageStatsKeys.SPACING: None,
545
+ ImageStatsKeys.SIZEMM: None,
546
+ ImageStatsKeys.INTENSITY: None,
547
+ }
548
+ super().__init__(stats_name, report_format)
549
+
550
+ self.update_ops(ImageStatsKeys.SHAPE, SampleOperations())
551
+ self.update_ops(ImageStatsKeys.CHANNELS, SampleOperations())
552
+ self.update_ops(ImageStatsKeys.CROPPED_SHAPE, SampleOperations())
553
+ self.update_ops(ImageStatsKeys.SPACING, SampleOperations())
554
+ self.update_ops(ImageStatsKeys.SIZEMM, SampleOperations())
555
+ self.update_ops(ImageStatsKeys.INTENSITY, SummaryOperations())
556
+
557
+ def __call__(self, data: list[dict]) -> dict:
558
+ """
559
+ Callable to execute the pre-defined functions
560
+
561
+ Returns:
562
+ A dictionary. The dict has the key in self.report_format and value
563
+ in a list format. Each element of the value list has stats pre-defined
564
+ by SampleOperations (max, min, ....).
565
+
566
+ Raises:
567
+ RuntimeError if the stats report generated is not consistent with the pre-
568
+ defined report_format.
569
+
570
+ Examples:
571
+ output dict contains a dictionary for all of the following keys{
572
+ ImageStatsKeys.SHAPE:{...}
573
+ ImageStatsKeys.CHANNELS: {...},
574
+ ImageStatsKeys.CROPPED_SHAPE: {...},
575
+ ImageStatsKeys.SPACING: {...},
576
+ ImageStatsKeys.SIZEMM: {...},
577
+ ImageStatsKeys.INTENSITY: {...},
578
+ }
579
+
580
+ Notes:
581
+ The stats operation uses numpy and torch to compute max, min, and other
582
+ functions. If the input has nan/inf, the stats results will be nan/inf.
583
+ """
584
+ if not isinstance(data, list):
585
+ raise ValueError(f"Callable {self.__class__} requires list inputs")
586
+
587
+ if len(data) == 0:
588
+ raise ValueError(f"Callable {self.__class__} input list is empty")
589
+
590
+ if self.stats_name not in data[0]:
591
+ raise KeyError(f"{self.stats_name} is not in input data")
592
+
593
+ report = deepcopy(self.get_report_format())
594
+
595
+ for k in [
596
+ ImageStatsKeys.SHAPE,
597
+ ImageStatsKeys.CHANNELS,
598
+ ImageStatsKeys.CROPPED_SHAPE,
599
+ ImageStatsKeys.SPACING,
600
+ ImageStatsKeys.SIZEMM,
601
+ ]:
602
+ v_np = concat_val_to_np(data, [self.stats_name, k])
603
+ report[k] = self.ops[k].evaluate(v_np, dim=(0, 1) if v_np.ndim > 2 and self.summary_average else 0)
604
+
605
+ intst_str = ImageStatsKeys.INTENSITY
606
+ op_keys = report[intst_str].keys() # template, max/min/...
607
+ intst_dict = concat_multikeys_to_dict(data, [self.stats_name, intst_str], op_keys)
608
+ report[intst_str] = self.ops[intst_str].evaluate(intst_dict, dim=None if self.summary_average else 0)
609
+
610
+ if not verify_report_format(report, self.get_report_format()):
611
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
612
+
613
+ return report
614
+
615
+
616
+ class FgImageStatsSumm(Analyzer):
617
+ """
618
+ This summary analyzer processes the values of specific key `stats_name` in a list of
619
+ dict. Typically, the list of dict is the output of case analyzer under the similar name
620
+ (FgImageStats).
621
+
622
+ Args:
623
+ stats_name: the key of the to-process value in the dict.
624
+ average: whether to average the statistical value across different image modalities.
625
+
626
+ """
627
+
628
+ def __init__(self, stats_name: str = DataStatsKeys.FG_IMAGE_STATS, average: bool | None = True):
629
+ self.summary_average = average
630
+
631
+ report_format = {ImageStatsKeys.INTENSITY: None}
632
+ super().__init__(stats_name, report_format)
633
+ self.update_ops(ImageStatsKeys.INTENSITY, SummaryOperations())
634
+
635
+ def __call__(self, data: list[dict]) -> dict:
636
+ """
637
+ Callable to execute the pre-defined functions.
638
+
639
+ Returns:
640
+ A dictionary. The dict has the key in self.report_format and value
641
+ in a list format. Each element of the value list has stats pre-defined
642
+ by SampleOperations (max, min, ....) and SummaryOperation (max of the
643
+ max, mean of the mean, etc).
644
+
645
+ Raises:
646
+ RuntimeError if the stats report generated is not consistent with the pre-
647
+ defined report_format.
648
+
649
+ Examples:
650
+ output dict contains a dictionary for all of the following keys{
651
+ ImageStatsKeys.INTENSITY: {...},
652
+ }
653
+
654
+ Notes:
655
+ The stats operation uses numpy and torch to compute max, min, and other
656
+ functions. If the input has nan/inf, the stats results will be nan/inf.
657
+ """
658
+ if not isinstance(data, list):
659
+ raise ValueError(f"Callable {self.__class__} requires list inputs")
660
+
661
+ if len(data) == 0:
662
+ raise ValueError(f"Callable {self.__class__} input list is empty")
663
+
664
+ if self.stats_name not in data[0]:
665
+ raise KeyError(f"{self.stats_name} is not in input data.")
666
+
667
+ report = deepcopy(self.get_report_format())
668
+ intst_str = ImageStatsKeys.INTENSITY
669
+ op_keys = report[intst_str].keys() # template, max/min/...
670
+ intst_dict = concat_multikeys_to_dict(data, [self.stats_name, intst_str], op_keys)
671
+
672
+ report[intst_str] = self.ops[intst_str].evaluate(intst_dict, dim=None if self.summary_average else 0)
673
+
674
+ if not verify_report_format(report, self.get_report_format()):
675
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
676
+
677
+ return report
678
+
679
+
680
+ class LabelStatsSumm(Analyzer):
681
+ """
682
+ This summary analyzer processes the values of specific key `stats_name` in a list of
683
+ dict. Typically, the list of dict is the output of case analyzer under the similar name
684
+ (LabelStats).
685
+
686
+ Args:
687
+ stats_name: the key of the to-process value in the dict.
688
+ average: whether to average the statistical value across different image modalities.
689
+
690
+ """
691
+
692
+ def __init__(
693
+ self, stats_name: str = DataStatsKeys.LABEL_STATS, average: bool | None = True, do_ccp: bool | None = True
694
+ ):
695
+ self.summary_average = average
696
+ self.do_ccp = do_ccp
697
+
698
+ report_format: dict[str, Any] = {
699
+ LabelStatsKeys.LABEL_UID: None,
700
+ LabelStatsKeys.IMAGE_INTST: None,
701
+ LabelStatsKeys.LABEL: [{LabelStatsKeys.PIXEL_PCT: None, LabelStatsKeys.IMAGE_INTST: None}],
702
+ }
703
+ if self.do_ccp:
704
+ report_format[LabelStatsKeys.LABEL][0].update(
705
+ {LabelStatsKeys.LABEL_SHAPE: None, LabelStatsKeys.LABEL_NCOMP: None}
706
+ )
707
+
708
+ super().__init__(stats_name, report_format)
709
+ self.update_ops(LabelStatsKeys.IMAGE_INTST, SummaryOperations())
710
+
711
+ # label-0-'pixel percentage'
712
+ id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.PIXEL_PCT])
713
+ self.update_ops_nested_label(id_seq, SampleOperations())
714
+ # label-0-'image intensity'
715
+ id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.IMAGE_INTST])
716
+ self.update_ops_nested_label(id_seq, SummaryOperations())
717
+ # label-0-shape
718
+ id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.LABEL_SHAPE])
719
+ self.update_ops_nested_label(id_seq, SampleOperations())
720
+ # label-0-ncomponents
721
+ id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.LABEL_NCOMP])
722
+ self.update_ops_nested_label(id_seq, SampleOperations())
723
+
724
+ def __call__(self, data: list[dict]) -> dict:
725
+ """
726
+ Callable to execute the pre-defined functions
727
+
728
+ Returns:
729
+ A dictionary. The dict has the key in self.report_format and value
730
+ in a list format. Each element of the value list has stats pre-defined
731
+ by SampleOperations (max, min, ....) and SummaryOperation (max of the
732
+ max, mean of the mean, etc).
733
+
734
+ Raises:
735
+ RuntimeError if the stats report generated is not consistent with the pre-
736
+ defined report_format.
737
+
738
+ Notes:
739
+ The stats operation uses numpy and torch to compute max, min, and other
740
+ functions. If the input has nan/inf, the stats results will be nan/inf.
741
+ """
742
+ if not isinstance(data, list):
743
+ raise ValueError(f"Callable {self.__class__} requires list inputs")
744
+
745
+ if len(data) == 0:
746
+ raise ValueError(f"Callable {self.__class__} input list is empty")
747
+
748
+ if self.stats_name not in data[0]:
749
+ raise KeyError(f"{self.stats_name} is not in input data")
750
+
751
+ report = deepcopy(self.get_report_format())
752
+ # unique class ID
753
+ uid_np = concat_val_to_np(data, [self.stats_name, LabelStatsKeys.LABEL_UID], axis=None, ragged=True)
754
+ unique_label = label_union(uid_np)
755
+ report[LabelStatsKeys.LABEL_UID] = unique_label
756
+
757
+ # image intensity
758
+ intst_str = LabelStatsKeys.IMAGE_INTST
759
+ op_keys = report[intst_str].keys() # template, max/min/...
760
+ intst_dict = concat_multikeys_to_dict(data, [self.stats_name, intst_str], op_keys)
761
+ report[intst_str] = self.ops[intst_str].evaluate(intst_dict, dim=None if self.summary_average else 0)
762
+
763
+ detailed_label_list = []
764
+ # iterate through each label
765
+ label_str = LabelStatsKeys.LABEL
766
+ for label_id in unique_label:
767
+ stats = {}
768
+
769
+ pct_str = LabelStatsKeys.PIXEL_PCT
770
+ pct_fixed_keys = [self.stats_name, label_str, label_id, pct_str]
771
+ pct_np = concat_val_to_np(data, pct_fixed_keys, allow_missing=True)
772
+ stats[pct_str] = self.ops[label_str][0][pct_str].evaluate(
773
+ pct_np, dim=(0, 1) if pct_np.ndim > 2 and self.summary_average else 0
774
+ )
775
+
776
+ if self.do_ccp:
777
+ ncomp_str = LabelStatsKeys.LABEL_NCOMP
778
+ ncomp_fixed_keys = [self.stats_name, LabelStatsKeys.LABEL, label_id, ncomp_str]
779
+ ncomp_np = concat_val_to_np(data, ncomp_fixed_keys, allow_missing=True)
780
+ stats[ncomp_str] = self.ops[label_str][0][ncomp_str].evaluate(
781
+ ncomp_np, dim=(0, 1) if ncomp_np.ndim > 2 and self.summary_average else 0
782
+ )
783
+
784
+ shape_str = LabelStatsKeys.LABEL_SHAPE
785
+ shape_fixed_keys = [self.stats_name, label_str, label_id, LabelStatsKeys.LABEL_SHAPE]
786
+ shape_np = concat_val_to_np(data, shape_fixed_keys, ragged=True, allow_missing=True)
787
+ stats[shape_str] = self.ops[label_str][0][shape_str].evaluate(
788
+ shape_np, dim=(0, 1) if shape_np.ndim > 2 and self.summary_average else 0
789
+ )
790
+ # label shape is a 3-element value, but the number of labels in each image
791
+ # can vary from 0 to N. So the value in a list format is "ragged"
792
+
793
+ intst_str = LabelStatsKeys.IMAGE_INTST
794
+ intst_fixed_keys = [self.stats_name, label_str, label_id, intst_str]
795
+ op_keys = report[label_str][0][intst_str].keys()
796
+ intst_dict = concat_multikeys_to_dict(data, intst_fixed_keys, op_keys, allow_missing=True)
797
+ stats[intst_str] = self.ops[label_str][0][intst_str].evaluate(
798
+ intst_dict, dim=None if self.summary_average else 0
799
+ )
800
+
801
+ detailed_label_list.append(stats)
802
+
803
+ report[LabelStatsKeys.LABEL] = detailed_label_list
804
+
805
+ if not verify_report_format(report, self.get_report_format()):
806
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
807
+
808
+ return report
809
+
810
+
811
+ class FilenameStats(Analyzer):
812
+ """
813
+ This class finds the file path for the loaded image/label and writes the info
814
+ into the data pipeline as a monai transforms.
815
+
816
+ Args:
817
+ key: the key to fetch the filename (for example, "image", "label").
818
+ stats_name: the key to store the filename in the output stats report.
819
+
820
+ """
821
+
822
+ def __init__(self, key: str | None, stats_name: str) -> None:
823
+ self.key = key
824
+ super().__init__(stats_name, {})
825
+
826
+ def __call__(self, data):
827
+ d = dict(data)
828
+
829
+ if self.key: # when there is no (label) file, key can be None
830
+ if self.key not in d: # check whether image/label is in the data
831
+ raise ValueError(f"Data with key {self.key} is missing.")
832
+ if not isinstance(d[self.key], MetaTensor):
833
+ raise ValueError(f"Value type of {self.key} is not MetaTensor.")
834
+ if ImageMetaKey.FILENAME_OR_OBJ not in d[self.key].meta:
835
+ raise ValueError(f"{ImageMetaKey.FILENAME_OR_OBJ} not found in MetaTensor {d[self.key]}.")
836
+ d[self.stats_name] = d[self.key].meta[ImageMetaKey.FILENAME_OR_OBJ]
837
+ else:
838
+ d[self.stats_name] = "None"
839
+
840
+ return d
841
+
842
+
843
+ class ImageHistogram(Analyzer):
844
+ """
845
+ Analyzer to compute intensity histogram.
846
+
847
+ Args:
848
+ image_key: the key to find image data in the callable function input (data)
849
+ hist_bins: list of positive integers (one for each channel) for setting the number of bins used to
850
+ compute the histogram. Defaults to [100].
851
+ hist_range: list of lists of two floats (one for each channel) setting the intensity range to
852
+ compute the histogram. Defaults to [-500, 500].
853
+
854
+ Examples:
855
+
856
+ .. code-block:: python
857
+
858
+ import numpy as np
859
+ from monai.auto3dseg.analyzer import ImageHistogram
860
+
861
+ input = {}
862
+ input['image'] = np.random.rand(1,30,30,30)
863
+ input['label'] = np.ones([30,30,30])
864
+ analyzer = ImageHistogram(image_key='image')
865
+ print(analyzer(input))
866
+
867
+ """
868
+
869
+ def __init__(
870
+ self,
871
+ image_key: str,
872
+ stats_name: str = DataStatsKeys.IMAGE_HISTOGRAM,
873
+ hist_bins: list[int] | int | None = None,
874
+ hist_range: list | None = None,
875
+ ):
876
+ self.image_key = image_key
877
+
878
+ # set defaults
879
+ self.hist_bins: list[int] = (
880
+ [100] if hist_bins is None else hist_bins if isinstance(hist_bins, list) else [hist_bins]
881
+ )
882
+ self.hist_range: list = [-500, 500] if hist_range is None else hist_range
883
+
884
+ report_format = {"counts": None, "bin_edges": None}
885
+
886
+ super().__init__(stats_name, report_format)
887
+ self.update_ops(ImageStatsKeys.HISTOGRAM, SampleOperations())
888
+
889
+ # check histogram configurations for each channel in list
890
+ if not all(isinstance(hr, list) for hr in self.hist_range):
891
+ self.hist_range = [self.hist_range]
892
+ if len(self.hist_bins) != len(self.hist_range):
893
+ raise ValueError(
894
+ f"Number of histogram bins ({len(self.hist_bins)}) and "
895
+ f"histogram ranges ({len(self.hist_range)}) need to be the same!"
896
+ )
897
+ for i, hist_params in enumerate(zip(self.hist_bins, self.hist_range)):
898
+ _hist_bins, _hist_range = hist_params
899
+ if not isinstance(_hist_bins, int) or _hist_bins < 0:
900
+ raise ValueError(f"Expected {i+1}. hist_bins value to be positive integer but got {_hist_bins}")
901
+ if not isinstance(_hist_range, list) or len(_hist_range) != 2:
902
+ raise ValueError(f"Expected {i+1}. hist_range values to be list of length 2 but received {_hist_range}")
903
+
904
+ def __call__(self, data: dict) -> dict:
905
+ """
906
+ Callable to execute the pre-defined functions
907
+
908
+ Returns:
909
+ A dictionary. The dict has the key in self.report_format and value
910
+
911
+ Raises:
912
+ RuntimeError if the stats report generated is not consistent with the pre-
913
+ defined report_format.
914
+
915
+ Note:
916
+ The stats operation uses numpy and torch to compute max, min, and other
917
+ functions. If the input has nan/inf, the stats results will be nan/inf.
918
+ """
919
+
920
+ d = dict(data)
921
+
922
+ ndas = convert_to_numpy(d[self.image_key], wrap_sequence=True) # (1,H,W,D) or (C,H,W,D)
923
+ nr_channels = np.shape(ndas)[0]
924
+
925
+ # adjust histogram params to match channels
926
+ if len(self.hist_bins) == 1:
927
+ self.hist_bins = nr_channels * self.hist_bins
928
+ if len(self.hist_bins) != nr_channels:
929
+ raise ValueError(
930
+ f"There is a mismatch between the number of channels ({nr_channels}) "
931
+ f"and number histogram bins ({len(self.hist_bins)})."
932
+ )
933
+ if len(self.hist_range) == 1:
934
+ self.hist_range = nr_channels * self.hist_range
935
+ if len(self.hist_range) != nr_channels:
936
+ raise ValueError(
937
+ f"There is a mismatch between the number of channels ({nr_channels}) "
938
+ f"and histogram ranges ({len(self.hist_range)})."
939
+ )
940
+
941
+ # perform calculation
942
+ reports = []
943
+ for channel in range(nr_channels):
944
+ counts, bin_edges = np.histogram(
945
+ ndas[channel, ...],
946
+ bins=self.hist_bins[channel],
947
+ range=(self.hist_range[channel][0], self.hist_range[channel][1]),
948
+ )
949
+ _report = {"counts": counts.tolist(), "bin_edges": bin_edges.tolist()}
950
+ if not verify_report_format(_report, self.get_report_format()):
951
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
952
+ reports.append(_report)
953
+
954
+ d[self.stats_name] = reports
955
+ return d
956
+
957
+
958
+ class ImageHistogramSumm(Analyzer):
959
+ """
960
+ This summary analyzer processes the values of specific key `stats_name` in a list of dict.
961
+ Typically, the list of dict is the output of case analyzer under the same prefix
962
+ (ImageHistogram).
963
+
964
+ Args:
965
+ stats_name: the key of the to-process value in the dict.
966
+ average: whether to average the statistical value across different image modalities.
967
+
968
+ """
969
+
970
+ def __init__(self, stats_name: str = DataStatsKeys.IMAGE_HISTOGRAM, average: bool | None = True):
971
+ self.summary_average = average
972
+ report_format = {ImageStatsKeys.HISTOGRAM: None}
973
+ super().__init__(stats_name, report_format)
974
+
975
+ self.update_ops(ImageStatsKeys.HISTOGRAM, SummaryOperations())
976
+
977
+ def __call__(self, data: list[dict]) -> dict:
978
+ """
979
+ Callable to execute the pre-defined functions
980
+
981
+ Returns:
982
+ A dictionary. The dict has the key in self.report_format and value
983
+ in a list format. Each element of the value list has stats pre-defined
984
+ by SampleOperations (max, min, ....).
985
+
986
+ Raises:
987
+ RuntimeError if the stats report generated is not consistent with the pre-
988
+ defined report_format.
989
+
990
+ Examples:
991
+ output dict contains a dictionary for all of the following keys{
992
+ ImageStatsKeys.SHAPE:{...}
993
+ ImageStatsKeys.CHANNELS: {...},
994
+ ImageStatsKeys.CROPPED_SHAPE: {...},
995
+ ImageStatsKeys.SPACING: {...},
996
+ ImageStatsKeys.SIZEMM: {...},
997
+ ImageStatsKeys.INTENSITY: {...},
998
+ }
999
+
1000
+ Notes:
1001
+ The stats operation uses numpy and torch to compute max, min, and other
1002
+ functions. If the input has nan/inf, the stats results will be nan/inf.
1003
+ """
1004
+ if not isinstance(data, list):
1005
+ raise ValueError(f"Callable {self.__class__} requires list inputs")
1006
+
1007
+ if len(data) == 0:
1008
+ raise ValueError(f"Callable {self.__class__} input list is empty")
1009
+
1010
+ if self.stats_name not in data[0]:
1011
+ raise KeyError(f"{self.stats_name} is not in input data")
1012
+
1013
+ summ_histogram: dict = {}
1014
+
1015
+ for d in data:
1016
+ if not summ_histogram:
1017
+ summ_histogram = d[DataStatsKeys.IMAGE_HISTOGRAM]
1018
+ # convert to numpy for computing total histogram
1019
+ for k in range(len(summ_histogram)):
1020
+ summ_histogram[k]["counts"] = np.array(summ_histogram[k]["counts"])
1021
+ else:
1022
+ for k in range(len(summ_histogram)):
1023
+ summ_histogram[k]["counts"] += np.array(d[DataStatsKeys.IMAGE_HISTOGRAM][k]["counts"])
1024
+ if np.all(summ_histogram[k]["bin_edges"] != d[DataStatsKeys.IMAGE_HISTOGRAM][k]["bin_edges"]):
1025
+ raise ValueError(
1026
+ f"bin edges are not consistent! {summ_histogram[k]['bin_edges']} vs. "
1027
+ f"{d[DataStatsKeys.IMAGE_HISTOGRAM][k]['bin_edges']}"
1028
+ )
1029
+
1030
+ # convert back to list
1031
+ for k in range(len(summ_histogram)):
1032
+ summ_histogram[k]["counts"] = summ_histogram[k]["counts"].tolist()
1033
+
1034
+ report = {ImageStatsKeys.HISTOGRAM: summ_histogram}
1035
+ if not verify_report_format(report, self.get_report_format()):
1036
+ raise RuntimeError(f"report generated by {self.__class__} differs from the report format.")
1037
+
1038
+ return report
source_code/SegMamba/monai/auto3dseg/operations.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections import UserDict
15
+ from functools import partial
16
+ from typing import Any
17
+
18
+ from monai.transforms.utils_pytorch_numpy_unification import max, mean, median, min, percentile, std
19
+
20
+ __all__ = ["Operations", "SampleOperations", "SummaryOperations"]
21
+
22
+
23
+ class Operations(UserDict):
24
+ """
25
+ Base class of operation interface
26
+ """
27
+
28
+ def evaluate(self, data: Any, **kwargs: Any) -> dict:
29
+ """
30
+ For key-value pairs in the self.data, if the value is a callable,
31
+ then this function will apply the callable to the input data.
32
+ The result will be written under the same key under the output dict.
33
+
34
+ Args:
35
+ data: input data.
36
+
37
+ Returns:
38
+ a dictionary which has same keys as the self.data if the value
39
+ is callable.
40
+ """
41
+ return {k: v(data, **kwargs) for k, v in self.data.items() if callable(v)}
42
+
43
+
44
+ class SampleOperations(Operations):
45
+ """
46
+ Apply statistical operation to a sample (image/ndarray/tensor).
47
+
48
+ Notes:
49
+ Percentile operation uses a partial function that embeds different kwargs (q).
50
+ In order to print the result nicely, data_addon is added to map the numbers
51
+ generated by percentile to different keys ("percentile_00_5" for example).
52
+ Annotation of the postfix means the percentage for percentile computation.
53
+ For example, _00_5 means 0.5% and _99_5 means 99.5%.
54
+
55
+ Example:
56
+
57
+ .. code-block:: python
58
+
59
+ # use the existing operations
60
+ import numpy as np
61
+ op = SampleOperations()
62
+ data_np = np.random.rand(10, 10).astype(np.float64)
63
+ print(op.evaluate(data_np))
64
+
65
+ # add a new operation
66
+ op.update({"sum": np.sum})
67
+ print(op.evaluate(data_np))
68
+ """
69
+
70
+ def __init__(self) -> None:
71
+ self.data = {
72
+ "max": max,
73
+ "mean": mean,
74
+ "median": median,
75
+ "min": min,
76
+ "stdev": std,
77
+ "percentile": partial(percentile, q=[0.5, 10, 90, 99.5]),
78
+ }
79
+ self.data_addon = {
80
+ "percentile_00_5": ("percentile", 0),
81
+ "percentile_10_0": ("percentile", 1),
82
+ "percentile_90_0": ("percentile", 2),
83
+ "percentile_99_5": ("percentile", 3),
84
+ }
85
+
86
+ def evaluate(self, data: Any, **kwargs: Any) -> dict:
87
+ """
88
+ Applies the callables to the data, and convert the
89
+ numerics to list or Python numeric types (int/float).
90
+
91
+ Args:
92
+ data: input data
93
+ """
94
+ ret = super().evaluate(data, **kwargs)
95
+ for k, v in self.data_addon.items():
96
+ cache = v[0]
97
+ idx = v[1]
98
+ if isinstance(v, tuple) and cache in ret:
99
+ ret.update({k: ret[cache][idx]})
100
+
101
+ for k, v in ret.items():
102
+ ret[k] = v.tolist() # type: ignore
103
+ return ret
104
+
105
+
106
+ class SummaryOperations(Operations):
107
+ """
108
+ Apply statistical operation to summarize a dict. The key-value looks like: {"max", "min"
109
+ ,"mean", ....}. The value may contain multiple values in a list format. Then this operation
110
+ will apply the operation to the list. Typically, the dict is generated by multiple
111
+ `SampleOperation` and `concat_multikeys_to_dict` functions.
112
+
113
+ Examples:
114
+
115
+ .. code-block:: python
116
+
117
+ import numpy as np
118
+ data = {
119
+ "min": np.random.rand(4),
120
+ "max": np.random.rand(4),
121
+ "mean": np.random.rand(4),
122
+ "sum": np.random.rand(4),
123
+ }
124
+ op = SummaryOperations()
125
+ print(op.evaluate(data)) # "sum" is not registered yet, so it won't contain "sum"
126
+
127
+ op.update({"sum", np.sum})
128
+ print(op.evaluate(data)) # output has "sum"
129
+ """
130
+
131
+ def __init__(self) -> None:
132
+ self.data = {
133
+ "max": max,
134
+ "mean": mean,
135
+ "median": mean,
136
+ "min": min,
137
+ "stdev": mean,
138
+ "percentile_00_5": mean,
139
+ "percentile_10_0": mean,
140
+ "percentile_90_0": mean,
141
+ "percentile_99_5": mean,
142
+ }
143
+
144
+ def evaluate(self, data: Any, **kwargs: Any) -> dict:
145
+ """
146
+ Applies the callables to the data, and convert the numerics to list or Python
147
+ numeric types (int/float).
148
+
149
+ Args:
150
+ data: input data
151
+ """
152
+ return {k: v(data[k], **kwargs).tolist() for k, v in self.data.items() if (callable(v) and k in data)}
source_code/SegMamba/monai/auto3dseg/seg_summarizer.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ from monai.auto3dseg.analyzer import (
17
+ Analyzer,
18
+ FgImageStats,
19
+ FgImageStatsSumm,
20
+ FilenameStats,
21
+ ImageHistogram,
22
+ ImageHistogramSumm,
23
+ ImageStats,
24
+ ImageStatsSumm,
25
+ LabelStats,
26
+ LabelStatsSumm,
27
+ )
28
+ from monai.transforms import Compose
29
+ from monai.utils.enums import DataStatsKeys
30
+
31
+ __all__ = ["SegSummarizer"]
32
+
33
+
34
+ class SegSummarizer(Compose):
35
+ """
36
+ SegSummarizer serializes the operations for data analysis in Auto3Dseg pipeline. It loads
37
+ two types of analyzer functions and execute differently. The first type of analyzer is
38
+ CaseAnalyzer which is similar to traditional monai transforms. It can be composed with other
39
+ transforms to process the data dict which has image/label keys. The second type of analyzer
40
+ is SummaryAnalyzer which works only on a list of dictionary. Each dictionary is the output
41
+ of the case analyzers on a single dataset.
42
+
43
+ Args:
44
+ image_key: a string that user specify for the image. The DataAnalyzer will look it up in the
45
+ datalist to locate the image files of the dataset.
46
+ label_key: a string that user specify for the label. The DataAnalyzer will look it up in the
47
+ datalist to locate the label files of the dataset. If label_key is None, the DataAnalyzer
48
+ will skip looking for labels and all label-related operations.
49
+ do_ccp: apply the connected component algorithm to process the labels/images.
50
+ hist_bins: list of positive integers (one for each channel) for setting the number of bins used to
51
+ compute the histogram. Defaults to [100].
52
+ hist_range: list of lists of two floats (one for each channel) setting the intensity range to
53
+ compute the histogram. Defaults to [-500, 500].
54
+ histogram_only: whether to only compute histograms. Defaults to False.
55
+
56
+ Examples:
57
+ .. code-block:: python
58
+
59
+ # imports
60
+
61
+ summarizer = SegSummarizer("image", "label")
62
+ transform_list = [
63
+ LoadImaged(keys=keys),
64
+ EnsureChannelFirstd(keys=keys), # this creates label to be (1,H,W,D)
65
+ ToDeviced(keys=keys, device=device, non_blocking=True),
66
+ Orientationd(keys=keys, axcodes="RAS"),
67
+ EnsureTyped(keys=keys, data_type="tensor"),
68
+ Lambdad(keys="label", func=lambda x: torch.argmax(x, dim=0, keepdim=True) if x.shape[0] > 1 else x),
69
+ SqueezeDimd(keys=["label"], dim=0),
70
+ summarizer,
71
+ ]
72
+ ...
73
+ # skip some steps to set up data loader
74
+ dataset = data.DataLoader(ds, batch_size=1, shuffle=False, num_workers=n_workers, collate_fn=no_collation)
75
+ transform = Compose(transform_list)
76
+ stats = []
77
+ for batch_data in dataset:
78
+ d = transform(batch_data[0])
79
+ stats.append(d)
80
+ report = summarizer.summarize(stats)
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ image_key: str,
86
+ label_key: str | None,
87
+ average: bool = True,
88
+ do_ccp: bool = True,
89
+ hist_bins: list[int] | int | None = None,
90
+ hist_range: list | None = None,
91
+ histogram_only: bool = False,
92
+ ) -> None:
93
+ self.image_key = image_key
94
+ self.label_key = label_key
95
+ # set defaults
96
+ self.hist_bins: list[int] | int = [100] if hist_bins is None else hist_bins
97
+ self.hist_range: list = [-500, 500] if hist_range is None else hist_range
98
+ self.histogram_only = histogram_only
99
+
100
+ self.summary_analyzers: list[Any] = []
101
+ super().__init__()
102
+
103
+ self.add_analyzer(FilenameStats(image_key, DataStatsKeys.BY_CASE_IMAGE_PATH), None)
104
+ self.add_analyzer(FilenameStats(label_key, DataStatsKeys.BY_CASE_LABEL_PATH), None)
105
+ if not self.histogram_only:
106
+ self.add_analyzer(ImageStats(image_key), ImageStatsSumm(average=average))
107
+
108
+ if label_key is None:
109
+ return
110
+
111
+ self.add_analyzer(FgImageStats(image_key, label_key), FgImageStatsSumm(average=average))
112
+
113
+ self.add_analyzer(
114
+ LabelStats(image_key, label_key, do_ccp=do_ccp), LabelStatsSumm(average=average, do_ccp=do_ccp)
115
+ )
116
+
117
+ # compute histograms
118
+ if self.hist_bins != 0:
119
+ self.add_analyzer(
120
+ ImageHistogram(image_key=image_key, hist_bins=hist_bins, hist_range=hist_range), ImageHistogramSumm()
121
+ )
122
+
123
+ def add_analyzer(self, case_analyzer: Analyzer, summary_analyzer: Analyzer | None) -> None:
124
+ """
125
+ Add new analyzers to the engine so that the callable and summarize functions will
126
+ utilize the new analyzers for stats computations.
127
+
128
+ Args:
129
+ case_analyzer: analyzer that works on each data.
130
+ summary_analyzer: analyzer that works on list of stats dict (output from case_analyzers).
131
+
132
+ Examples:
133
+
134
+ .. code-block:: python
135
+
136
+ from monai.auto3dseg import Analyzer
137
+ from monai.auto3dseg.utils import concat_val_to_np
138
+ from monai.auto3dseg.analyzer_engine import SegSummarizer
139
+
140
+ class UserAnalyzer(Analyzer):
141
+ def __init__(self, image_key="image", stats_name="user_stats"):
142
+ self.image_key = image_key
143
+ report_format = {"ndims": None}
144
+ super().__init__(stats_name, report_format)
145
+
146
+ def __call__(self, data):
147
+ d = dict(data)
148
+ report = deepcopy(self.get_report_format())
149
+ report["ndims"] = d[self.image_key].ndim
150
+ d[self.stats_name] = report
151
+ return d
152
+
153
+ class UserSummaryAnalyzer(Analyzer):
154
+ def __init__(stats_name="user_stats"):
155
+ report_format = {"ndims": None}
156
+ super().__init__(stats_name, report_format)
157
+ self.update_ops("ndims", SampleOperations())
158
+
159
+ def __call__(self, data):
160
+ report = deepcopy(self.get_report_format())
161
+ v_np = concat_val_to_np(data, [self.stats_name, "ndims"])
162
+ report["ndims"] = self.ops["ndims"].evaluate(v_np)
163
+ return report
164
+
165
+ summarizer = SegSummarizer()
166
+ summarizer.add_analyzer(UserAnalyzer, UserSummaryAnalyzer)
167
+
168
+ """
169
+ self.transforms += (case_analyzer,)
170
+ if summary_analyzer is not None:
171
+ self.summary_analyzers.append(summary_analyzer)
172
+
173
+ def summarize(self, data: list[dict]) -> dict[str, dict]:
174
+ """
175
+ Summarize the input list of data and generates a report ready for json/yaml export.
176
+
177
+ Args:
178
+ data: a list of data dicts.
179
+
180
+ Returns:
181
+ a dict that summarizes the stats across data samples.
182
+
183
+ Examples:
184
+ stats_summary:
185
+ image_foreground_stats:
186
+ intensity: {...}
187
+ image_stats:
188
+ channels: {...}
189
+ cropped_shape: {...}
190
+ ...
191
+ label_stats:
192
+ image_intensity: {...}
193
+ label:
194
+ - image_intensity: {...}
195
+ - image_intensity: {...}
196
+ - image_intensity: {...}
197
+ - image_intensity: {...}
198
+ """
199
+ if not isinstance(data, list):
200
+ raise ValueError(f"{self.__class__} summarize function needs input to be a list of dict")
201
+
202
+ report: dict[str, dict] = {}
203
+ if len(data) == 0:
204
+ return report
205
+
206
+ if not isinstance(data[0], dict):
207
+ raise ValueError(f"{self.__class__} summarize function needs a list of dict. Now we have {type(data[0])}")
208
+
209
+ for analyzer in self.summary_analyzers:
210
+ if callable(analyzer):
211
+ report.update({analyzer.stats_name: analyzer(data)})
212
+
213
+ return report
source_code/SegMamba/monai/auto3dseg/utils.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ import pickle
17
+ import subprocess
18
+ import sys
19
+ from copy import deepcopy
20
+ from numbers import Number
21
+ from typing import Any, cast
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+ from monai.auto3dseg import Algo
27
+ from monai.bundle.config_parser import ConfigParser
28
+ from monai.bundle.utils import ID_SEP_KEY
29
+ from monai.config import PathLike
30
+ from monai.data.meta_tensor import MetaTensor
31
+ from monai.transforms import CropForeground, ToCupy
32
+ from monai.utils import min_version, optional_import, run_cmd
33
+
34
+ __all__ = [
35
+ "get_foreground_image",
36
+ "get_foreground_label",
37
+ "get_label_ccp",
38
+ "concat_val_to_np",
39
+ "concat_multikeys_to_dict",
40
+ "datafold_read",
41
+ "verify_report_format",
42
+ "algo_to_pickle",
43
+ "algo_from_pickle",
44
+ ]
45
+
46
+ measure_np, has_measure = optional_import("skimage.measure", "0.14.2", min_version)
47
+ cp, has_cp = optional_import("cupy")
48
+
49
+
50
+ def get_foreground_image(image: MetaTensor) -> np.ndarray:
51
+ """
52
+ Get a foreground image by removing all-zero rectangles on the edges of the image
53
+ Note for the developer: update select_fn if the foreground is defined differently.
54
+
55
+ Args:
56
+ image: ndarray image to segment.
57
+
58
+ Returns:
59
+ ndarray of foreground image by removing all-zero edges.
60
+
61
+ Notes:
62
+ the size of the output is smaller than the input.
63
+ """
64
+
65
+ copper = CropForeground(select_fn=lambda x: x > 0, allow_smaller=True)
66
+ image_foreground = copper(image)
67
+ return cast(np.ndarray, image_foreground)
68
+
69
+
70
+ def get_foreground_label(image: MetaTensor, label: MetaTensor) -> MetaTensor:
71
+ """
72
+ Get foreground image pixel values and mask out the non-labeled area.
73
+
74
+ Args
75
+ image: ndarray image to segment.
76
+ label: ndarray the image input and annotated with class IDs.
77
+
78
+ Returns:
79
+ 1D array of foreground image with label > 0
80
+ """
81
+
82
+ label_foreground = MetaTensor(image[label > 0])
83
+ return label_foreground
84
+
85
+
86
+ def get_label_ccp(mask_index: MetaTensor, use_gpu: bool = True) -> tuple[list[Any], int]:
87
+ """
88
+ Find all connected components and their bounding shape. Backend can be cuPy/cuCIM or Numpy
89
+ depending on the hardware.
90
+
91
+ Args:
92
+ mask_index: a binary mask.
93
+ use_gpu: a switch to use GPU/CUDA or not. If GPU is unavailable, CPU will be used
94
+ regardless of this setting.
95
+
96
+ """
97
+ skimage, has_cucim = optional_import("cucim.skimage")
98
+ shape_list = []
99
+ if mask_index.device.type == "cuda" and has_cp and has_cucim and use_gpu:
100
+ mask_cupy = ToCupy()(mask_index.short())
101
+ labeled = skimage.measure.label(mask_cupy)
102
+ vals = cp.unique(labeled[cp.nonzero(labeled)])
103
+
104
+ for ncomp in vals:
105
+ comp_idx = cp.argwhere(labeled == ncomp)
106
+ comp_idx_min = cp.min(comp_idx, axis=0).tolist()
107
+ comp_idx_max = cp.max(comp_idx, axis=0).tolist()
108
+ bbox_shape = [comp_idx_max[i] - comp_idx_min[i] + 1 for i in range(len(comp_idx_max))]
109
+ shape_list.append(bbox_shape)
110
+ ncomponents = len(vals)
111
+
112
+ del mask_cupy, labeled, vals, comp_idx, ncomp
113
+ cp.get_default_memory_pool().free_all_blocks()
114
+
115
+ elif has_measure:
116
+ labeled, ncomponents = measure_np.label(mask_index.data.cpu().numpy(), background=-1, return_num=True)
117
+ for ncomp in range(1, ncomponents + 1):
118
+ comp_idx = np.argwhere(labeled == ncomp)
119
+ comp_idx_min = np.min(comp_idx, axis=0).tolist()
120
+ comp_idx_max = np.max(comp_idx, axis=0).tolist()
121
+ bbox_shape = [comp_idx_max[i] - comp_idx_min[i] + 1 for i in range(len(comp_idx_max))]
122
+ shape_list.append(bbox_shape)
123
+ else:
124
+ raise RuntimeError("Cannot find one of the following required dependencies: {cuPy+cuCIM} or {scikit-image}")
125
+
126
+ return shape_list, ncomponents
127
+
128
+
129
+ def concat_val_to_np(
130
+ data_list: list[dict],
131
+ fixed_keys: list[str | int],
132
+ ragged: bool | None = False,
133
+ allow_missing: bool | None = False,
134
+ **kwargs: Any,
135
+ ) -> np.ndarray:
136
+ """
137
+ Get the nested value in a list of dictionary that shares the same structure.
138
+
139
+ Args:
140
+ data_list: a list of dictionary {key1: {key2: np.ndarray}}.
141
+ fixed_keys: a list of keys that records to path to the value in the dict elements.
142
+ ragged: if True, numbers can be in list of lists or ragged format so concat mode needs change.
143
+ allow_missing: if True, it will return a None if the value cannot be found.
144
+
145
+ Returns:
146
+ nd.array of concatenated array.
147
+
148
+ """
149
+
150
+ np_list: list[np.ndarray | None] = []
151
+ for data in data_list:
152
+ parser = ConfigParser(data)
153
+ for i, key in enumerate(fixed_keys):
154
+ fixed_keys[i] = str(key)
155
+
156
+ val: Any
157
+ val = parser.get(ID_SEP_KEY.join(fixed_keys)) # type: ignore
158
+
159
+ if val is None:
160
+ if allow_missing:
161
+ np_list.append(None)
162
+ else:
163
+ raise AttributeError(f"{fixed_keys} is not nested in the dictionary")
164
+ elif isinstance(val, list):
165
+ np_list.append(np.array(val))
166
+ elif isinstance(val, (torch.Tensor, MetaTensor)):
167
+ np_list.append(val.cpu().numpy())
168
+ elif isinstance(val, np.ndarray):
169
+ np_list.append(val)
170
+ elif isinstance(val, Number):
171
+ np_list.append(np.array(val))
172
+ else:
173
+ raise NotImplementedError(f"{val.__class__} concat is not supported.")
174
+
175
+ if allow_missing:
176
+ np_list = [x for x in np_list if x is not None]
177
+
178
+ if len(np_list) == 0:
179
+ return np.array([0])
180
+ elif ragged:
181
+ return np.concatenate(np_list, **kwargs) # type: ignore
182
+ else:
183
+ return np.concatenate([np_list], **kwargs)
184
+
185
+
186
+ def concat_multikeys_to_dict(
187
+ data_list: list[dict], fixed_keys: list[str | int], keys: list[str], zero_insert: bool = True, **kwargs: Any
188
+ ) -> dict[str, np.ndarray]:
189
+ """
190
+ Get the nested value in a list of dictionary that shares the same structure iteratively on all keys.
191
+ It returns a dictionary with keys with the found values in nd.ndarray.
192
+
193
+ Args:
194
+ data_list: a list of dictionary {key1: {key2: np.ndarray}}.
195
+ fixed_keys: a list of keys that records to path to the value in the dict elements.
196
+ keys: a list of string keys that will be iterated to generate a dict output.
197
+ zero_insert: insert a zero in the list so that it can find the value in element 0 before getting the keys
198
+ flatten: if True, numbers are flattened before concat.
199
+
200
+ Returns:
201
+ a dict with keys - nd.array of concatenated array pair.
202
+ """
203
+
204
+ ret_dict = {}
205
+ for key in keys:
206
+ addon: list[str | int] = [0, key] if zero_insert else [key]
207
+ val = concat_val_to_np(data_list, fixed_keys + addon, **kwargs)
208
+ ret_dict.update({key: val})
209
+
210
+ return ret_dict
211
+
212
+
213
+ def datafold_read(datalist: str | dict, basedir: str, fold: int = 0, key: str = "training") -> tuple[list, list]:
214
+ """
215
+ Read a list of data dictionary `datalist`
216
+
217
+ Args:
218
+ datalist: the name of a JSON file listing the data, or a dictionary.
219
+ basedir: directory of image files.
220
+ fold: which fold to use (0..1 if in training set).
221
+ key: usually 'training' , but can try 'validation' or 'testing' to get the list data without labels (used in challenges).
222
+
223
+ Returns:
224
+ A tuple of two arrays (training, validation).
225
+ """
226
+
227
+ if isinstance(datalist, str):
228
+ json_data = ConfigParser.load_config_file(datalist)
229
+ else:
230
+ json_data = datalist
231
+
232
+ dict_data = deepcopy(json_data[key])
233
+
234
+ for d in dict_data:
235
+ for k, _ in d.items():
236
+ if isinstance(d[k], list):
237
+ d[k] = [os.path.join(basedir, iv) for iv in d[k]]
238
+ elif isinstance(d[k], str):
239
+ d[k] = os.path.join(basedir, d[k]) if len(d[k]) > 0 else d[k]
240
+
241
+ tr = []
242
+ val = []
243
+ for d in dict_data:
244
+ if "fold" in d and d["fold"] == fold:
245
+ val.append(d)
246
+ else:
247
+ tr.append(d)
248
+
249
+ return tr, val
250
+
251
+
252
+ def verify_report_format(report: dict, report_format: dict) -> bool:
253
+ """
254
+ Compares the report and the report_format that has only keys.
255
+
256
+ Args:
257
+ report: dict that has real values.
258
+ report_format: dict that only has keys and list-nested value.
259
+ """
260
+ for k_fmt, v_fmt in report_format.items():
261
+ if k_fmt not in report:
262
+ return False
263
+
264
+ v = report[k_fmt]
265
+
266
+ if isinstance(v_fmt, list) and isinstance(v, list):
267
+ if len(v_fmt) != 1:
268
+ raise UserWarning("list length in report_format is not 1")
269
+ if len(v_fmt) > 0 and len(v) > 0:
270
+ return verify_report_format(v[0], v_fmt[0])
271
+ else:
272
+ return False
273
+
274
+ return True
275
+
276
+
277
+ def algo_to_pickle(algo: Algo, template_path: PathLike | None = None, **algo_meta_data: Any) -> str:
278
+ """
279
+ Export the Algo object to pickle file.
280
+
281
+ Args:
282
+ algo: Algo-like object.
283
+ template_path: a str path that is needed to be added to the sys.path to instantiate the class.
284
+ algo_meta_data: additional keyword to save into the dictionary, for example, model training info
285
+ such as acc/best_metrics
286
+
287
+ Returns:
288
+ filename of the pickled Algo object
289
+ """
290
+ data = {"algo_bytes": pickle.dumps(algo), "template_path": str(template_path)}
291
+ pkl_filename = os.path.join(algo.get_output_path(), "algo_object.pkl")
292
+ for k, v in algo_meta_data.items():
293
+ data.update({k: v})
294
+ data_bytes = pickle.dumps(data)
295
+ with open(pkl_filename, "wb") as f_pi:
296
+ f_pi.write(data_bytes)
297
+ return pkl_filename
298
+
299
+
300
+ def algo_from_pickle(pkl_filename: str, template_path: PathLike | None = None, **kwargs: Any) -> Any:
301
+ """
302
+ Import the Algo object from a pickle file.
303
+
304
+ Args:
305
+ pkl_filename: the name of the pickle file.
306
+ template_path: a folder containing files to instantiate the Algo. Besides the `template_path`,
307
+ this function will also attempt to use the `template_path` saved in the pickle file and a directory
308
+ named `algorithm_templates` in the parent folder of the folder containing the pickle file.
309
+
310
+ Returns:
311
+ algo: the Algo object saved in the pickle file.
312
+ algo_meta_data: additional keyword saved in the pickle file, for example, acc/best_metrics.
313
+
314
+ Raises:
315
+ ValueError if the pkl_filename does not contain a dict, or the dict does not contain `algo_bytes`.
316
+ ModuleNotFoundError if it is unable to instantiate the Algo class.
317
+
318
+ """
319
+ with open(pkl_filename, "rb") as f_pi:
320
+ data_bytes = f_pi.read()
321
+ data = pickle.loads(data_bytes)
322
+
323
+ if not isinstance(data, dict):
324
+ raise ValueError(f"the data object is {data.__class__}. Dict is expected.")
325
+
326
+ if "algo_bytes" not in data:
327
+ raise ValueError(f"key [algo_bytes] not found in {data}. Unable to instantiate.")
328
+
329
+ algo_bytes = data.pop("algo_bytes")
330
+ algo_template_path = data.pop("template_path", None)
331
+
332
+ template_paths_candidates: list[str] = []
333
+
334
+ if os.path.isdir(str(template_path)):
335
+ template_paths_candidates.append(os.path.abspath(str(template_path)))
336
+ template_paths_candidates.append(os.path.abspath(os.path.join(str(template_path), "..")))
337
+
338
+ if os.path.isdir(str(algo_template_path)):
339
+ template_paths_candidates.append(os.path.abspath(algo_template_path))
340
+ template_paths_candidates.append(os.path.abspath(os.path.join(algo_template_path, "..")))
341
+
342
+ pkl_dir = os.path.dirname(pkl_filename)
343
+ algo_template_path_fuzzy = os.path.join(pkl_dir, "..", "algorithm_templates")
344
+
345
+ if os.path.isdir(algo_template_path_fuzzy):
346
+ template_paths_candidates.append(os.path.abspath(algo_template_path_fuzzy))
347
+
348
+ if len(template_paths_candidates) == 0:
349
+ # no template_path provided or needed
350
+ algo = pickle.loads(algo_bytes)
351
+ algo.template_path = None
352
+ else:
353
+ for i, p in enumerate(template_paths_candidates):
354
+ try:
355
+ sys.path.append(p)
356
+ algo = pickle.loads(algo_bytes)
357
+ break
358
+ except ModuleNotFoundError as not_found_err:
359
+ logging.debug(f"Folder {p} doesn't contain the Algo templates for Algo instantiation.")
360
+ sys.path.pop()
361
+ if i == len(template_paths_candidates) - 1:
362
+ raise ValueError(
363
+ f"Failed to instantiate {pkl_filename} with {template_paths_candidates}"
364
+ ) from not_found_err
365
+ algo.template_path = p
366
+
367
+ if os.path.abspath(pkl_dir) != os.path.abspath(algo.get_output_path()):
368
+ logging.debug(f"{algo.get_output_path()} is changed. Now override the Algo output_path with: {pkl_dir}.")
369
+ algo.output_path = pkl_dir
370
+
371
+ algo_meta_data = {}
372
+ for k, v in data.items():
373
+ algo_meta_data.update({k: v})
374
+
375
+ return algo, algo_meta_data
376
+
377
+
378
+ def list_to_python_fire_arg_str(args: list) -> str:
379
+ """
380
+ Convert a list of arguments to a string that can be used in python-fire.
381
+
382
+ Args:
383
+ args: the list of arguments.
384
+
385
+ Returns:
386
+ the string that can be used in python-fire.
387
+ """
388
+ args_str = ",".join([str(arg) for arg in args])
389
+ return f"'{args_str}'"
390
+
391
+
392
+ def check_and_set_optional_args(params: dict) -> str:
393
+ """convert `params` into '--key_1=value_1 --key_2=value_2 ...'"""
394
+ cmd_mod_opt = ""
395
+ for k, v in params.items():
396
+ if isinstance(v, dict):
397
+ raise ValueError("Nested dict is not supported.")
398
+ elif isinstance(v, list):
399
+ v = list_to_python_fire_arg_str(v)
400
+ cmd_mod_opt += f" --{k}={v}"
401
+ return cmd_mod_opt
402
+
403
+
404
+ def _prepare_cmd_default(cmd: str, cmd_prefix: str | None = None, **kwargs: Any) -> str:
405
+ """
406
+ Prepare the command for subprocess to run the script with the given arguments.
407
+
408
+ Args:
409
+ cmd: the command or script to run in the distributed job.
410
+ cmd_prefix: the command prefix to run the script, e.g., "python", "python -m", "python3", "/opt/conda/bin/python3.8 ".
411
+ kwargs: the keyword arguments to be passed to the script.
412
+
413
+ Returns:
414
+ the command to run with ``subprocess``.
415
+
416
+ Examples:
417
+ To prepare a subprocess command
418
+ "python train.py run -k --config 'a,b'", the function can be called as
419
+ - _prepare_cmd_default("train.py run -k", config=['a','b'])
420
+ - _prepare_cmd_default("train.py run -k --config 'a,b'")
421
+
422
+ """
423
+ params = kwargs.copy()
424
+
425
+ if not cmd_prefix or "None" in cmd_prefix: # defaulting to 'python'
426
+ cmd_prefix = "python"
427
+
428
+ if not cmd_prefix.endswith(" "):
429
+ cmd_prefix += " " # ensure a space after the command prefix so that the script can be appended
430
+
431
+ return cmd_prefix + cmd + check_and_set_optional_args(params)
432
+
433
+
434
+ def _prepare_cmd_torchrun(cmd: str, **kwargs: Any) -> str:
435
+ """
436
+ Prepare the command for multi-gpu/multi-node job execution using torchrun.
437
+
438
+ Args:
439
+ cmd: the command or script to run in the distributed job.
440
+ kwargs: the keyword arguments to be passed to the script.
441
+
442
+ Returns:
443
+ the command to append to ``torchrun``
444
+
445
+ Examples:
446
+ For command "torchrun --nnodes=1 --nproc_per_node=8 train.py run -k --config 'a,b'",
447
+ it only prepares command after the torchrun arguments, i.e., "train.py run -k --config 'a,b'".
448
+ The function can be called as
449
+ - _prepare_cmd_torchrun("train.py run -k", config=['a','b'])
450
+ - _prepare_cmd_torchrun("train.py run -k --config 'a,b'")
451
+ """
452
+ params = kwargs.copy()
453
+ return cmd + check_and_set_optional_args(params)
454
+
455
+
456
+ def _prepare_cmd_bcprun(cmd: str, cmd_prefix: str | None = None, **kwargs: Any) -> str:
457
+ """
458
+ Prepare the command for distributed job running using bcprun.
459
+
460
+ Args:
461
+ script: the script to run in the distributed job.
462
+ cmd_prefix: the command prefix to run the script, e.g., "python".
463
+ kwargs: the keyword arguments to be passed to the script.
464
+
465
+ Returns:
466
+ The command to run the script in the distributed job.
467
+
468
+ Examples:
469
+ For command "bcprun -n 2 -p 8 -c python train.py run -k --config 'a,b'",
470
+ it only prepares command after the bcprun arguments, i.e., "train.py run -k --config 'a,b'".
471
+ the function can be called as
472
+ - _prepare_cmd_bcprun("train.py run -k", config=['a','b'], n=2, p=8)
473
+ - _prepare_cmd_bcprun("train.py run -k --config 'a,b'", n=2, p=8)
474
+ """
475
+
476
+ return _prepare_cmd_default(cmd, cmd_prefix=cmd_prefix, **kwargs)
477
+
478
+
479
+ def _run_cmd_torchrun(cmd: str, **kwargs: Any) -> subprocess.CompletedProcess:
480
+ """
481
+ Run the command with torchrun.
482
+
483
+ Args:
484
+ cmd: the command to run. Typically it is prepared by ``_prepare_cmd_torchrun``.
485
+ kwargs: the keyword arguments to be passed to the ``torchrun``.
486
+
487
+ Return:
488
+ the return code of the subprocess command.
489
+ """
490
+ params = kwargs.copy()
491
+
492
+ cmd_list = cmd.split()
493
+
494
+ # append arguments to the command list
495
+ torchrun_list = ["torchrun"]
496
+ required_args = ["nnodes", "nproc_per_node"]
497
+ for arg in required_args:
498
+ if arg not in params:
499
+ raise ValueError(f"Missing required argument {arg} for torchrun.")
500
+ torchrun_list += [f"--{arg}", str(params.pop(arg))]
501
+ torchrun_list += cmd_list
502
+ return run_cmd(torchrun_list, run_cmd_verbose=True, **params)
503
+
504
+
505
+ def _run_cmd_bcprun(cmd: str, **kwargs: Any) -> subprocess.CompletedProcess:
506
+ """
507
+ Run the command with bcprun.
508
+
509
+ Args:
510
+ cmd: the command to run. Typically it is prepared by ``_prepare_cmd_bcprun``.
511
+ kwargs: the keyword arguments to be passed to the ``bcprun``.
512
+
513
+ Returns:
514
+ the return code of the subprocess command.
515
+ """
516
+ params = kwargs.copy()
517
+ cmd_list = ["bcprun"]
518
+ required_args = ["n", "p"]
519
+ for arg in required_args:
520
+ if arg not in params:
521
+ raise ValueError(f"Missing required argument {arg} for bcprun.")
522
+ cmd_list += [f"-{arg}", str(params.pop(arg))]
523
+ cmd_list.extend(["-c", cmd])
524
+ return run_cmd(cmd_list, run_cmd_verbose=True, **params)
source_code/SegMamba/monai/bundle/__init__.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from .config_item import ComponentLocator, ConfigComponent, ConfigExpression, ConfigItem, Instantiable
15
+ from .config_parser import ConfigParser
16
+ from .properties import InferProperties, MetaProperties, TrainProperties
17
+ from .reference_resolver import ReferenceResolver
18
+ from .scripts import (
19
+ ckpt_export,
20
+ create_workflow,
21
+ download,
22
+ download_large_files,
23
+ get_all_bundles_list,
24
+ get_bundle_info,
25
+ get_bundle_versions,
26
+ init_bundle,
27
+ load,
28
+ onnx_export,
29
+ push_to_hf_hub,
30
+ run,
31
+ run_workflow,
32
+ trt_export,
33
+ update_kwargs,
34
+ verify_metadata,
35
+ verify_net_in_out,
36
+ )
37
+ from .utils import (
38
+ DEFAULT_EXP_MGMT_SETTINGS,
39
+ DEFAULT_MLFLOW_SETTINGS,
40
+ EXPR_KEY,
41
+ ID_REF_KEY,
42
+ ID_SEP_KEY,
43
+ MACRO_KEY,
44
+ load_bundle_config,
45
+ )
46
+ from .workflows import BundleWorkflow, ConfigWorkflow
source_code/SegMamba/monai/bundle/__main__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from monai.bundle.scripts import (
15
+ ckpt_export,
16
+ download,
17
+ download_large_files,
18
+ init_bundle,
19
+ onnx_export,
20
+ run,
21
+ run_workflow,
22
+ trt_export,
23
+ verify_metadata,
24
+ verify_net_in_out,
25
+ )
26
+
27
+ if __name__ == "__main__":
28
+ from monai.utils import optional_import
29
+
30
+ fire, _ = optional_import("fire")
31
+ fire.Fire()
source_code/SegMamba/monai/bundle/config_item.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import inspect
16
+ import sys
17
+ import warnings
18
+ from abc import ABC, abstractmethod
19
+ from collections.abc import Mapping, Sequence
20
+ from importlib import import_module
21
+ from pprint import pformat
22
+ from typing import Any
23
+
24
+ from monai.bundle.utils import EXPR_KEY
25
+ from monai.utils import CompInitMode, ensure_tuple, first, instantiate, optional_import, run_debug, run_eval
26
+
27
+ __all__ = ["ComponentLocator", "ConfigItem", "ConfigExpression", "ConfigComponent", "Instantiable"]
28
+
29
+
30
+ class Instantiable(ABC):
31
+ """
32
+ Base class for an instantiable object.
33
+ """
34
+
35
+ @abstractmethod
36
+ def is_disabled(self, *args: Any, **kwargs: Any) -> bool:
37
+ """
38
+ Return a boolean flag to indicate whether the object should be instantiated.
39
+ """
40
+ raise NotImplementedError(f"subclass {self.__class__.__name__} must implement this method.")
41
+
42
+ @abstractmethod
43
+ def instantiate(self, *args: Any, **kwargs: Any) -> object:
44
+ """
45
+ Instantiate the target component and return the instance.
46
+ """
47
+ raise NotImplementedError(f"subclass {self.__class__.__name__} must implement this method.")
48
+
49
+
50
+ class ComponentLocator:
51
+ """
52
+ Scan all the available classes and functions in the MONAI package and map them with the module paths in a table.
53
+ It's used to locate the module path for provided component name.
54
+
55
+ Args:
56
+ excludes: if any string of the `excludes` exists in the full module name, don't import this module.
57
+
58
+ """
59
+
60
+ MOD_START = "monai"
61
+
62
+ def __init__(self, excludes: Sequence[str] | str | None = None):
63
+ self.excludes = [] if excludes is None else ensure_tuple(excludes)
64
+ self._components_table: dict[str, list] | None = None
65
+
66
+ def _find_module_names(self) -> list[str]:
67
+ """
68
+ Find all the modules start with MOD_START and don't contain any of `excludes`.
69
+
70
+ """
71
+ return [m for m in sys.modules if m.startswith(self.MOD_START) and all(s not in m for s in self.excludes)]
72
+
73
+ def _find_classes_or_functions(self, modnames: Sequence[str] | str) -> dict[str, list]:
74
+ """
75
+ Find all the classes and functions in the modules with specified `modnames`.
76
+
77
+ Args:
78
+ modnames: names of the target modules to find all the classes and functions.
79
+
80
+ """
81
+ table: dict[str, list] = {}
82
+ # all the MONAI modules are already loaded by `load_submodules`
83
+ for modname in ensure_tuple(modnames):
84
+ try:
85
+ # scan all the classes and functions in the module
86
+ module = import_module(modname)
87
+ for name, obj in inspect.getmembers(module):
88
+ if (inspect.isclass(obj) or inspect.isfunction(obj)) and obj.__module__ == modname:
89
+ if name not in table:
90
+ table[name] = []
91
+ table[name].append(modname)
92
+ except ModuleNotFoundError:
93
+ pass
94
+ return table
95
+
96
+ def get_component_module_name(self, name: str) -> list[str] | str | None:
97
+ """
98
+ Get the full module name of the class or function with specified ``name``.
99
+ If target component name exists in multiple packages or modules, return a list of full module names.
100
+
101
+ Args:
102
+ name: name of the expected class or function.
103
+
104
+ """
105
+ if not isinstance(name, str):
106
+ raise ValueError(f"`name` must be a valid string, but got: {name}.")
107
+ if self._components_table is None:
108
+ # init component and module mapping table
109
+ self._components_table = self._find_classes_or_functions(self._find_module_names())
110
+
111
+ mods: list[str] | str | None = self._components_table.get(name)
112
+ if isinstance(mods, list) and len(mods) == 1:
113
+ mods = mods[0]
114
+ return mods
115
+
116
+
117
+ class ConfigItem:
118
+ """
119
+ Basic data structure to represent a configuration item.
120
+
121
+ A `ConfigItem` instance can optionally have a string id, so that other items can refer to it.
122
+ It has a build-in `config` property to store the configuration object.
123
+
124
+ Args:
125
+ config: content of a config item, can be objects of any types,
126
+ a configuration resolver may interpret the content to generate a configuration object.
127
+ id: name of the current config item, defaults to empty string.
128
+
129
+ """
130
+
131
+ def __init__(self, config: Any, id: str = "") -> None:
132
+ self.config = config
133
+ self.id = id
134
+
135
+ def get_id(self) -> str:
136
+ """
137
+ Get the ID name of current config item, useful to identify config items during parsing.
138
+
139
+ """
140
+ return self.id
141
+
142
+ def update_config(self, config: Any) -> None:
143
+ """
144
+ Replace the content of `self.config` with new `config`.
145
+ A typical usage is to modify the initial config content at runtime.
146
+
147
+ Args:
148
+ config: content of a `ConfigItem`.
149
+
150
+ """
151
+ self.config = config
152
+
153
+ def get_config(self):
154
+ """
155
+ Get the config content of current config item.
156
+
157
+ """
158
+ return self.config
159
+
160
+ def __repr__(self) -> str:
161
+ return f"{type(self).__name__}: \n{pformat(self.config)}"
162
+
163
+
164
+ class ConfigComponent(ConfigItem, Instantiable):
165
+ """
166
+ Subclass of :py:class:`monai.bundle.ConfigItem`, this class uses a dictionary with string keys to
167
+ represent a component of `class` or `function` and supports instantiation.
168
+
169
+ Currently, three special keys (strings surrounded by ``_``) are defined and interpreted beyond the regular literals:
170
+
171
+ - class or function identifier of the python module, specified by ``"_target_"``,
172
+ indicating a monai built-in Python class or function such as ``"LoadImageDict"``,
173
+ or a full module name, e.g. ``"monai.transforms.LoadImageDict"``, or a callable, e.g. ``"$@model.forward"``.
174
+ - ``"_requires_"`` (optional): specifies reference IDs (string starts with ``"@"``) or ``ConfigExpression``
175
+ of the dependencies for this ``ConfigComponent`` object. These dependencies will be
176
+ evaluated/instantiated before this object is instantiated. It is useful when the
177
+ component doesn't explicitly depend on the other `ConfigItems` via its arguments,
178
+ but requires the dependencies to be instantiated/evaluated beforehand.
179
+ - ``"_disabled_"`` (optional): a flag to indicate whether to skip the instantiation.
180
+ - ``"_desc_"`` (optional): free text descriptions of the component for code readability.
181
+ - ``"_mode_"`` (optional): operating mode for invoking the callable ``component`` defined by ``"_target_"``:
182
+
183
+ - ``"default"``: returns ``component(**kwargs)``
184
+ - ``"callable"``: returns ``component`` or, if ``kwargs`` are provided, ``functools.partial(component, **kwargs)``
185
+ - ``"debug"``: returns ``pdb.runcall(component, **kwargs)``
186
+
187
+ Other fields in the config content are input arguments to the python module.
188
+
189
+ .. code-block:: python
190
+
191
+ from monai.bundle import ComponentLocator, ConfigComponent
192
+
193
+ locator = ComponentLocator(excludes=["modules_to_exclude"])
194
+ config = {
195
+ "_target_": "LoadImaged",
196
+ "keys": ["image", "label"]
197
+ }
198
+
199
+ configer = ConfigComponent(config, id="test", locator=locator)
200
+ image_loader = configer.instantiate()
201
+ print(image_loader) # <monai.transforms.io.dictionary.LoadImaged object at 0x7fba7ad1ee50>
202
+
203
+ Args:
204
+ config: content of a config item.
205
+ id: name of the current config item, defaults to empty string.
206
+ locator: a ``ComponentLocator`` to convert a module name string into the actual python module.
207
+ if `None`, a ``ComponentLocator(excludes=excludes)`` will be used.
208
+ excludes: if ``locator`` is None, create a new ``ComponentLocator`` with ``excludes``.
209
+ See also: :py:class:`monai.bundle.ComponentLocator`.
210
+
211
+ """
212
+
213
+ non_arg_keys = {"_target_", "_disabled_", "_requires_", "_desc_", "_mode_"}
214
+
215
+ def __init__(
216
+ self,
217
+ config: Any,
218
+ id: str = "",
219
+ locator: ComponentLocator | None = None,
220
+ excludes: Sequence[str] | str | None = None,
221
+ ) -> None:
222
+ super().__init__(config=config, id=id)
223
+ self.locator = ComponentLocator(excludes=excludes) if locator is None else locator
224
+
225
+ @staticmethod
226
+ def is_instantiable(config: Any) -> bool:
227
+ """
228
+ Check whether this config represents a `class` or `function` that is to be instantiated.
229
+
230
+ Args:
231
+ config: input config content to check.
232
+
233
+ """
234
+ return isinstance(config, Mapping) and "_target_" in config
235
+
236
+ def resolve_module_name(self):
237
+ """
238
+ Resolve the target module name from current config content.
239
+ The config content must have ``"_target_"`` key.
240
+
241
+ """
242
+ config = dict(self.get_config())
243
+ target = config.get("_target_")
244
+ if not isinstance(target, str):
245
+ return target # for feature discussed in project-monai/monai#5852
246
+
247
+ module = self.locator.get_component_module_name(target)
248
+ if module is None:
249
+ # target is the full module name, no need to parse
250
+ return target
251
+
252
+ if isinstance(module, list):
253
+ warnings.warn(
254
+ f"there are more than 1 component have name `{target}`: {module}, use the first one `{module[0]}."
255
+ f" if want to use others, please set its full module path in `_target_` directly."
256
+ )
257
+ module = module[0]
258
+ return f"{module}.{target}"
259
+
260
+ def resolve_args(self):
261
+ """
262
+ Utility function used in `instantiate()` to resolve the arguments from current config content.
263
+
264
+ """
265
+ return {k: v for k, v in self.get_config().items() if k not in self.non_arg_keys}
266
+
267
+ def is_disabled(self) -> bool:
268
+ """
269
+ Utility function used in `instantiate()` to check whether to skip the instantiation.
270
+
271
+ """
272
+ _is_disabled = self.get_config().get("_disabled_", False)
273
+ return _is_disabled.lower().strip() == "true" if isinstance(_is_disabled, str) else bool(_is_disabled)
274
+
275
+ def instantiate(self, **kwargs: Any) -> object:
276
+ """
277
+ Instantiate component based on ``self.config`` content.
278
+ The target component must be a `class` or a `function`, otherwise, return `None`.
279
+
280
+ Args:
281
+ kwargs: args to override / add the config args when instantiation.
282
+
283
+ """
284
+ if not self.is_instantiable(self.get_config()) or self.is_disabled():
285
+ # if not a class or function or marked as `disabled`, skip parsing and return `None`
286
+ return None
287
+
288
+ modname = self.resolve_module_name()
289
+ mode = self.get_config().get("_mode_", CompInitMode.DEFAULT)
290
+ args = self.resolve_args()
291
+ args.update(kwargs)
292
+ return instantiate(modname, mode, **args)
293
+
294
+
295
+ class ConfigExpression(ConfigItem):
296
+ """
297
+ Subclass of :py:class:`monai.bundle.ConfigItem`, the `ConfigItem` represents an executable expression
298
+ (execute based on ``eval()``, or import the module to the `globals` if it's an import statement).
299
+
300
+ See also:
301
+
302
+ - https://docs.python.org/3/library/functions.html#eval.
303
+
304
+ For example:
305
+
306
+ .. code-block:: python
307
+
308
+ import monai
309
+ from monai.bundle import ConfigExpression
310
+
311
+ config = "$monai.__version__"
312
+ expression = ConfigExpression(config, id="test", globals={"monai": monai})
313
+ print(expression.evaluate())
314
+
315
+ Args:
316
+ config: content of a config item.
317
+ id: name of current config item, defaults to empty string.
318
+ globals: additional global context to evaluate the string.
319
+
320
+ """
321
+
322
+ prefix = EXPR_KEY
323
+ run_eval = run_eval
324
+
325
+ def __init__(self, config: Any, id: str = "", globals: dict | None = None) -> None:
326
+ super().__init__(config=config, id=id)
327
+ self.globals = globals if globals is not None else {}
328
+
329
+ def _parse_import_string(self, import_string: str) -> Any | None:
330
+ """parse single import statement such as "from monai.transforms import Resize"""
331
+ node = first(ast.iter_child_nodes(ast.parse(import_string)))
332
+ if not isinstance(node, (ast.Import, ast.ImportFrom)):
333
+ return None
334
+ if len(node.names) < 1:
335
+ return None
336
+ if len(node.names) > 1:
337
+ warnings.warn(f"ignoring multiple import alias '{import_string}'.")
338
+ name, asname = f"{node.names[0].name}", node.names[0].asname
339
+ asname = name if asname is None else f"{asname}"
340
+ if isinstance(node, ast.ImportFrom):
341
+ self.globals[asname], _ = optional_import(f"{node.module}", name=f"{name}")
342
+ return self.globals[asname]
343
+ if isinstance(node, ast.Import):
344
+ self.globals[asname], _ = optional_import(f"{name}")
345
+ return self.globals[asname]
346
+ return None
347
+
348
+ def evaluate(self, globals: dict | None = None, locals: dict | None = None) -> str | Any | None:
349
+ """
350
+ Execute the current config content and return the result if it is expression, based on Python `eval()`.
351
+ For more details: https://docs.python.org/3/library/functions.html#eval.
352
+
353
+ Args:
354
+ globals: besides ``self.globals``, other global symbols used in the expression at runtime.
355
+ locals: besides ``globals``, may also have some local symbols used in the expression at runtime.
356
+
357
+ """
358
+ value = self.get_config()
359
+ if not ConfigExpression.is_expression(value):
360
+ return None
361
+ optional_module = self._parse_import_string(value[len(self.prefix) :])
362
+ if optional_module is not None:
363
+ return optional_module
364
+ if not self.run_eval:
365
+ return f"{value[len(self.prefix) :]}"
366
+ globals_ = dict(self.globals)
367
+ if globals is not None:
368
+ for k, v in globals.items():
369
+ if k in globals_:
370
+ warnings.warn(f"the new global variable `{k}` conflicts with `self.globals`, override it.")
371
+ globals_[k] = v
372
+ if not run_debug:
373
+ try:
374
+ return eval(value[len(self.prefix) :], globals_, locals)
375
+ except Exception as e:
376
+ raise RuntimeError(f"Failed to evaluate {self}") from e
377
+ warnings.warn(
378
+ f"\n\npdb: value={value}\n"
379
+ f"See also Debugger commands documentation: https://docs.python.org/3/library/pdb.html\n"
380
+ )
381
+ import pdb
382
+
383
+ pdb.run(value[len(self.prefix) :], globals_, locals)
384
+ return None
385
+
386
+ @classmethod
387
+ def is_expression(cls, config: dict | list | str) -> bool:
388
+ """
389
+ Check whether the config is an executable expression string.
390
+ Currently, a string starts with ``"$"`` character is interpreted as an expression.
391
+
392
+ Args:
393
+ config: input config content to check.
394
+
395
+ """
396
+ return isinstance(config, str) and config.startswith(cls.prefix)
397
+
398
+ @classmethod
399
+ def is_import_statement(cls, config: dict | list | str) -> bool:
400
+ """
401
+ Check whether the config is an import statement (a special case of expression).
402
+
403
+ Args:
404
+ config: input config content to check.
405
+ """
406
+ if not cls.is_expression(config):
407
+ return False
408
+ if "import" not in config:
409
+ return False
410
+ return isinstance(
411
+ first(ast.iter_child_nodes(ast.parse(f"{config[len(cls.prefix) :]}"))), (ast.Import, ast.ImportFrom)
412
+ )
source_code/SegMamba/monai/bundle/config_parser.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from collections.abc import Sequence
17
+ from copy import deepcopy
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ from monai.bundle.config_item import ComponentLocator, ConfigComponent, ConfigExpression, ConfigItem
22
+ from monai.bundle.reference_resolver import ReferenceResolver
23
+ from monai.bundle.utils import ID_REF_KEY, ID_SEP_KEY, MACRO_KEY
24
+ from monai.config import PathLike
25
+ from monai.utils import ensure_tuple, look_up_option, optional_import
26
+ from monai.utils.misc import CheckKeyDuplicatesYamlLoader, check_key_duplicates
27
+
28
+ if TYPE_CHECKING:
29
+ import yaml
30
+ else:
31
+ yaml, _ = optional_import("yaml")
32
+
33
+ __all__ = ["ConfigParser"]
34
+
35
+ _default_globals = {"monai": "monai", "torch": "torch", "np": "numpy", "numpy": "numpy"}
36
+
37
+
38
+ class ConfigParser:
39
+ """
40
+ The primary configuration parser. It traverses a structured config (in the form of nested Python dict or list),
41
+ creates ``ConfigItem``, and assign unique IDs according to the structures.
42
+
43
+ This class provides convenient access to the set of ``ConfigItem`` of the config by ID.
44
+ A typical workflow of config parsing is as follows:
45
+
46
+ - Initialize ``ConfigParser`` with the ``config`` source.
47
+ - Call ``get_parsed_content()`` to get expected component with `id`.
48
+
49
+ .. code-block:: python
50
+
51
+ from monai.bundle import ConfigParser
52
+
53
+ config = {
54
+ "my_dims": 2,
55
+ "dims_1": "$@my_dims + 1",
56
+ "my_xform": {"_target_": "LoadImage"},
57
+ "my_net": {"_target_": "BasicUNet", "spatial_dims": "@dims_1", "in_channels": 1, "out_channels": 4},
58
+ "trainer": {"_target_": "SupervisedTrainer", "network": "@my_net", "preprocessing": "@my_xform"}
59
+ }
60
+ # in the example $@my_dims + 1 is an expression, which adds 1 to the value of @my_dims
61
+ parser = ConfigParser(config)
62
+
63
+ # get/set configuration content, the set method should happen before calling parse()
64
+ print(parser["my_net"]["in_channels"]) # original input channels 1
65
+ parser["my_net"]["in_channels"] = 4 # change input channels to 4
66
+ print(parser["my_net"]["in_channels"])
67
+
68
+ # instantiate the network component
69
+ parser.parse(True)
70
+ net = parser.get_parsed_content("my_net", instantiate=True)
71
+ print(net)
72
+
73
+ # also support to get the configuration content of parsed `ConfigItem`
74
+ trainer = parser.get_parsed_content("trainer", instantiate=False)
75
+ print(trainer)
76
+
77
+ Args:
78
+ config: input config source to parse.
79
+ excludes: when importing modules to instantiate components,
80
+ excluding components from modules specified in ``excludes``.
81
+ globals: pre-import packages as global variables to ``ConfigExpression``,
82
+ so that expressions, for example, ``"$monai.data.list_data_collate"`` can use ``monai`` modules.
83
+ The current supported globals and alias names are
84
+ ``{"monai": "monai", "torch": "torch", "np": "numpy", "numpy": "numpy"}``.
85
+ These are MONAI's minimal dependencies. Additional packages could be included with `globals={"itk": "itk"}`.
86
+ Set it to ``False`` to disable `self.globals` module importing.
87
+
88
+ See also:
89
+
90
+ - :py:class:`monai.bundle.ConfigItem`
91
+ - :py:class:`monai.bundle.scripts.run`
92
+
93
+ """
94
+
95
+ suffixes = ("json", "yaml", "yml")
96
+ suffix_match = rf".*\.({'|'.join(suffixes)})"
97
+ path_match = rf"({suffix_match}$)"
98
+ # match relative id names, e.g. "@#data", "@##transform#1"
99
+ relative_id_prefix = re.compile(rf"(?:{ID_REF_KEY}|{MACRO_KEY}){ID_SEP_KEY}+")
100
+ meta_key = "_meta_" # field key to save metadata
101
+
102
+ def __init__(
103
+ self,
104
+ config: Any = None,
105
+ excludes: Sequence[str] | str | None = None,
106
+ globals: dict[str, Any] | None | bool = None,
107
+ ):
108
+ self.config: ConfigItem | None = None
109
+ self.globals: dict[str, Any] = {}
110
+ _globals = _default_globals.copy()
111
+ if isinstance(_globals, dict) and globals not in (None, False):
112
+ _globals.update(globals) # type: ignore
113
+ if _globals is not None and globals is not False:
114
+ for k, v in _globals.items():
115
+ self.globals[k] = optional_import(v)[0] if isinstance(v, str) else v
116
+
117
+ self.locator = ComponentLocator(excludes=excludes)
118
+ self.ref_resolver = ReferenceResolver()
119
+ if config is None:
120
+ config = {self.meta_key: {}}
121
+ self.set(config=config)
122
+
123
+ def __repr__(self):
124
+ return f"{self.config}"
125
+
126
+ def __getattr__(self, id):
127
+ """
128
+ Get the parsed result of ``ConfigItem`` with the specified ``id``
129
+ with default arguments (e.g. ``lazy=True``, ``instantiate=True`` and ``eval_expr=True``).
130
+
131
+ Args:
132
+ id: id of the ``ConfigItem``.
133
+
134
+ See also:
135
+ :py:meth:`get_parsed_content`
136
+ """
137
+ return self.get_parsed_content(id)
138
+
139
+ def __getitem__(self, id: str | int) -> Any:
140
+ """
141
+ Get the config by id.
142
+
143
+ Args:
144
+ id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to
145
+ go one level further into the nested structures.
146
+ Use digits indexing from "0" for list or other strings for dict.
147
+ For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``.
148
+
149
+ """
150
+ if id == "":
151
+ return self.config
152
+ config = self.config
153
+ for k in ReferenceResolver.split_id(id):
154
+ if not isinstance(config, (dict, list)):
155
+ raise ValueError(f"config must be dict or list for key `{k}`, but got {type(config)}: {config}.")
156
+ try:
157
+ config = (
158
+ look_up_option(k, config, print_all_options=False) if isinstance(config, dict) else config[int(k)]
159
+ )
160
+ except ValueError as e:
161
+ raise KeyError(f"query key: {k}") from e
162
+ return config
163
+
164
+ def __setitem__(self, id: str | int, config: Any) -> None:
165
+ """
166
+ Set config by ``id``. Note that this method should be used before ``parse()`` or ``get_parsed_content()``
167
+ to ensure the updates are included in the parsed content.
168
+
169
+ Args:
170
+ id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to
171
+ go one level further into the nested structures.
172
+ Use digits indexing from "0" for list or other strings for dict.
173
+ For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``.
174
+ config: config to set at location ``id``.
175
+
176
+ """
177
+ if id == "":
178
+ self.config = config
179
+ self.ref_resolver.reset()
180
+ return
181
+ last_id, base_id = ReferenceResolver.split_id(id, last=True)
182
+ # get the last parent level config item and replace it
183
+ conf_ = self[last_id]
184
+
185
+ indexing = base_id if isinstance(conf_, dict) else int(base_id)
186
+ conf_[indexing] = config
187
+ self.ref_resolver.reset()
188
+ return
189
+
190
+ def get(self, id: str = "", default: Any | None = None) -> Any:
191
+ """
192
+ Get the config by id.
193
+
194
+ Args:
195
+ id: id to specify the expected position. See also :py:meth:`__getitem__`.
196
+ default: default value to return if the specified ``id`` is invalid.
197
+
198
+ """
199
+ try:
200
+ return self[id]
201
+ except (KeyError, IndexError, ValueError): # Index error for integer indexing
202
+ return default
203
+
204
+ def set(self, config: Any, id: str = "", recursive: bool = True) -> None:
205
+ """
206
+ Set config by ``id``.
207
+
208
+ Args:
209
+ config: config to set at location ``id``.
210
+ id: id to specify the expected position. See also :py:meth:`__setitem__`.
211
+ recursive: if the nested id doesn't exist, whether to recursively create the nested items in the config.
212
+ default to `True`. for the nested id, only support `dict` for the missing section.
213
+
214
+ """
215
+ keys = ReferenceResolver.split_id(id)
216
+ conf_ = self.get()
217
+ if recursive:
218
+ if conf_ is None:
219
+ self.config = conf_ = {} # type: ignore
220
+ for k in keys[:-1]:
221
+ if isinstance(conf_, dict) and k not in conf_:
222
+ conf_[k] = {}
223
+ conf_ = conf_[k if isinstance(conf_, dict) else int(k)]
224
+ self[ReferenceResolver.normalize_id(id)] = config
225
+
226
+ def update(self, pairs: dict[str, Any]) -> None:
227
+ """
228
+ Set the ``id`` and the corresponding config content in pairs, see also :py:meth:`__setitem__`.
229
+ For example, ``parser.update({"train::epoch": 100, "train::lr": 0.02})``
230
+
231
+ Args:
232
+ pairs: dictionary of `id` and config pairs.
233
+
234
+ """
235
+ for k, v in pairs.items():
236
+ self[k] = v
237
+
238
+ def __contains__(self, id: str | int) -> bool:
239
+ """
240
+ Returns True if `id` is stored in this configuration.
241
+
242
+ Args:
243
+ id: id to specify the expected position. See also :py:meth:`__getitem__`.
244
+ """
245
+ try:
246
+ _ = self[id]
247
+ return True
248
+ except (KeyError, IndexError, ValueError): # Index error for integer indexing
249
+ return False
250
+
251
+ def parse(self, reset: bool = True) -> None:
252
+ """
253
+ Recursively resolve `self.config` to replace the macro tokens with target content.
254
+ Then recursively parse the config source, add every item as ``ConfigItem`` to the reference resolver.
255
+
256
+ Args:
257
+ reset: whether to reset the ``reference_resolver`` before parsing. Defaults to `True`.
258
+
259
+ """
260
+ if reset:
261
+ self.ref_resolver.reset()
262
+ self.resolve_macro_and_relative_ids()
263
+ self._do_parse(config=self.get())
264
+
265
+ def get_parsed_content(self, id: str = "", **kwargs: Any) -> Any:
266
+ """
267
+ Get the parsed result of ``ConfigItem`` with the specified ``id``.
268
+
269
+ - If the item is ``ConfigComponent`` and ``instantiate=True``, the result is the instance.
270
+ - If the item is ``ConfigExpression`` and ``eval_expr=True``, the result is the evaluated output.
271
+ - Else, the result is the configuration content of `ConfigItem`.
272
+
273
+ Args:
274
+ id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to
275
+ go one level further into the nested structures.
276
+ Use digits indexing from "0" for list or other strings for dict.
277
+ For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``.
278
+ kwargs: additional keyword arguments to be passed to ``_resolve_one_item``.
279
+ Currently support ``lazy`` (whether to retain the current config cache, default to `True`),
280
+ ``instantiate`` (whether to instantiate the `ConfigComponent`, default to `True`) and
281
+ ``eval_expr`` (whether to evaluate the `ConfigExpression`, default to `True`), ``default``
282
+ (the default config item if the `id` is not in the config content).
283
+
284
+ """
285
+ if not self.ref_resolver.is_resolved():
286
+ # not parsed the config source yet, parse it
287
+ self.parse(reset=True)
288
+ elif not kwargs.get("lazy", True):
289
+ self.parse(reset=not kwargs.get("lazy", True))
290
+ return self.ref_resolver.get_resolved_content(id=id, **kwargs)
291
+
292
+ def read_meta(self, f: PathLike | Sequence[PathLike] | dict, **kwargs: Any) -> None:
293
+ """
294
+ Read the metadata from specified JSON or YAML file.
295
+ The metadata as a dictionary will be stored at ``self.config["_meta_"]``.
296
+
297
+ Args:
298
+ f: filepath of the metadata file, the content must be a dictionary,
299
+ if providing a list of files, will merge the content of them.
300
+ if providing a dictionary directly, use it as metadata.
301
+ kwargs: other arguments for ``json.load`` or ``yaml.safe_load``, depends on the file format.
302
+
303
+ """
304
+ self.set(self.load_config_files(f, **kwargs), self.meta_key)
305
+
306
+ def read_config(self, f: PathLike | Sequence[PathLike] | dict, **kwargs: Any) -> None:
307
+ """
308
+ Read the config from specified JSON/YAML file or a dictionary and
309
+ override the config content in the `self.config` dictionary.
310
+
311
+ Args:
312
+ f: filepath of the config file, the content must be a dictionary,
313
+ if providing a list of files, wil merge the content of them.
314
+ if providing a dictionary directly, use it as config.
315
+ kwargs: other arguments for ``json.load`` or ``yaml.safe_load``, depends on the file format.
316
+
317
+ """
318
+ content = {self.meta_key: self.get(self.meta_key, {})}
319
+ content.update(self.load_config_files(f, **kwargs))
320
+ self.set(config=content)
321
+
322
+ def _do_resolve(self, config: Any, id: str = "") -> Any:
323
+ """
324
+ Recursively resolve `self.config` to replace the relative ids with absolute ids, for example,
325
+ `@##A` means `A` in the upper level. and replace the macro tokens with target content,
326
+ The macro tokens start with "%", can be from another structured file, like:
327
+ ``"%default_net"``, ``"%/data/config.json#net"``.
328
+ Note that the macro replacement doesn't support recursive macro tokens.
329
+
330
+ Args:
331
+ config: input config file to resolve.
332
+ id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to
333
+ go one level further into the nested structures.
334
+ Use digits indexing from "0" for list or other strings for dict.
335
+ For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``.
336
+
337
+ """
338
+ if isinstance(config, (dict, list)):
339
+ for k, sub_id, v in self.ref_resolver.iter_subconfigs(id=id, config=config):
340
+ config[k] = self._do_resolve(v, sub_id) # type: ignore
341
+ if isinstance(config, str):
342
+ config = self.resolve_relative_ids(id, config)
343
+ if config.startswith(MACRO_KEY):
344
+ path, ids = ConfigParser.split_path_id(config[len(MACRO_KEY) :])
345
+ parser = ConfigParser(config=self.get() if not path else ConfigParser.load_config_file(path))
346
+ # deepcopy to ensure the macro replacement is independent config content
347
+ return deepcopy(parser[ids])
348
+ return config
349
+
350
+ def resolve_macro_and_relative_ids(self):
351
+ """
352
+ Recursively resolve `self.config` to replace the relative ids with absolute ids, for example,
353
+ `@##A` means `A` in the upper level. and replace the macro tokens with target content,
354
+ The macro tokens are marked as starting with "%", can be from another structured file, like:
355
+ ``"%default_net"``, ``"%/data/config.json::net"``.
356
+
357
+ """
358
+ self.set(self._do_resolve(config=self.get()))
359
+
360
+ def _do_parse(self, config: Any, id: str = "") -> None:
361
+ """
362
+ Recursively parse the nested data in config source, add every item as `ConfigItem` to the resolver.
363
+
364
+ Args:
365
+ config: config source to parse.
366
+ id: id of the ``ConfigItem``, ``"::"`` (or ``"#"``) in id are interpreted as special characters to
367
+ go one level further into the nested structures.
368
+ Use digits indexing from "0" for list or other strings for dict.
369
+ For example: ``"xform::5"``, ``"net::channels"``. ``""`` indicates the entire ``self.config``.
370
+
371
+ """
372
+ if isinstance(config, (dict, list)):
373
+ for _, sub_id, v in self.ref_resolver.iter_subconfigs(id=id, config=config):
374
+ self._do_parse(config=v, id=sub_id)
375
+
376
+ if ConfigComponent.is_instantiable(config):
377
+ self.ref_resolver.add_item(ConfigComponent(config=config, id=id, locator=self.locator))
378
+ elif ConfigExpression.is_expression(config):
379
+ self.ref_resolver.add_item(ConfigExpression(config=config, id=id, globals=self.globals))
380
+ else:
381
+ self.ref_resolver.add_item(ConfigItem(config=config, id=id))
382
+
383
+ @classmethod
384
+ def load_config_file(cls, filepath: PathLike, **kwargs: Any) -> dict:
385
+ """
386
+ Load a single config file with specified file path (currently support JSON and YAML files).
387
+
388
+ Args:
389
+ filepath: path of target file to load, supported postfixes: `.json`, `.yml`, `.yaml`.
390
+ kwargs: other arguments for ``json.load`` or ```yaml.safe_load``, depends on the file format.
391
+
392
+ """
393
+ if not filepath:
394
+ return {}
395
+ _filepath: str = str(Path(filepath))
396
+ if not re.compile(cls.path_match, re.IGNORECASE).findall(_filepath):
397
+ raise ValueError(f'unknown file input: "{filepath}"')
398
+ with open(_filepath) as f:
399
+ if _filepath.lower().endswith(cls.suffixes[0]):
400
+ return json.load(f, object_pairs_hook=check_key_duplicates, **kwargs) # type: ignore[no-any-return]
401
+ if _filepath.lower().endswith(cls.suffixes[1:]):
402
+ return yaml.load(f, CheckKeyDuplicatesYamlLoader, **kwargs) # type: ignore[no-any-return]
403
+ raise ValueError(f"only support JSON or YAML config file so far, got name {_filepath}.")
404
+
405
+ @classmethod
406
+ def load_config_files(cls, files: PathLike | Sequence[PathLike] | dict, **kwargs: Any) -> dict:
407
+ """
408
+ Load multiple config files into a single config dict.
409
+ The latter config file in the list will override or add the former config file.
410
+ ``"::"`` (or ``"#"``) in the config keys are interpreted as special characters to go one level
411
+ further into the nested structures.
412
+
413
+ Args:
414
+ files: path of target files to load, supported postfixes: `.json`, `.yml`, `.yaml`.
415
+ if providing a list of files, will merge the content of them.
416
+ if providing a string with comma separated file paths, will merge the content of them.
417
+ if providing a dictionary, return it directly.
418
+ kwargs: other arguments for ``json.load`` or ```yaml.safe_load``, depends on the file format.
419
+ """
420
+ if isinstance(files, dict): # already a config dict
421
+ return files
422
+ parser = ConfigParser(config={})
423
+ if isinstance(files, str) and not Path(files).is_file() and "," in files:
424
+ files = files.split(",")
425
+ for i in ensure_tuple(files):
426
+ for k, v in (cls.load_config_file(i, **kwargs)).items():
427
+ parser[k] = v
428
+ return parser.get() # type: ignore
429
+
430
+ @classmethod
431
+ def export_config_file(cls, config: dict, filepath: PathLike, fmt: str = "json", **kwargs: Any) -> None:
432
+ """
433
+ Export the config content to the specified file path (currently support JSON and YAML files).
434
+
435
+ Args:
436
+ config: source config content to export.
437
+ filepath: target file path to save.
438
+ fmt: format of config content, currently support ``"json"`` and ``"yaml"``.
439
+ kwargs: other arguments for ``json.dump`` or ``yaml.safe_dump``, depends on the file format.
440
+
441
+ """
442
+ _filepath: str = str(Path(filepath))
443
+ writer = look_up_option(fmt.lower(), {"json", "yaml", "yml"})
444
+ with open(_filepath, "w") as f:
445
+ if writer == "json":
446
+ json.dump(config, f, **kwargs)
447
+ return
448
+ if writer == "yaml" or writer == "yml":
449
+ return yaml.safe_dump(config, f, **kwargs)
450
+ raise ValueError(f"only support JSON or YAML config file so far, got {writer}.")
451
+
452
+ @classmethod
453
+ def split_path_id(cls, src: str) -> tuple[str, str]:
454
+ """
455
+ Split `src` string into two parts: a config file path and component id.
456
+ The file path should end with `(json|yaml|yml)`. The component id should be separated by `::` if it exists.
457
+ If no path or no id, return "".
458
+
459
+ Args:
460
+ src: source string to split.
461
+
462
+ """
463
+ src = ReferenceResolver.normalize_id(src)
464
+ result = re.compile(rf"({cls.suffix_match}(?=(?:{ID_SEP_KEY}.*)|$))", re.IGNORECASE).findall(src)
465
+ if not result:
466
+ return "", src # the src is a pure id
467
+ path_name = result[0][0] # at most one path_name
468
+ _, ids = src.rsplit(path_name, 1)
469
+ return path_name, ids[len(ID_SEP_KEY) :] if ids.startswith(ID_SEP_KEY) else ""
470
+
471
+ @classmethod
472
+ def resolve_relative_ids(cls, id: str, value: str) -> str:
473
+ """
474
+ To simplify the reference or macro tokens ID in the nested config content, it's available to use
475
+ relative ID name which starts with the `ID_SEP_KEY`, for example, "@#A" means `A` in the same level,
476
+ `@##A` means `A` in the upper level.
477
+ It resolves the relative ids to absolute ids. For example, if the input data is:
478
+
479
+ .. code-block:: python
480
+
481
+ {
482
+ "A": 1,
483
+ "B": {"key": "@##A", "value1": 2, "value2": "%#value1", "value3": [3, 4, "@#1"]},
484
+ }
485
+
486
+ It will resolve `B` to `{"key": "@A", "value1": 2, "value2": "%B#value1", "value3": [3, 4, "@B#value3#1"]}`.
487
+
488
+ Args:
489
+ id: id name for current config item to compute relative id.
490
+ value: input value to resolve relative ids.
491
+
492
+ """
493
+ # get the prefixes like: "@####", "%###", "@#"
494
+ value = ReferenceResolver.normalize_id(value)
495
+ prefixes = sorted(set().union(cls.relative_id_prefix.findall(value)), reverse=True)
496
+ current_id = id.split(ID_SEP_KEY)
497
+
498
+ for p in prefixes:
499
+ sym = ID_REF_KEY if ID_REF_KEY in p else MACRO_KEY
500
+ length = p[len(sym) :].count(ID_SEP_KEY)
501
+ if length > len(current_id):
502
+ raise ValueError(f"the relative id in `{value}` is out of the range of config content.")
503
+ if length == len(current_id):
504
+ new = "" # root id is `""`
505
+ else:
506
+ new = ID_SEP_KEY.join(current_id[:-length]) + ID_SEP_KEY
507
+ value = value.replace(p, sym + new)
508
+ return value
source_code/SegMamba/monai/bundle/properties.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+ """
12
+ The predefined properties for a bundle workflow, other applications can leverage the properties
13
+ to interact with the bundle workflow.
14
+ Some properties are required and some are optional, optional properties mean: if some component of the
15
+ bundle workflow refer to the property, the property must be defined, otherwise, the property can be None.
16
+ Every item in this `TrainProperties` or `InferProperties` or `MetaProperties` dictionary is a property,
17
+ the key is the property name and the values include:
18
+ 1. description.
19
+ 2. whether it's a required property.
20
+ 3. config item ID name (only applicable when the bundle workflow is defined in config).
21
+ 4. reference config item ID name (only applicable when the bundle workflow is defined in config).
22
+
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from monai.bundle.utils import ID_SEP_KEY
28
+ from monai.utils import BundleProperty, BundlePropertyConfig
29
+
30
+ TrainProperties = {
31
+ "bundle_root": {
32
+ BundleProperty.DESC: "root path of the bundle.",
33
+ BundleProperty.REQUIRED: True,
34
+ BundlePropertyConfig.ID: "bundle_root",
35
+ },
36
+ "device": {
37
+ BundleProperty.DESC: "target device to execute the bundle workflow.",
38
+ BundleProperty.REQUIRED: True,
39
+ BundlePropertyConfig.ID: "device",
40
+ },
41
+ "dataset_dir": {
42
+ BundleProperty.DESC: "directory path of the dataset.",
43
+ BundleProperty.REQUIRED: True,
44
+ BundlePropertyConfig.ID: "dataset_dir",
45
+ },
46
+ "trainer": {
47
+ BundleProperty.DESC: "training workflow engine.",
48
+ BundleProperty.REQUIRED: True,
49
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}trainer",
50
+ },
51
+ "network_def": {
52
+ BundleProperty.DESC: "network module for the training.",
53
+ BundleProperty.REQUIRED: False,
54
+ BundlePropertyConfig.ID: "network_def",
55
+ },
56
+ "max_epochs": {
57
+ BundleProperty.DESC: "max number of epochs to execute the training.",
58
+ BundleProperty.REQUIRED: True,
59
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}max_epochs",
60
+ },
61
+ "train_dataset": {
62
+ BundleProperty.DESC: "PyTorch dataset object for the training logic.",
63
+ BundleProperty.REQUIRED: True,
64
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}dataset",
65
+ },
66
+ "train_inferer": {
67
+ BundleProperty.DESC: "MONAI Inferer object to execute the model computation in training.",
68
+ BundleProperty.REQUIRED: True,
69
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}inferer",
70
+ },
71
+ "train_dataset_data": {
72
+ BundleProperty.DESC: "data source for the training dataset.",
73
+ BundleProperty.REQUIRED: False,
74
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}dataset{ID_SEP_KEY}data",
75
+ BundlePropertyConfig.REF_ID: None, # no reference to this ID
76
+ },
77
+ "train_handlers": {
78
+ BundleProperty.DESC: "event-handlers for the training logic.",
79
+ BundleProperty.REQUIRED: False,
80
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}handlers",
81
+ BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}train_handlers",
82
+ },
83
+ "train_preprocessing": {
84
+ BundleProperty.DESC: "preprocessing for the training input data.",
85
+ BundleProperty.REQUIRED: False,
86
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}preprocessing",
87
+ BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}dataset{ID_SEP_KEY}transform",
88
+ },
89
+ "train_postprocessing": {
90
+ BundleProperty.DESC: "postprocessing for the training model output data.",
91
+ BundleProperty.REQUIRED: False,
92
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}postprocessing",
93
+ BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}postprocessing",
94
+ },
95
+ "train_key_metric": {
96
+ BundleProperty.DESC: "key metric to compute on the training data.",
97
+ BundleProperty.REQUIRED: False,
98
+ BundlePropertyConfig.ID: f"train{ID_SEP_KEY}key_metric",
99
+ BundlePropertyConfig.REF_ID: f"train{ID_SEP_KEY}trainer{ID_SEP_KEY}key_train_metric",
100
+ },
101
+ "evaluator": {
102
+ BundleProperty.DESC: "validation workflow engine.",
103
+ BundleProperty.REQUIRED: False,
104
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}evaluator",
105
+ BundlePropertyConfig.REF_ID: "validator", # this REF_ID is the arg name of `ValidationHandler`
106
+ },
107
+ "val_interval": {
108
+ BundleProperty.DESC: "validation interval during the training.",
109
+ BundleProperty.REQUIRED: False,
110
+ BundlePropertyConfig.ID: "val_interval",
111
+ BundlePropertyConfig.REF_ID: "interval", # this REF_ID is the arg name of `ValidationHandler`
112
+ },
113
+ "val_handlers": {
114
+ BundleProperty.DESC: "event-handlers for the validation logic.",
115
+ BundleProperty.REQUIRED: False,
116
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}handlers",
117
+ BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}val_handlers",
118
+ },
119
+ "val_dataset": {
120
+ BundleProperty.DESC: "PyTorch dataset object for the validation logic.",
121
+ BundleProperty.REQUIRED: False,
122
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}dataset",
123
+ BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}dataloader{ID_SEP_KEY}dataset",
124
+ },
125
+ "val_dataset_data": {
126
+ BundleProperty.DESC: "data source for the validation dataset.",
127
+ BundleProperty.REQUIRED: False,
128
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}dataset{ID_SEP_KEY}data",
129
+ BundlePropertyConfig.REF_ID: None, # no reference to this ID
130
+ },
131
+ "val_inferer": {
132
+ BundleProperty.DESC: "MONAI Inferer object to execute the model computation in validation.",
133
+ BundleProperty.REQUIRED: False,
134
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}inferer",
135
+ BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}inferer",
136
+ },
137
+ "val_preprocessing": {
138
+ BundleProperty.DESC: "preprocessing for the validation input data.",
139
+ BundleProperty.REQUIRED: False,
140
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}preprocessing",
141
+ BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}dataset{ID_SEP_KEY}transform",
142
+ },
143
+ "val_postprocessing": {
144
+ BundleProperty.DESC: "postprocessing for the validation model output data.",
145
+ BundleProperty.REQUIRED: False,
146
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}postprocessing",
147
+ BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}postprocessing",
148
+ },
149
+ "val_key_metric": {
150
+ BundleProperty.DESC: "key metric to compute on the validation data.",
151
+ BundleProperty.REQUIRED: False,
152
+ BundlePropertyConfig.ID: f"validate{ID_SEP_KEY}key_metric",
153
+ BundlePropertyConfig.REF_ID: f"validate{ID_SEP_KEY}evaluator{ID_SEP_KEY}key_val_metric",
154
+ },
155
+ }
156
+
157
+ InferProperties = {
158
+ "bundle_root": {
159
+ BundleProperty.DESC: "root path of the bundle.",
160
+ BundleProperty.REQUIRED: True,
161
+ BundlePropertyConfig.ID: "bundle_root",
162
+ },
163
+ "device": {
164
+ BundleProperty.DESC: "target device to execute the bundle workflow.",
165
+ BundleProperty.REQUIRED: True,
166
+ BundlePropertyConfig.ID: "device",
167
+ },
168
+ "dataset_dir": {
169
+ BundleProperty.DESC: "directory path of the dataset.",
170
+ BundleProperty.REQUIRED: True,
171
+ BundlePropertyConfig.ID: "dataset_dir",
172
+ },
173
+ "dataset": {
174
+ BundleProperty.DESC: "PyTorch dataset object for the inference / evaluation logic.",
175
+ BundleProperty.REQUIRED: True,
176
+ BundlePropertyConfig.ID: "dataset",
177
+ },
178
+ "evaluator": {
179
+ BundleProperty.DESC: "inference / evaluation workflow engine.",
180
+ BundleProperty.REQUIRED: True,
181
+ BundlePropertyConfig.ID: "evaluator",
182
+ },
183
+ "network_def": {
184
+ BundleProperty.DESC: "network module for the inference.",
185
+ BundleProperty.REQUIRED: True,
186
+ BundlePropertyConfig.ID: "network_def",
187
+ },
188
+ "inferer": {
189
+ BundleProperty.DESC: "MONAI Inferer object to execute the model computation in inference.",
190
+ BundleProperty.REQUIRED: True,
191
+ BundlePropertyConfig.ID: "inferer",
192
+ },
193
+ "dataset_data": {
194
+ BundleProperty.DESC: "data source for the inference / evaluation dataset.",
195
+ BundleProperty.REQUIRED: False,
196
+ BundlePropertyConfig.ID: f"dataset{ID_SEP_KEY}data",
197
+ BundlePropertyConfig.REF_ID: None, # no reference to this ID
198
+ },
199
+ "handlers": {
200
+ BundleProperty.DESC: "event-handlers for the inference / evaluation logic.",
201
+ BundleProperty.REQUIRED: False,
202
+ BundlePropertyConfig.ID: "handlers",
203
+ BundlePropertyConfig.REF_ID: f"evaluator{ID_SEP_KEY}val_handlers",
204
+ },
205
+ "preprocessing": {
206
+ BundleProperty.DESC: "preprocessing for the input data.",
207
+ BundleProperty.REQUIRED: False,
208
+ BundlePropertyConfig.ID: "preprocessing",
209
+ BundlePropertyConfig.REF_ID: f"dataset{ID_SEP_KEY}transform",
210
+ },
211
+ "postprocessing": {
212
+ BundleProperty.DESC: "postprocessing for the model output data.",
213
+ BundleProperty.REQUIRED: False,
214
+ BundlePropertyConfig.ID: "postprocessing",
215
+ BundlePropertyConfig.REF_ID: f"evaluator{ID_SEP_KEY}postprocessing",
216
+ },
217
+ "key_metric": {
218
+ BundleProperty.DESC: "the key metric during evaluation.",
219
+ BundleProperty.REQUIRED: False,
220
+ BundlePropertyConfig.ID: "key_metric",
221
+ BundlePropertyConfig.REF_ID: f"evaluator{ID_SEP_KEY}key_val_metric",
222
+ },
223
+ }
224
+
225
+ MetaProperties = {
226
+ "version": {
227
+ BundleProperty.DESC: "bundle version",
228
+ BundleProperty.REQUIRED: True,
229
+ BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}version",
230
+ },
231
+ "monai_version": {
232
+ BundleProperty.DESC: "required monai version used for bundle",
233
+ BundleProperty.REQUIRED: True,
234
+ BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}monai_version",
235
+ },
236
+ "pytorch_version": {
237
+ BundleProperty.DESC: "required pytorch version used for bundle",
238
+ BundleProperty.REQUIRED: True,
239
+ BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}pytorch_version",
240
+ },
241
+ "numpy_version": {
242
+ BundleProperty.DESC: "required numpy version used for bundle",
243
+ BundleProperty.REQUIRED: True,
244
+ BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}numpy_version",
245
+ },
246
+ "description": {
247
+ BundleProperty.DESC: "description for bundle",
248
+ BundleProperty.REQUIRED: False,
249
+ BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}description",
250
+ },
251
+ "spatial_shape": {
252
+ BundleProperty.DESC: "spatial shape for the inputs",
253
+ BundleProperty.REQUIRED: False,
254
+ BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}network_data_format{ID_SEP_KEY}inputs{ID_SEP_KEY}image"
255
+ f"{ID_SEP_KEY}spatial_shape",
256
+ },
257
+ "channel_def": {
258
+ BundleProperty.DESC: "channel definition for the prediction",
259
+ BundleProperty.REQUIRED: False,
260
+ BundlePropertyConfig.ID: f"_meta_{ID_SEP_KEY}network_data_format{ID_SEP_KEY}outputs{ID_SEP_KEY}pred{ID_SEP_KEY}channel_def",
261
+ },
262
+ }
source_code/SegMamba/monai/bundle/reference_resolver.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import warnings
16
+ from collections.abc import Sequence
17
+ from typing import Any, Iterator
18
+
19
+ from monai.bundle.config_item import ConfigComponent, ConfigExpression, ConfigItem
20
+ from monai.bundle.utils import ID_REF_KEY, ID_SEP_KEY
21
+ from monai.utils import allow_missing_reference, look_up_option
22
+
23
+ __all__ = ["ReferenceResolver"]
24
+
25
+
26
+ class ReferenceResolver:
27
+ """
28
+ Utility class to manage a set of ``ConfigItem`` and resolve the references between them.
29
+
30
+ This class maintains a set of ``ConfigItem`` objects and their associated IDs.
31
+ The IDs must be unique within this set. A string in ``ConfigItem``
32
+ starting with ``@`` will be treated as a reference to other ``ConfigItem`` objects by ID.
33
+ Since ``ConfigItem`` may have a nested dictionary or list structure,
34
+ the reference string may also contain the separator ``::`` to refer to a substructure by
35
+ key indexing for a dictionary or integer indexing for a list.
36
+
37
+ In this class, resolving references is essentially substitution of the reference strings with the
38
+ corresponding python objects. A typical workflow of resolving references is as follows:
39
+
40
+ - Add multiple ``ConfigItem`` objects to the ``ReferenceResolver`` by ``add_item()``.
41
+ - Call ``get_resolved_content()`` to automatically resolve the references. This is done (recursively) by:
42
+ - Convert the items to objects, for those do not have references to other items.
43
+ - If it is instantiable, instantiate it and cache the class instance in ``resolved_content``.
44
+ - If it is an expression, evaluate it and save the value in ``resolved_content``.
45
+ - Substitute the reference strings with the corresponding objects.
46
+
47
+ Args:
48
+ items: ``ConfigItem``s to resolve, this could be added later with ``add_item()``.
49
+
50
+ """
51
+
52
+ _vars = "__local_refs"
53
+ sep = ID_SEP_KEY # separator for key indexing
54
+ ref = ID_REF_KEY # reference prefix
55
+ # match a reference string, e.g. "@id::key", "@id::key::0", "@_target_::key"
56
+ id_matcher = re.compile(rf"{ref}(?:\w*)(?:{sep}\w*)*")
57
+ # if `allow_missing_reference` and can't find a reference ID, will just raise a warning and don't update the config
58
+ allow_missing_reference = allow_missing_reference
59
+
60
+ def __init__(self, items: Sequence[ConfigItem] | None = None):
61
+ # save the items in a dictionary with the `ConfigItem.id` as key
62
+ self.items: dict[str, ConfigItem] = {} if items is None else {i.get_id(): i for i in items}
63
+ self.resolved_content: dict[str, ConfigExpression | str | Any | None] = {}
64
+
65
+ def reset(self):
66
+ """
67
+ Clear all the added `ConfigItem` and all the resolved content.
68
+
69
+ """
70
+ self.items = {}
71
+ self.resolved_content = {}
72
+
73
+ def is_resolved(self) -> bool:
74
+ return bool(self.resolved_content)
75
+
76
+ def add_item(self, item: ConfigItem) -> None:
77
+ """
78
+ Add a ``ConfigItem`` to the resolver.
79
+
80
+ Args:
81
+ item: a ``ConfigItem``.
82
+
83
+ """
84
+ id = item.get_id()
85
+ if id in self.items:
86
+ return
87
+ self.items[id] = item
88
+
89
+ def get_item(self, id: str, resolve: bool = False, **kwargs: Any) -> ConfigItem | None:
90
+ """
91
+ Get the ``ConfigItem`` by id.
92
+
93
+ If ``resolve=True``, the returned item will be resolved, that is,
94
+ all the reference strings are substituted by the corresponding ``ConfigItem`` objects.
95
+
96
+ Args:
97
+ id: id of the expected config item.
98
+ resolve: whether to resolve the item if it is not resolved, default to False.
99
+ kwargs: keyword arguments to pass to ``_resolve_one_item()``.
100
+ Currently support ``instantiate`` and ``eval_expr``. Both are defaulting to True.
101
+ """
102
+ id = self.normalize_id(id)
103
+ if resolve and id not in self.resolved_content:
104
+ self._resolve_one_item(id=id, **kwargs)
105
+ return self.items.get(id)
106
+
107
+ def _resolve_one_item(
108
+ self, id: str, waiting_list: set[str] | None = None, **kwargs: Any
109
+ ) -> ConfigExpression | str | Any | None:
110
+ """
111
+ Resolve and return one ``ConfigItem`` of ``id``, cache the resolved result in ``resolved_content``.
112
+ If it has unresolved references, recursively resolve the referring items first.
113
+
114
+ Args:
115
+ id: id name of ``ConfigItem`` to be resolved.
116
+ waiting_list: set of ids pending to be resolved.
117
+ It's used to detect circular references such as:
118
+ `{"name": "A", "dep": "@B"}` and `{"name": "B", "dep": "@A"}`.
119
+ kwargs: keyword arguments to pass to ``_resolve_one_item()``.
120
+ Currently support ``instantiate``, ``eval_expr`` and ``default``.
121
+ `instantiate` and `eval_expr` are defaulting to True, `default` is the target config item
122
+ if the `id` is not in the config content, must be a `ConfigItem` object.
123
+
124
+ """
125
+ id = self.normalize_id(id)
126
+ if id in self.resolved_content:
127
+ return self.resolved_content[id]
128
+ try:
129
+ item = look_up_option(id, self.items, print_all_options=False, default=kwargs.get("default", "no_default"))
130
+ except ValueError as err:
131
+ raise KeyError(f"id='{id}' is not found in the config resolver.") from err
132
+ if not isinstance(item, ConfigItem):
133
+ return item
134
+ item_config = item.get_config()
135
+
136
+ if waiting_list is None:
137
+ waiting_list = set()
138
+ waiting_list.add(id)
139
+
140
+ for t, v in self.items.items():
141
+ if (
142
+ t not in self.resolved_content
143
+ and isinstance(v, ConfigExpression)
144
+ and v.is_import_statement(v.get_config())
145
+ ):
146
+ self.resolved_content[t] = v.evaluate() if kwargs.get("eval_expr", True) else v
147
+ for d in self.find_refs_in_config(config=item_config, id=id).keys():
148
+ # if current item has reference already in the waiting list, that's circular references
149
+ if d in waiting_list:
150
+ raise ValueError(f"detected circular references '{d}' for id='{id}' in the config content.")
151
+ # check whether the component has any unresolved references
152
+ if d not in self.resolved_content:
153
+ # this referring item is not resolved
154
+ try:
155
+ look_up_option(d, self.items, print_all_options=False)
156
+ except ValueError as err:
157
+ msg = f"the referring item `@{d}` is not defined in the config content."
158
+ if not self.allow_missing_reference:
159
+ raise ValueError(msg) from err
160
+ warnings.warn(msg)
161
+ continue
162
+ # recursively resolve the reference first
163
+ self._resolve_one_item(id=d, waiting_list=waiting_list, **kwargs)
164
+ waiting_list.discard(d)
165
+
166
+ # all references are resolved, then try to resolve current config item
167
+ new_config = self.update_config_with_refs(config=item_config, id=id, refs=self.resolved_content)
168
+ item.update_config(config=new_config)
169
+ # save the resolved result into `resolved_content` to recursively resolve others
170
+ if isinstance(item, ConfigComponent):
171
+ self.resolved_content[id] = item.instantiate() if kwargs.get("instantiate", True) else item
172
+ elif isinstance(item, ConfigExpression):
173
+ run_eval = kwargs.get("eval_expr", True)
174
+ self.resolved_content[id] = (
175
+ item.evaluate(globals={f"{self._vars}": self.resolved_content}) if run_eval else item
176
+ )
177
+ else:
178
+ self.resolved_content[id] = new_config
179
+ return self.resolved_content[id]
180
+
181
+ def get_resolved_content(self, id: str, **kwargs: Any) -> ConfigExpression | str | Any | None:
182
+ """
183
+ Get the resolved ``ConfigItem`` by id.
184
+
185
+ Args:
186
+ id: id name of the expected item.
187
+ kwargs: keyword arguments to pass to ``_resolve_one_item()``.
188
+ Currently support ``instantiate``, ``eval_expr`` and ``default``.
189
+ `instantiate` and `eval_expr` are defaulting to True, `default` is the target config item
190
+ if the `id` is not in the config content, must be a `ConfigItem` object.
191
+
192
+ """
193
+ return self._resolve_one_item(id=id, **kwargs)
194
+
195
+ @classmethod
196
+ def normalize_id(cls, id: str | int) -> str:
197
+ """
198
+ Normalize the id string to consistently use `cls.sep`.
199
+
200
+ Args:
201
+ id: id string to be normalized.
202
+ """
203
+ return str(id).replace("#", cls.sep) # backward compatibility `#` is the old separator
204
+
205
+ @classmethod
206
+ def split_id(cls, id: str | int, last: bool = False) -> list[str]:
207
+ """
208
+ Split the id string into a list of strings by `cls.sep`.
209
+
210
+ Args:
211
+ id: id string to be split.
212
+ last: whether to split the rightmost part of the id. default is False (split all parts).
213
+ """
214
+ if not last:
215
+ return cls.normalize_id(id).split(cls.sep)
216
+ res = cls.normalize_id(id).rsplit(cls.sep, 1)
217
+ return ["".join(res[:-1]), res[-1]]
218
+
219
+ @classmethod
220
+ def iter_subconfigs(cls, id: str, config: Any) -> Iterator[tuple[str, str, Any]]:
221
+ """
222
+ Iterate over the sub-configs of the input config, the output `sub_id` uses `cls.sep` to denote substructure.
223
+
224
+ Args:
225
+ id: id string of the current input config.
226
+ config: input config to be iterated.
227
+ """
228
+ for k, v in config.items() if isinstance(config, dict) else enumerate(config):
229
+ sub_id = f"{id}{cls.sep}{k}" if id != "" else f"{k}"
230
+ yield k, sub_id, v
231
+
232
+ @classmethod
233
+ def match_refs_pattern(cls, value: str) -> dict[str, int]:
234
+ """
235
+ Match regular expression for the input string to find the references.
236
+ The reference string starts with ``"@"``, like: ``"@XXX::YYY::ZZZ"``.
237
+
238
+ Args:
239
+ value: input value to match regular expression.
240
+
241
+ """
242
+ refs: dict[str, int] = {}
243
+ # regular expression pattern to match "@XXX" or "@XXX::YYY"
244
+ value = cls.normalize_id(value)
245
+ result = cls.id_matcher.findall(value)
246
+ value_is_expr = ConfigExpression.is_expression(value)
247
+ for item in result:
248
+ if value_is_expr or value == item:
249
+ # only check when string starts with "$" or the whole content is "@XXX"
250
+ id = item[len(cls.ref) :]
251
+ refs[id] = refs.get(id, 0) + 1
252
+ return refs
253
+
254
+ @classmethod
255
+ def update_refs_pattern(cls, value: str, refs: dict) -> str:
256
+ """
257
+ Match regular expression for the input string to update content with the references.
258
+ The reference part starts with ``"@"``, like: ``"@XXX::YYY::ZZZ"``.
259
+ References dictionary must contain the referring IDs as keys.
260
+
261
+ Args:
262
+ value: input value to match regular expression.
263
+ refs: all the referring components with ids as keys, default to `None`.
264
+
265
+ """
266
+ # regular expression pattern to match "@XXX" or "@XXX::YYY"
267
+ value = cls.normalize_id(value)
268
+ result = cls.id_matcher.findall(value)
269
+ # reversely sort the matched references by length
270
+ # and handle the longer first in case a reference item is substring of another longer item
271
+ result.sort(key=len, reverse=True)
272
+ value_is_expr = ConfigExpression.is_expression(value)
273
+ for item in result:
274
+ # only update reference when string starts with "$" or the whole content is "@XXX"
275
+ if value_is_expr or value == item:
276
+ ref_id = item[len(cls.ref) :] # remove the ref prefix "@"
277
+ if ref_id not in refs:
278
+ msg = f"can not find expected ID '{ref_id}' in the references."
279
+ if not cls.allow_missing_reference:
280
+ raise KeyError(msg)
281
+ warnings.warn(msg)
282
+ continue
283
+ if value_is_expr:
284
+ # replace with local code, `{"__local_refs": self.resolved_content}` will be added to
285
+ # the `globals` argument of python `eval` in the `evaluate`
286
+ value = value.replace(item, f"{cls._vars}['{ref_id}']")
287
+ elif value == item:
288
+ # the whole content is "@XXX", it will avoid the case that regular string contains "@"
289
+ value = refs[ref_id]
290
+ return value
291
+
292
+ @classmethod
293
+ def find_refs_in_config(cls, config: Any, id: str, refs: dict[str, int] | None = None) -> dict[str, int]:
294
+ """
295
+ Recursively search all the content of input config item to get the ids of references.
296
+ References mean: the IDs of other config items (``"@XXX"`` in this config item), or the
297
+ sub-item in the config is `instantiable`, or the sub-item in the config is `expression`.
298
+ For `dict` and `list`, recursively check the sub-items.
299
+
300
+ Args:
301
+ config: input config content to search.
302
+ id: ID name for the input config item.
303
+ refs: dict of the ID name and count of found references, default to `None`.
304
+
305
+ """
306
+ refs_: dict[str, int] = refs or {}
307
+ if isinstance(config, str):
308
+ for id, count in cls.match_refs_pattern(value=config).items(): # ref count is not currently used
309
+ refs_[id] = refs_.get(id, 0) + count
310
+ if not isinstance(config, (list, dict)):
311
+ return refs_
312
+ for _, sub_id, v in cls.iter_subconfigs(id, config):
313
+ if ConfigComponent.is_instantiable(v) or ConfigExpression.is_expression(v) and sub_id not in refs_:
314
+ refs_[sub_id] = 1
315
+ refs_ = cls.find_refs_in_config(v, sub_id, refs_)
316
+ return refs_
317
+
318
+ @classmethod
319
+ def update_config_with_refs(cls, config: Any, id: str, refs: dict | None = None) -> Any:
320
+ """
321
+ With all the references in ``refs``, update the input config content with references
322
+ and return the new config.
323
+
324
+ Args:
325
+ config: input config content to update.
326
+ id: ID name for the input config.
327
+ refs: all the referring content with ids, default to `None`.
328
+
329
+ """
330
+ refs_: dict = refs or {}
331
+ if isinstance(config, str):
332
+ return cls.update_refs_pattern(config, refs_)
333
+ if not isinstance(config, (list, dict)):
334
+ return config
335
+ ret = type(config)()
336
+ for idx, sub_id, v in cls.iter_subconfigs(id, config):
337
+ if ConfigComponent.is_instantiable(v) or ConfigExpression.is_expression(v):
338
+ updated = refs_[sub_id]
339
+ if ConfigComponent.is_instantiable(v) and updated is None:
340
+ # the component is disabled
341
+ continue
342
+ else:
343
+ updated = cls.update_config_with_refs(v, sub_id, refs_)
344
+ ret.update({idx: updated}) if isinstance(ret, dict) else ret.append(updated)
345
+ return ret
source_code/SegMamba/monai/bundle/scripts.py ADDED
@@ -0,0 +1,1806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import json
16
+ import os
17
+ import re
18
+ import warnings
19
+ from collections.abc import Mapping, Sequence
20
+ from pathlib import Path
21
+ from pydoc import locate
22
+ from shutil import copyfile
23
+ from textwrap import dedent
24
+ from typing import Any, Callable
25
+
26
+ import torch
27
+ from torch.cuda import is_available
28
+
29
+ from monai.apps.mmars.mmars import _get_all_ngc_models
30
+ from monai.apps.utils import _basename, download_url, extractall, get_logger
31
+ from monai.bundle.config_item import ConfigComponent
32
+ from monai.bundle.config_parser import ConfigParser
33
+ from monai.bundle.utils import DEFAULT_INFERENCE, DEFAULT_METADATA
34
+ from monai.bundle.workflows import BundleWorkflow, ConfigWorkflow
35
+ from monai.config import IgniteInfo, PathLike
36
+ from monai.data import load_net_with_metadata, save_net_with_metadata
37
+ from monai.networks import (
38
+ convert_to_onnx,
39
+ convert_to_torchscript,
40
+ convert_to_trt,
41
+ copy_model_state,
42
+ get_state_dict,
43
+ save_state,
44
+ )
45
+ from monai.utils import (
46
+ check_parent_dir,
47
+ deprecated_arg,
48
+ ensure_tuple,
49
+ get_equivalent_dtype,
50
+ min_version,
51
+ optional_import,
52
+ pprint_edges,
53
+ )
54
+
55
+ validate, _ = optional_import("jsonschema", name="validate")
56
+ ValidationError, _ = optional_import("jsonschema.exceptions", name="ValidationError")
57
+ Checkpoint, has_ignite = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Checkpoint")
58
+ requests_get, has_requests = optional_import("requests", name="get")
59
+ onnx, _ = optional_import("onnx")
60
+ huggingface_hub, _ = optional_import("huggingface_hub")
61
+
62
+ logger = get_logger(module_name=__name__)
63
+
64
+ # set BUNDLE_DOWNLOAD_SRC="ngc" to use NGC source in default for bundle download
65
+ # set BUNDLE_DOWNLOAD_SRC="github" to use github source in default for bundle download
66
+ DEFAULT_DOWNLOAD_SOURCE = os.environ.get("BUNDLE_DOWNLOAD_SRC", "monaihosting")
67
+ PPRINT_CONFIG_N = 5
68
+
69
+
70
+ def update_kwargs(args: str | dict | None = None, ignore_none: bool = True, **kwargs: Any) -> dict:
71
+ """
72
+ Update the `args` dictionary with the input `kwargs`.
73
+ For dict data, recursively update the content based on the keys.
74
+
75
+ Example::
76
+
77
+ from monai.bundle import update_kwargs
78
+ update_kwargs({'exist': 1}, exist=2, new_arg=3)
79
+ # return {'exist': 2, 'new_arg': 3}
80
+
81
+ Args:
82
+ args: source `args` dictionary (or a json/yaml filename to read as dictionary) to update.
83
+ ignore_none: whether to ignore input args with None value, default to `True`.
84
+ kwargs: key=value pairs to be merged into `args`.
85
+
86
+ """
87
+ args_: dict = args if isinstance(args, dict) else {}
88
+ if isinstance(args, str):
89
+ # args are defined in a structured file
90
+ args_ = ConfigParser.load_config_file(args)
91
+ if isinstance(args, (tuple, list)) and all(isinstance(x, str) for x in args):
92
+ primary, overrides = args
93
+ args_ = update_kwargs(primary, ignore_none, **update_kwargs(overrides, ignore_none, **kwargs))
94
+ if not isinstance(args_, dict):
95
+ return args_
96
+ # recursively update the default args with new args
97
+ for k, v in kwargs.items():
98
+ if ignore_none and v is None:
99
+ continue
100
+ if isinstance(v, dict) and isinstance(args_.get(k), dict):
101
+ args_[k] = update_kwargs(args_[k], ignore_none, **v)
102
+ else:
103
+ args_[k] = v
104
+ return args_
105
+
106
+
107
+ _update_args = update_kwargs # backward compatibility
108
+
109
+
110
+ def _pop_args(src: dict, *args: Any, **kwargs: Any) -> tuple:
111
+ """
112
+ Pop args from the `src` dictionary based on specified keys in `args` and (key, default value) pairs in `kwargs`.
113
+
114
+ """
115
+ return tuple([src.pop(i) for i in args] + [src.pop(k, v) for k, v in kwargs.items()])
116
+
117
+
118
+ def _log_input_summary(tag: str, args: dict) -> None:
119
+ logger.info(f"--- input summary of monai.bundle.scripts.{tag} ---")
120
+ for name, val in args.items():
121
+ logger.info(f"> {name}: {pprint_edges(val, PPRINT_CONFIG_N)}")
122
+ logger.info("---\n\n")
123
+
124
+
125
+ def _get_var_names(expr: str) -> list[str]:
126
+ """
127
+ Parse the expression and discover what variables are present in it based on ast module.
128
+
129
+ Args:
130
+ expr: source expression to parse.
131
+
132
+ """
133
+ tree = ast.parse(expr)
134
+ return [m.id for m in ast.walk(tree) if isinstance(m, ast.Name)]
135
+
136
+
137
+ def _get_fake_spatial_shape(shape: Sequence[str | int], p: int = 1, n: int = 1, any: int = 1) -> tuple:
138
+ """
139
+ Get spatial shape for fake data according to the specified shape pattern.
140
+ It supports `int` number and `string` with formats like: "32", "32 * n", "32 ** p", "32 ** p *n".
141
+
142
+ Args:
143
+ shape: specified pattern for the spatial shape.
144
+ p: power factor to generate fake data shape if dim of expected shape is "x**p", default to 1.
145
+ p: multiply factor to generate fake data shape if dim of expected shape is "x*n", default to 1.
146
+ any: specified size to generate fake data shape if dim of expected shape is "*", default to 1.
147
+
148
+ """
149
+ ret = []
150
+ for i in shape:
151
+ if isinstance(i, int):
152
+ ret.append(i)
153
+ elif isinstance(i, str):
154
+ if i == "*":
155
+ ret.append(any)
156
+ else:
157
+ for c in _get_var_names(i):
158
+ if c not in ["p", "n"]:
159
+ raise ValueError(f"only support variables 'p' and 'n' so far, but got: {c}.")
160
+ ret.append(eval(i, {"p": p, "n": n}))
161
+ else:
162
+ raise ValueError(f"spatial shape items must be int or string, but got: {type(i)} {i}.")
163
+ return tuple(ret)
164
+
165
+
166
+ def _get_git_release_url(repo_owner: str, repo_name: str, tag_name: str, filename: str) -> str:
167
+ return f"https://github.com/{repo_owner}/{repo_name}/releases/download/{tag_name}/{filename}"
168
+
169
+
170
+ def _get_ngc_bundle_url(model_name: str, version: str) -> str:
171
+ return f"https://api.ngc.nvidia.com/v2/models/nvidia/monaitoolkit/{model_name.lower()}/versions/{version}/zip"
172
+
173
+
174
+ def _get_monaihosting_bundle_url(model_name: str, version: str) -> str:
175
+ monaihosting_root_path = "https://api.ngc.nvidia.com/v2/models/nvidia/monaihosting"
176
+ return f"{monaihosting_root_path}/{model_name.lower()}/versions/{version}/files/{model_name}_v{version}.zip"
177
+
178
+
179
+ def _download_from_github(repo: str, download_path: Path, filename: str, progress: bool = True) -> None:
180
+ repo_owner, repo_name, tag_name = repo.split("/")
181
+ if ".zip" not in filename:
182
+ filename += ".zip"
183
+ url = _get_git_release_url(repo_owner, repo_name, tag_name=tag_name, filename=filename)
184
+ filepath = download_path / f"{filename}"
185
+ download_url(url=url, filepath=filepath, hash_val=None, progress=progress)
186
+ extractall(filepath=filepath, output_dir=download_path, has_base=True)
187
+
188
+
189
+ def _download_from_monaihosting(download_path: Path, filename: str, version: str, progress: bool) -> None:
190
+ url = _get_monaihosting_bundle_url(model_name=filename, version=version)
191
+ filepath = download_path / f"{filename}_v{version}.zip"
192
+ download_url(url=url, filepath=filepath, hash_val=None, progress=progress)
193
+ extractall(filepath=filepath, output_dir=download_path, has_base=True)
194
+
195
+
196
+ def _add_ngc_prefix(name: str, prefix: str = "monai_") -> str:
197
+ if name.startswith(prefix):
198
+ return name
199
+ return f"{prefix}{name}"
200
+
201
+
202
+ def _remove_ngc_prefix(name: str, prefix: str = "monai_") -> str:
203
+ if name.startswith(prefix):
204
+ return name[len(prefix) :]
205
+ return name
206
+
207
+
208
+ def _download_from_ngc(
209
+ download_path: Path, filename: str, version: str, remove_prefix: str | None, progress: bool
210
+ ) -> None:
211
+ # ensure prefix is contained
212
+ filename = _add_ngc_prefix(filename)
213
+ url = _get_ngc_bundle_url(model_name=filename, version=version)
214
+ filepath = download_path / f"{filename}_v{version}.zip"
215
+ if remove_prefix:
216
+ filename = _remove_ngc_prefix(filename, prefix=remove_prefix)
217
+ extract_path = download_path / f"{filename}"
218
+ download_url(url=url, filepath=filepath, hash_val=None, progress=progress)
219
+ extractall(filepath=filepath, output_dir=extract_path, has_base=True)
220
+
221
+
222
+ def _get_latest_bundle_version_monaihosting(name):
223
+ url = "https://api.ngc.nvidia.com/v2/models/nvidia/monaihosting"
224
+ full_url = f"{url}/{name.lower()}"
225
+ requests_get, has_requests = optional_import("requests", name="get")
226
+ if has_requests:
227
+ resp = requests_get(full_url)
228
+ resp.raise_for_status()
229
+ else:
230
+ raise ValueError("NGC API requires requests package. Please install it.")
231
+ model_info = json.loads(resp.text)
232
+ return model_info["model"]["latestVersionIdStr"]
233
+
234
+
235
+ def _get_latest_bundle_version(source: str, name: str, repo: str) -> dict[str, list[str] | str] | Any | None:
236
+ if source == "ngc":
237
+ name = _add_ngc_prefix(name)
238
+ model_dict = _get_all_ngc_models(name)
239
+ for v in model_dict.values():
240
+ if v["name"] == name:
241
+ return v["latest"]
242
+ return None
243
+ elif source == "monaihosting":
244
+ return _get_latest_bundle_version_monaihosting(name)
245
+ elif source == "github":
246
+ repo_owner, repo_name, tag_name = repo.split("/")
247
+ return get_bundle_versions(name, repo=f"{repo_owner}/{repo_name}", tag=tag_name)["latest_version"]
248
+ elif source == "huggingface_hub":
249
+ refs = huggingface_hub.list_repo_refs(repo_id=repo)
250
+ if len(refs.tags) > 0:
251
+ all_versions = [t.name for t in refs.tags] # git tags, not to be confused with `tag`
252
+ latest_version = ["latest_version" if "latest_version" in all_versions else all_versions[-1]][0]
253
+ else:
254
+ latest_version = [b.name for b in refs.branches][0] # use the branch that was last updated
255
+ return latest_version
256
+ else:
257
+ raise ValueError(
258
+ f"To get the latest bundle version, source should be 'github', 'monaihosting' or 'ngc', got {source}."
259
+ )
260
+
261
+
262
+ def _process_bundle_dir(bundle_dir: PathLike | None = None) -> Path:
263
+ if bundle_dir is None:
264
+ get_dir, has_home = optional_import("torch.hub", name="get_dir")
265
+ if has_home:
266
+ bundle_dir = Path(get_dir()) / "bundle"
267
+ else:
268
+ raise ValueError("bundle_dir=None, but no suitable default directory computed. Upgrade Pytorch to 1.6+ ?")
269
+ return Path(bundle_dir)
270
+
271
+
272
+ def download(
273
+ name: str | None = None,
274
+ version: str | None = None,
275
+ bundle_dir: PathLike | None = None,
276
+ source: str = DEFAULT_DOWNLOAD_SOURCE,
277
+ repo: str | None = None,
278
+ url: str | None = None,
279
+ remove_prefix: str | None = "monai_",
280
+ progress: bool = True,
281
+ args_file: str | None = None,
282
+ ) -> None:
283
+ """
284
+ download bundle from the specified source or url. The bundle should be a zip file and it
285
+ will be extracted after downloading.
286
+ This function refers to:
287
+ https://pytorch.org/docs/stable/_modules/torch/hub.html
288
+
289
+ Typical usage examples:
290
+
291
+ .. code-block:: bash
292
+
293
+ # Execute this module as a CLI entry, and download bundle from the model-zoo repo:
294
+ python -m monai.bundle download --name <bundle_name> --version "0.1.0" --bundle_dir "./"
295
+
296
+ # Execute this module as a CLI entry, and download bundle from specified github repo:
297
+ python -m monai.bundle download --name <bundle_name> --source "github" --repo "repo_owner/repo_name/release_tag"
298
+
299
+ # Execute this module as a CLI entry, and download bundle from ngc with latest version:
300
+ python -m monai.bundle download --name <bundle_name> --source "ngc" --bundle_dir "./"
301
+
302
+ # Execute this module as a CLI entry, and download bundle from monaihosting with latest version:
303
+ python -m monai.bundle download --name <bundle_name> --source "monaihosting" --bundle_dir "./"
304
+
305
+ # Execute this module as a CLI entry, and download bundle from Hugging Face Hub:
306
+ python -m monai.bundle download --name "bundle_name" --source "huggingface_hub" --repo "repo_owner/repo_name"
307
+
308
+ # Execute this module as a CLI entry, and download bundle via URL:
309
+ python -m monai.bundle download --name <bundle_name> --url <url>
310
+
311
+ # Set default args of `run` in a JSON / YAML file, help to record and simplify the command line.
312
+ # Other args still can override the default args at runtime.
313
+ # The content of the JSON / YAML file is a dictionary. For example:
314
+ # {"name": "spleen", "bundle_dir": "download", "source": ""}
315
+ # then do the following command for downloading:
316
+ python -m monai.bundle download --args_file "args.json" --source "github"
317
+
318
+ Args:
319
+ name: bundle name. If `None` and `url` is `None`, it must be provided in `args_file`.
320
+ for example:
321
+ "spleen_ct_segmentation", "prostate_mri_anatomy" in model-zoo:
322
+ https://github.com/Project-MONAI/model-zoo/releases/tag/hosting_storage_v1.
323
+ "monai_brats_mri_segmentation" in ngc:
324
+ https://catalog.ngc.nvidia.com/models?filters=&orderBy=scoreDESC&query=monai.
325
+ version: version name of the target bundle to download, like: "0.1.0". If `None`, will download
326
+ the latest version (or the last commit to the `main` branch in the case of Hugging Face Hub).
327
+ bundle_dir: target directory to store the downloaded data.
328
+ Default is `bundle` subfolder under `torch.hub.get_dir()`.
329
+ source: storage location name. This argument is used when `url` is `None`.
330
+ In default, the value is achieved from the environment variable BUNDLE_DOWNLOAD_SRC, and
331
+ it should be "ngc", "monaihosting", "github", or "huggingface_hub".
332
+ repo: repo name. This argument is used when `url` is `None` and `source` is "github" or "huggingface_hub".
333
+ If `source` is "github", it should be in the form of "repo_owner/repo_name/release_tag".
334
+ If `source` is "huggingface_hub", it should be in the form of "repo_owner/repo_name".
335
+ url: url to download the data. If not `None`, data will be downloaded directly
336
+ and `source` will not be checked.
337
+ If `name` is `None`, filename is determined by `monai.apps.utils._basename(url)`.
338
+ remove_prefix: This argument is used when `source` is "ngc". Currently, all ngc bundles
339
+ have the ``monai_`` prefix, which is not existing in their model zoo contrasts. In order to
340
+ maintain the consistency between these two sources, remove prefix is necessary.
341
+ Therefore, if specified, downloaded folder name will remove the prefix.
342
+ progress: whether to display a progress bar.
343
+ args_file: a JSON or YAML file to provide default values for all the args in this function.
344
+ so that the command line inputs can be simplified.
345
+
346
+ """
347
+ _args = update_kwargs(
348
+ args=args_file,
349
+ name=name,
350
+ version=version,
351
+ bundle_dir=bundle_dir,
352
+ source=source,
353
+ repo=repo,
354
+ url=url,
355
+ remove_prefix=remove_prefix,
356
+ progress=progress,
357
+ )
358
+
359
+ _log_input_summary(tag="download", args=_args)
360
+ source_, progress_, remove_prefix_, repo_, name_, version_, bundle_dir_, url_ = _pop_args(
361
+ _args, "source", "progress", remove_prefix=None, repo=None, name=None, version=None, bundle_dir=None, url=None
362
+ )
363
+
364
+ bundle_dir_ = _process_bundle_dir(bundle_dir_)
365
+ if repo_ is None:
366
+ repo_ = "Project-MONAI/model-zoo/hosting_storage_v1"
367
+ if len(repo_.split("/")) != 3 and source_ != "huggingface_hub":
368
+ raise ValueError("repo should be in the form of `repo_owner/repo_name/release_tag`.")
369
+ elif len(repo_.split("/")) != 2 and source_ == "huggingface_hub":
370
+ raise ValueError("Hugging Face Hub repo should be in the form of `repo_owner/repo_name`")
371
+ if url_ is not None:
372
+ if name_ is not None:
373
+ filepath = bundle_dir_ / f"{name_}.zip"
374
+ else:
375
+ filepath = bundle_dir_ / f"{_basename(url_)}"
376
+ download_url(url=url_, filepath=filepath, hash_val=None, progress=progress_)
377
+ extractall(filepath=filepath, output_dir=bundle_dir_, has_base=True)
378
+ else:
379
+ if name_ is None:
380
+ raise ValueError(f"To download from source: {source_}, `name` must be provided.")
381
+ if version_ is None:
382
+ version_ = _get_latest_bundle_version(source=source_, name=name_, repo=repo_)
383
+ if source_ == "github":
384
+ if version_ is not None:
385
+ name_ = "_v".join([name_, version_])
386
+ _download_from_github(repo=repo_, download_path=bundle_dir_, filename=name_, progress=progress_)
387
+ elif source_ == "monaihosting":
388
+ _download_from_monaihosting(download_path=bundle_dir_, filename=name_, version=version_, progress=progress_)
389
+ elif source_ == "ngc":
390
+ _download_from_ngc(
391
+ download_path=bundle_dir_,
392
+ filename=name_,
393
+ version=version_,
394
+ remove_prefix=remove_prefix_,
395
+ progress=progress_,
396
+ )
397
+ elif source_ == "huggingface_hub":
398
+ extract_path = os.path.join(bundle_dir_, name_)
399
+ huggingface_hub.snapshot_download(repo_id=repo_, revision=version_, local_dir=extract_path)
400
+ else:
401
+ raise NotImplementedError(
402
+ "Currently only download from `url`, source 'github', 'monaihosting', 'huggingface_hub' or 'ngc' are implemented,"
403
+ f"got source: {source_}."
404
+ )
405
+
406
+
407
+ @deprecated_arg("net_name", since="1.2", removed="1.5", msg_suffix="please use ``model`` instead.")
408
+ @deprecated_arg("net_kwargs", since="1.2", removed="1.5", msg_suffix="please use ``model`` instead.")
409
+ @deprecated_arg("return_state_dict", since="1.2", removed="1.5")
410
+ def load(
411
+ name: str,
412
+ model: torch.nn.Module | None = None,
413
+ version: str | None = None,
414
+ workflow_type: str = "train",
415
+ model_file: str | None = None,
416
+ load_ts_module: bool = False,
417
+ bundle_dir: PathLike | None = None,
418
+ source: str = DEFAULT_DOWNLOAD_SOURCE,
419
+ repo: str | None = None,
420
+ remove_prefix: str | None = "monai_",
421
+ progress: bool = True,
422
+ device: str | None = None,
423
+ key_in_ckpt: str | None = None,
424
+ config_files: Sequence[str] = (),
425
+ workflow_name: str | BundleWorkflow | None = None,
426
+ args_file: str | None = None,
427
+ copy_model_args: dict | None = None,
428
+ return_state_dict: bool = True,
429
+ net_override: dict | None = None,
430
+ net_name: str | None = None,
431
+ **net_kwargs: Any,
432
+ ) -> object | tuple[torch.nn.Module, dict, dict] | Any:
433
+ """
434
+ Load model weights or TorchScript module of a bundle.
435
+
436
+ Args:
437
+ name: bundle name. If `None` and `url` is `None`, it must be provided in `args_file`.
438
+ for example:
439
+ "spleen_ct_segmentation", "prostate_mri_anatomy" in model-zoo:
440
+ https://github.com/Project-MONAI/model-zoo/releases/tag/hosting_storage_v1.
441
+ "monai_brats_mri_segmentation" in ngc:
442
+ https://catalog.ngc.nvidia.com/models?filters=&orderBy=scoreDESC&query=monai.
443
+ "mednist_gan" in monaihosting:
444
+ https://api.ngc.nvidia.com/v2/models/nvidia/monaihosting/mednist_gan/versions/0.2.0/files/mednist_gan_v0.2.0.zip
445
+ model: a pytorch module to be updated. Default to None, using the "network_def" in the bundle.
446
+ version: version name of the target bundle to download, like: "0.1.0". If `None`, will download
447
+ the latest version. If `source` is "huggingface_hub", this argument is a Git revision id.
448
+ workflow_type: specifies the workflow type: "train" or "training" for a training workflow,
449
+ or "infer", "inference", "eval", "evaluation" for a inference workflow,
450
+ other unsupported string will raise a ValueError.
451
+ default to `train` for training workflow.
452
+ model_file: the relative path of the model weights or TorchScript module within bundle.
453
+ If `None`, "models/model.pt" or "models/model.ts" will be used.
454
+ load_ts_module: a flag to specify if loading the TorchScript module.
455
+ bundle_dir: directory the weights/TorchScript module will be loaded from.
456
+ Default is `bundle` subfolder under `torch.hub.get_dir()`.
457
+ source: storage location name. This argument is used when `model_file` is not existing locally and need to be
458
+ downloaded first.
459
+ In default, the value is achieved from the environment variable BUNDLE_DOWNLOAD_SRC, and
460
+ it should be "ngc", "monaihosting", "github", or "huggingface_hub".
461
+ repo: repo name. This argument is used when `url` is `None` and `source` is "github" or "huggingface_hub".
462
+ If `source` is "github", it should be in the form of "repo_owner/repo_name/release_tag".
463
+ If `source` is "huggingface_hub", it should be in the form of "repo_owner/repo_name".
464
+ remove_prefix: This argument is used when `source` is "ngc". Currently, all ngc bundles
465
+ have the ``monai_`` prefix, which is not existing in their model zoo contrasts. In order to
466
+ maintain the consistency between these three sources, remove prefix is necessary.
467
+ Therefore, if specified, downloaded folder name will remove the prefix.
468
+ progress: whether to display a progress bar when downloading.
469
+ device: target device of returned weights or module, if `None`, prefer to "cuda" if existing.
470
+ key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
471
+ weights. if not nested checkpoint, no need to set.
472
+ config_files: extra filenames would be loaded. The argument only works when loading a TorchScript module,
473
+ see `_extra_files` in `torch.jit.load` for more details.
474
+ workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow".
475
+ args_file: a JSON or YAML file to provide default values for all the args in "download" function.
476
+ copy_model_args: other arguments for the `monai.networks.copy_model_state` function.
477
+ return_state_dict: whether to return state dict, if True, return state_dict, else a corresponding network
478
+ from `_workflow.network_def` will be instantiated and load the achieved weights.
479
+ net_override: id-value pairs to override the parameters in the network of the bundle, default to `None`.
480
+ net_name: if not `None`, a corresponding network will be instantiated and load the achieved weights.
481
+ This argument only works when loading weights.
482
+ net_kwargs: other arguments that are used to instantiate the network class defined by `net_name`.
483
+
484
+ Returns:
485
+ 1. If `load_ts_module` is `False` and `model` is `None`,
486
+ return model weights if can't find "network_def" in the bundle,
487
+ else return an instantiated network that loaded the weights.
488
+ 2. If `load_ts_module` is `False` and `model` is not `None`,
489
+ return an instantiated network that loaded the weights.
490
+ 3. If `load_ts_module` is `True`, return a triple that include a TorchScript module,
491
+ the corresponding metadata dict, and extra files dict.
492
+ please check `monai.data.load_net_with_metadata` for more details.
493
+ 4. If `return_state_dict` is True, return model weights, only used for compatibility
494
+ when `model` and `net_name` are all `None`.
495
+
496
+ """
497
+ if return_state_dict and (model is not None or net_name is not None):
498
+ warnings.warn("Incompatible values: model and net_name are all specified, return state dict instead.")
499
+
500
+ bundle_dir_ = _process_bundle_dir(bundle_dir)
501
+ net_override = {} if net_override is None else net_override
502
+ copy_model_args = {} if copy_model_args is None else copy_model_args
503
+
504
+ if device is None:
505
+ device = "cuda:0" if is_available() else "cpu"
506
+ if model_file is None:
507
+ model_file = os.path.join("models", "model.ts" if load_ts_module is True else "model.pt")
508
+ if source == "ngc":
509
+ name = _add_ngc_prefix(name)
510
+ if remove_prefix:
511
+ name = _remove_ngc_prefix(name, prefix=remove_prefix)
512
+ full_path = os.path.join(bundle_dir_, name, model_file)
513
+ if not os.path.exists(full_path):
514
+ download(
515
+ name=name,
516
+ version=version,
517
+ bundle_dir=bundle_dir_,
518
+ source=source,
519
+ repo=repo,
520
+ remove_prefix=remove_prefix,
521
+ progress=progress,
522
+ args_file=args_file,
523
+ )
524
+
525
+ # loading with `torch.jit.load`
526
+ if load_ts_module is True:
527
+ return load_net_with_metadata(full_path, map_location=torch.device(device), more_extra_files=config_files)
528
+ # loading with `torch.load`
529
+ model_dict = torch.load(full_path, map_location=torch.device(device))
530
+
531
+ if not isinstance(model_dict, Mapping):
532
+ warnings.warn(f"the state dictionary from {full_path} should be a dictionary but got {type(model_dict)}.")
533
+ model_dict = get_state_dict(model_dict)
534
+
535
+ if return_state_dict:
536
+ return model_dict
537
+
538
+ _workflow = None
539
+ if model is None and net_name is None:
540
+ bundle_config_file = bundle_dir_ / name / "configs" / f"{workflow_type}.json"
541
+ if bundle_config_file.is_file():
542
+ _net_override = {f"network_def#{key}": value for key, value in net_override.items()}
543
+ _workflow = create_workflow(
544
+ workflow_name=workflow_name,
545
+ args_file=args_file,
546
+ config_file=str(bundle_config_file),
547
+ workflow_type=workflow_type,
548
+ **_net_override,
549
+ )
550
+ else:
551
+ warnings.warn(f"Cannot find the config file: {bundle_config_file}, return state dict instead.")
552
+ return model_dict
553
+ if _workflow is not None:
554
+ if not hasattr(_workflow, "network_def"):
555
+ warnings.warn("No available network definition in the bundle, return state dict instead.")
556
+ return model_dict
557
+ else:
558
+ model = _workflow.network_def
559
+ elif net_name is not None:
560
+ net_kwargs["_target_"] = net_name
561
+ configer = ConfigComponent(config=net_kwargs)
562
+ model = configer.instantiate() # type: ignore
563
+
564
+ model.to(device) # type: ignore
565
+
566
+ copy_model_state(
567
+ dst=model, src=model_dict if key_in_ckpt is None else model_dict[key_in_ckpt], **copy_model_args # type: ignore
568
+ )
569
+
570
+ return model
571
+
572
+
573
+ def _get_all_bundles_info(
574
+ repo: str = "Project-MONAI/model-zoo", tag: str = "dev", auth_token: str | None = None
575
+ ) -> dict[str, dict[str, dict[str, Any]]]:
576
+ if has_requests:
577
+ if tag == "hosting_storage_v1":
578
+ request_url = f"https://api.github.com/repos/{repo}/releases"
579
+ else:
580
+ request_url = f"https://raw.githubusercontent.com/{repo}/{tag}/models/model_info.json"
581
+
582
+ if auth_token is not None:
583
+ headers = {"Authorization": f"Bearer {auth_token}"}
584
+ resp = requests_get(request_url, headers=headers)
585
+ else:
586
+ resp = requests_get(request_url)
587
+ resp.raise_for_status()
588
+ else:
589
+ raise ValueError("requests package is required, please install it.")
590
+ releases_list = json.loads(resp.text)
591
+ bundle_name_pattern = re.compile(r"_v\d*.")
592
+ bundles_info: dict[str, dict[str, dict[str, Any]]] = {}
593
+
594
+ if tag == "hosting_storage_v1":
595
+ for release in releases_list:
596
+ if release["tag_name"] == tag:
597
+ for asset in release["assets"]:
598
+ asset_name = bundle_name_pattern.split(asset["name"])[0]
599
+ if asset_name not in bundles_info:
600
+ bundles_info[asset_name] = {}
601
+ asset_version = asset["name"].split(f"{asset_name}_v")[-1].replace(".zip", "")
602
+ bundles_info[asset_name][asset_version] = dict(asset)
603
+ return bundles_info
604
+ else:
605
+ for asset in releases_list.keys():
606
+ asset_name = bundle_name_pattern.split(asset)[0]
607
+ if asset_name not in bundles_info:
608
+ bundles_info[asset_name] = {}
609
+ asset_version = asset.split(f"{asset_name}_v")[-1]
610
+ bundles_info[asset_name][asset_version] = {
611
+ "name": asset,
612
+ "browser_download_url": releases_list[asset]["source"],
613
+ }
614
+ return bundles_info
615
+
616
+
617
+ def get_all_bundles_list(
618
+ repo: str = "Project-MONAI/model-zoo", tag: str = "dev", auth_token: str | None = None
619
+ ) -> list[tuple[str, str]]:
620
+ """
621
+ Get all bundles names (and the latest versions) that are stored in the release of specified repository
622
+ with the provided tag. If tag is "dev", will get model information from
623
+ https://raw.githubusercontent.com/repo_owner/repo_name/dev/models/model_info.json.
624
+ The default values of arguments correspond to the release of MONAI model zoo. In order to increase the
625
+ rate limits of calling Github APIs, you can input your personal access token.
626
+ Please check the following link for more details about rate limiting:
627
+ https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting
628
+
629
+ The following link shows how to create your personal access token:
630
+ https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
631
+
632
+ Args:
633
+ repo: it should be in the form of "repo_owner/repo_name/".
634
+ tag: the tag name of the release.
635
+ auth_token: github personal access token.
636
+
637
+ Returns:
638
+ a list of tuple in the form of (bundle name, latest version).
639
+
640
+ """
641
+
642
+ bundles_info = _get_all_bundles_info(repo=repo, tag=tag, auth_token=auth_token)
643
+ bundles_list = []
644
+ for bundle_name in bundles_info:
645
+ latest_version = sorted(bundles_info[bundle_name].keys())[-1]
646
+ bundles_list.append((bundle_name, latest_version))
647
+
648
+ return bundles_list
649
+
650
+
651
+ def get_bundle_versions(
652
+ bundle_name: str, repo: str = "Project-MONAI/model-zoo", tag: str = "dev", auth_token: str | None = None
653
+ ) -> dict[str, list[str] | str]:
654
+ """
655
+ Get the latest version, as well as all existing versions of a bundle that is stored in the release of specified
656
+ repository with the provided tag. If tag is "dev", will get model information from
657
+ https://raw.githubusercontent.com/repo_owner/repo_name/dev/models/model_info.json.
658
+ In order to increase the rate limits of calling Github APIs, you can input your personal access token.
659
+ Please check the following link for more details about rate limiting:
660
+ https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting
661
+
662
+ The following link shows how to create your personal access token:
663
+ https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
664
+
665
+ Args:
666
+ bundle_name: bundle name.
667
+ repo: it should be in the form of "repo_owner/repo_name/".
668
+ tag: the tag name of the release.
669
+ auth_token: github personal access token.
670
+
671
+ Returns:
672
+ a dictionary that contains the latest version and all versions of a bundle.
673
+
674
+ """
675
+
676
+ bundles_info = _get_all_bundles_info(repo=repo, tag=tag, auth_token=auth_token)
677
+ if bundle_name not in bundles_info:
678
+ raise ValueError(f"bundle: {bundle_name} is not existing in repo: {repo}.")
679
+ bundle_info = bundles_info[bundle_name]
680
+ all_versions = sorted(bundle_info.keys())
681
+
682
+ return {"latest_version": all_versions[-1], "all_versions": all_versions}
683
+
684
+
685
+ def get_bundle_info(
686
+ bundle_name: str,
687
+ version: str | None = None,
688
+ repo: str = "Project-MONAI/model-zoo",
689
+ tag: str = "dev",
690
+ auth_token: str | None = None,
691
+ ) -> dict[str, Any]:
692
+ """
693
+ Get all information (include "name" and "browser_download_url") of a bundle
694
+ with the specified bundle name and version which is stored in the release of specified repository with the provided tag.
695
+ In order to increase the rate limits of calling Github APIs, you can input your personal access token.
696
+ Please check the following link for more details about rate limiting:
697
+ https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting
698
+
699
+ The following link shows how to create your personal access token:
700
+ https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
701
+
702
+ Args:
703
+ bundle_name: bundle name.
704
+ version: version name of the target bundle, if None, the latest version will be used.
705
+ repo: it should be in the form of "repo_owner/repo_name/".
706
+ tag: the tag name of the release.
707
+ auth_token: github personal access token.
708
+
709
+ Returns:
710
+ a dictionary that contains the bundle's information.
711
+
712
+ """
713
+
714
+ bundles_info = _get_all_bundles_info(repo=repo, tag=tag, auth_token=auth_token)
715
+ if bundle_name not in bundles_info:
716
+ raise ValueError(f"bundle: {bundle_name} is not existing.")
717
+ bundle_info = bundles_info[bundle_name]
718
+ if version is None:
719
+ version = sorted(bundle_info.keys())[-1]
720
+ if version not in bundle_info:
721
+ raise ValueError(f"version: {version} of bundle: {bundle_name} is not existing.")
722
+
723
+ return bundle_info[version]
724
+
725
+
726
+ def run(
727
+ run_id: str | None = None,
728
+ init_id: str | None = None,
729
+ final_id: str | None = None,
730
+ meta_file: str | Sequence[str] | None = None,
731
+ config_file: str | Sequence[str] | None = None,
732
+ logging_file: str | None = None,
733
+ tracking: str | dict | None = None,
734
+ args_file: str | None = None,
735
+ **override: Any,
736
+ ) -> None:
737
+ """
738
+ Specify `config_file` to run monai bundle components and workflows.
739
+
740
+ Typical usage examples:
741
+
742
+ .. code-block:: bash
743
+
744
+ # Execute this module as a CLI entry:
745
+ python -m monai.bundle run --meta_file <meta path> --config_file <config path>
746
+
747
+ # Execute with specified `run_id=training`:
748
+ python -m monai.bundle run training --meta_file <meta path> --config_file <config path>
749
+
750
+ # Execute with all specified `run_id=runtest`, `init_id=inittest`, `final_id=finaltest`:
751
+ python -m monai.bundle run --run_id runtest --init_id inittest --final_id finaltest ...
752
+
753
+ # Override config values at runtime by specifying the component id and its new value:
754
+ python -m monai.bundle run --net#input_chns 1 ...
755
+
756
+ # Override config values with another config file `/path/to/another.json`:
757
+ python -m monai.bundle run --net %/path/to/another.json ...
758
+
759
+ # Override config values with part content of another config file:
760
+ python -m monai.bundle run --net %/data/other.json#net_arg ...
761
+
762
+ # Set default args of `run` in a JSON / YAML file, help to record and simplify the command line.
763
+ # Other args still can override the default args at runtime:
764
+ python -m monai.bundle run --args_file "/workspace/data/args.json" --config_file <config path>
765
+
766
+ Args:
767
+ run_id: ID name of the expected config expression to run, default to "run".
768
+ to run the config, the target config must contain this ID.
769
+ init_id: ID name of the expected config expression to initialize before running, default to "initialize".
770
+ it's optional for both configs and this `run` function.
771
+ final_id: ID name of the expected config expression to finalize after running, default to "finalize".
772
+ it's optional for both configs and this `run` function.
773
+ meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
774
+ Default to None.
775
+ config_file: filepath of the config file, if `None`, must be provided in `args_file`.
776
+ if it is a list of file paths, the content of them will be merged.
777
+ logging_file: config file for `logging` module in the program. for more details:
778
+ https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig.
779
+ Default to None.
780
+ tracking: if not None, enable the experiment tracking at runtime with optionally configurable and extensible.
781
+ If "mlflow", will add `MLFlowHandler` to the parsed bundle with default tracking settings where a set of
782
+ common parameters shown below will be added and can be passed through the `override` parameter of this method.
783
+
784
+ - ``"output_dir"``: the path to save mlflow tracking outputs locally, default to "<bundle root>/eval".
785
+ - ``"tracking_uri"``: uri to save mlflow tracking outputs, default to "/output_dir/mlruns".
786
+ - ``"experiment_name"``: experiment name for this run, default to "monai_experiment".
787
+ - ``"run_name"``: the name of current run.
788
+ - ``"save_execute_config"``: whether to save the executed config files. It can be `False`, `/path/to/artifacts`
789
+ or `True`. If set to `True`, will save to the default path "<bundle_root>/eval". Default to `True`.
790
+
791
+ If other string, treat it as file path to load the tracking settings.
792
+ If `dict`, treat it as tracking settings.
793
+ Will patch the target config content with `tracking handlers` and the top-level items of `configs`.
794
+ for detailed usage examples, please check the tutorial:
795
+ https://github.com/Project-MONAI/tutorials/blob/main/experiment_management/bundle_integrate_mlflow.ipynb.
796
+ args_file: a JSON or YAML file to provide default values for `run_id`, `meta_file`,
797
+ `config_file`, `logging`, and override pairs. so that the command line inputs can be simplified.
798
+ override: id-value pairs to override or add the corresponding config content.
799
+ e.g. ``--net#input_chns 42``, ``--net %/data/other.json#net_arg``.
800
+
801
+ """
802
+
803
+ workflow = create_workflow(
804
+ config_file=config_file,
805
+ args_file=args_file,
806
+ meta_file=meta_file,
807
+ logging_file=logging_file,
808
+ init_id=init_id,
809
+ run_id=run_id,
810
+ final_id=final_id,
811
+ tracking=tracking,
812
+ **override,
813
+ )
814
+ workflow.run()
815
+ workflow.finalize()
816
+
817
+
818
+ def run_workflow(
819
+ workflow_name: str | BundleWorkflow | None = None, args_file: str | None = None, **kwargs: Any
820
+ ) -> None:
821
+ """
822
+ Specify `bundle workflow` to run monai bundle components and workflows.
823
+ The workflow should be subclass of `BundleWorkflow` and be available to import.
824
+ It can be MONAI existing bundle workflows or user customized workflows.
825
+
826
+ Typical usage examples:
827
+
828
+ .. code-block:: bash
829
+
830
+ # Execute this module as a CLI entry with default ConfigWorkflow:
831
+ python -m monai.bundle run_workflow --meta_file <meta path> --config_file <config path>
832
+
833
+ # Set the workflow to other customized BundleWorkflow subclass:
834
+ python -m monai.bundle run_workflow --workflow_name CustomizedWorkflow ...
835
+
836
+ Args:
837
+ workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow".
838
+ args_file: a JSON or YAML file to provide default values for this API.
839
+ so that the command line inputs can be simplified.
840
+ kwargs: arguments to instantiate the workflow class.
841
+
842
+ """
843
+
844
+ workflow_ = create_workflow(workflow_name=workflow_name, args_file=args_file, **kwargs)
845
+ workflow_.run()
846
+ workflow_.finalize()
847
+
848
+
849
+ def verify_metadata(
850
+ meta_file: str | Sequence[str] | None = None,
851
+ filepath: PathLike | None = None,
852
+ create_dir: bool | None = None,
853
+ hash_val: str | None = None,
854
+ hash_type: str | None = None,
855
+ args_file: str | None = None,
856
+ **kwargs: Any,
857
+ ) -> None:
858
+ """
859
+ Verify the provided `metadata` file based on the predefined `schema`.
860
+ `metadata` content must contain the `schema` field for the URL of schema file to download.
861
+ The schema standard follows: http://json-schema.org/.
862
+
863
+ Args:
864
+ meta_file: filepath of the metadata file to verify, if `None`, must be provided in `args_file`.
865
+ if it is a list of file paths, the content of them will be merged.
866
+ filepath: file path to store the downloaded schema.
867
+ create_dir: whether to create directories if not existing, default to `True`.
868
+ hash_val: if not None, define the hash value to verify the downloaded schema file.
869
+ hash_type: if not None, define the hash type to verify the downloaded schema file. Defaults to "md5".
870
+ args_file: a JSON or YAML file to provide default values for all the args in this function.
871
+ so that the command line inputs can be simplified.
872
+ kwargs: other arguments for `jsonschema.validate()`. for more details:
873
+ https://python-jsonschema.readthedocs.io/en/stable/validate/#jsonschema.validate.
874
+
875
+ """
876
+
877
+ _args = update_kwargs(
878
+ args=args_file,
879
+ meta_file=meta_file,
880
+ filepath=filepath,
881
+ create_dir=create_dir,
882
+ hash_val=hash_val,
883
+ hash_type=hash_type,
884
+ **kwargs,
885
+ )
886
+ _log_input_summary(tag="verify_metadata", args=_args)
887
+ filepath_, meta_file_, create_dir_, hash_val_, hash_type_ = _pop_args(
888
+ _args, "filepath", "meta_file", create_dir=True, hash_val=None, hash_type="md5"
889
+ )
890
+
891
+ check_parent_dir(path=filepath_, create_dir=create_dir_)
892
+ metadata = ConfigParser.load_config_files(files=meta_file_)
893
+ url = metadata.get("schema")
894
+ if url is None:
895
+ raise ValueError("must provide the `schema` field in the metadata for the URL of schema file.")
896
+ download_url(url=url, filepath=filepath_, hash_val=hash_val_, hash_type=hash_type_, progress=True)
897
+ schema = ConfigParser.load_config_file(filepath=filepath_)
898
+
899
+ try:
900
+ # the rest key-values in the _args are for `validate` API
901
+ validate(instance=metadata, schema=schema, **_args)
902
+ except ValidationError as e: # pylint: disable=E0712
903
+ # as the error message is very long, only extract the key information
904
+ raise ValueError(
905
+ re.compile(r".*Failed validating", re.S).findall(str(e))[0] + f" against schema `{url}`."
906
+ ) from e
907
+ logger.info("metadata is verified with no error.")
908
+
909
+
910
+ def _get_net_io_info(parser: ConfigParser | None = None, prefix: str = "_meta_#network_data_format") -> tuple:
911
+ """
912
+ Get the input and output information defined in the metadata.
913
+
914
+ Args:
915
+ parser: a ConfigParser of the given bundle.
916
+ prefix: a prefix for the input and output ID, which will be combined as `prefix#inputs` and
917
+ `prefix#outputs` to parse the input and output information in the `metadata.json` file of
918
+ a bundle, default to `meta_#network_data_format`.
919
+
920
+ Returns:
921
+ input_channels: the channel number of the `image` input.
922
+ input_spatial_shape: the spatial shape of the `image` input.
923
+ input_dtype: the data type of the `image` input.
924
+ output_channels: the channel number of the output.
925
+ output_dtype: the data type of the output.
926
+ """
927
+ if not isinstance(parser, ConfigParser):
928
+ raise AttributeError(f"Parameter parser should be a ConfigParser, got {type(parser)}.")
929
+
930
+ prefix_key = f"{prefix}#inputs"
931
+ key = f"{prefix_key}#image#num_channels"
932
+ input_channels = parser.get(key)
933
+ key = f"{prefix_key}#image#spatial_shape"
934
+ input_spatial_shape = tuple(parser.get(key))
935
+ key = f"{prefix_key}#image#dtype"
936
+ input_dtype = get_equivalent_dtype(parser.get(key), torch.Tensor)
937
+
938
+ prefix_key = f"{prefix}#outputs"
939
+ key = f"{prefix_key}#pred#num_channels"
940
+ output_channels = parser.get(key)
941
+ key = f"{prefix_key}#pred#dtype"
942
+ output_dtype = get_equivalent_dtype(parser.get(key), torch.Tensor)
943
+
944
+ return input_channels, input_spatial_shape, input_dtype, output_channels, output_dtype
945
+
946
+
947
+ def _get_fake_input_shape(parser: ConfigParser) -> tuple:
948
+ """
949
+ 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.
950
+
951
+ Args:
952
+ parser: a ConfigParser which contains the i/o information of a bundle.
953
+ """
954
+ input_channels, input_spatial_shape, _, _, _ = _get_net_io_info(parser=parser)
955
+ spatial_shape = _get_fake_spatial_shape(input_spatial_shape)
956
+ input_shape = (1, input_channels, *spatial_shape)
957
+ return input_shape
958
+
959
+
960
+ def verify_net_in_out(
961
+ net_id: str | None = None,
962
+ meta_file: str | Sequence[str] | None = None,
963
+ config_file: str | Sequence[str] | None = None,
964
+ device: str | None = None,
965
+ p: int | None = None,
966
+ n: int | None = None,
967
+ any: int | None = None,
968
+ extra_forward_args: dict | None = None,
969
+ args_file: str | None = None,
970
+ **override: Any,
971
+ ) -> None:
972
+ """
973
+ Verify the input and output data shape and data type of network defined in the metadata.
974
+ Will test with fake Tensor data according to the required data shape in `metadata`.
975
+
976
+ Typical usage examples:
977
+
978
+ .. code-block:: bash
979
+
980
+ python -m monai.bundle verify_net_in_out network --meta_file <meta path> --config_file <config path>
981
+
982
+ Args:
983
+ net_id: ID name of the network component to verify, it must be `torch.nn.Module`.
984
+ meta_file: filepath of the metadata file to get network args, if `None`, must be provided in `args_file`.
985
+ if it is a list of file paths, the content of them will be merged.
986
+ config_file: filepath of the config file to get network definition, if `None`, must be provided in `args_file`.
987
+ if it is a list of file paths, the content of them will be merged.
988
+ device: target device to run the network forward computation, if None, prefer to "cuda" if existing.
989
+ p: power factor to generate fake data shape if dim of expected shape is "x**p", default to 1.
990
+ n: multiply factor to generate fake data shape if dim of expected shape is "x*n", default to 1.
991
+ any: specified size to generate fake data shape if dim of expected shape is "*", default to 1.
992
+ extra_forward_args: a dictionary that contains other args for the forward function of the network.
993
+ Default to an empty dictionary.
994
+ args_file: a JSON or YAML file to provide default values for `net_id`, `meta_file`, `config_file`,
995
+ `device`, `p`, `n`, `any`, and override pairs. so that the command line inputs can be simplified.
996
+ override: id-value pairs to override or add the corresponding config content.
997
+ e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.
998
+
999
+ """
1000
+
1001
+ _args = update_kwargs(
1002
+ args=args_file,
1003
+ net_id=net_id,
1004
+ meta_file=meta_file,
1005
+ config_file=config_file,
1006
+ device=device,
1007
+ p=p,
1008
+ n=n,
1009
+ any=any,
1010
+ extra_forward_args=extra_forward_args,
1011
+ **override,
1012
+ )
1013
+ _log_input_summary(tag="verify_net_in_out", args=_args)
1014
+ config_file_, meta_file_, net_id_, device_, p_, n_, any_, extra_forward_args_ = _pop_args(
1015
+ _args,
1016
+ "config_file",
1017
+ "meta_file",
1018
+ net_id="",
1019
+ device="cuda:0" if is_available() else "cpu",
1020
+ p=1,
1021
+ n=1,
1022
+ any=1,
1023
+ extra_forward_args={},
1024
+ )
1025
+
1026
+ parser = ConfigParser()
1027
+ parser.read_config(f=config_file_)
1028
+ parser.read_meta(f=meta_file_)
1029
+
1030
+ # the rest key-values in the _args are to override config content
1031
+ for k, v in _args.items():
1032
+ parser[k] = v
1033
+
1034
+ input_channels, input_spatial_shape, input_dtype, output_channels, output_dtype = _get_net_io_info(parser=parser)
1035
+ try:
1036
+ key: str = net_id_ # mark the full id when KeyError
1037
+ net = parser.get_parsed_content(key).to(device_)
1038
+ except KeyError as e:
1039
+ raise KeyError(f"Failed to verify due to missing expected key in the config: {key}.") from e
1040
+
1041
+ net.eval()
1042
+ with torch.no_grad():
1043
+ spatial_shape = _get_fake_spatial_shape(input_spatial_shape, p=p_, n=n_, any=any_)
1044
+ test_data = torch.rand(*(1, input_channels, *spatial_shape), dtype=input_dtype, device=device_)
1045
+ if input_dtype == torch.float16:
1046
+ # fp16 can only be executed in gpu mode
1047
+ net.to("cuda")
1048
+ from torch.cuda.amp import autocast
1049
+
1050
+ with autocast():
1051
+ output = net(test_data.cuda(), **extra_forward_args_)
1052
+ net.to(device_)
1053
+ else:
1054
+ output = net(test_data, **extra_forward_args_)
1055
+ if output.shape[1] != output_channels:
1056
+ raise ValueError(f"output channel number `{output.shape[1]}` doesn't match: `{output_channels}`.")
1057
+ if output.dtype != output_dtype:
1058
+ raise ValueError(f"dtype of output data `{output.dtype}` doesn't match: {output_dtype}.")
1059
+ logger.info("data shape of network is verified with no error.")
1060
+
1061
+
1062
+ def _export(
1063
+ converter: Callable,
1064
+ parser: ConfigParser,
1065
+ net_id: str,
1066
+ filepath: str,
1067
+ ckpt_file: str,
1068
+ config_file: str,
1069
+ key_in_ckpt: str,
1070
+ **kwargs: Any,
1071
+ ) -> None:
1072
+ """
1073
+ Export a model defined in the parser to a new one specified by the converter.
1074
+
1075
+ Args:
1076
+ converter: a callable object that takes a torch.nn.module and kwargs as input and
1077
+ converts the module to another type.
1078
+ parser: a ConfigParser of the bundle to be converted.
1079
+ net_id: ID name of the network component in the parser, it must be `torch.nn.Module`.
1080
+ filepath: filepath to export, if filename has no extension, it becomes `.ts`.
1081
+ ckpt_file: filepath of the model checkpoint to load.
1082
+ config_file: filepath of the config file to save in the converted model,the saved key in the converted
1083
+ model is the config filename without extension, and the saved config value is always serialized in
1084
+ JSON format no matter the original file format is JSON or YAML. it can be a single file or a list
1085
+ of files.
1086
+ key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
1087
+ weights. if not nested checkpoint, no need to set.
1088
+ kwargs: key arguments for the converter.
1089
+
1090
+ """
1091
+ net = parser.get_parsed_content(net_id)
1092
+ if has_ignite:
1093
+ # here we use ignite Checkpoint to support nested weights and be compatible with MONAI CheckpointSaver
1094
+ Checkpoint.load_objects(to_load={key_in_ckpt: net}, checkpoint=ckpt_file)
1095
+ else:
1096
+ ckpt = torch.load(ckpt_file)
1097
+ copy_model_state(dst=net, src=ckpt if key_in_ckpt == "" else ckpt[key_in_ckpt])
1098
+
1099
+ # Use the given converter to convert a model and save with metadata, config content
1100
+ net = converter(model=net, **kwargs)
1101
+
1102
+ extra_files: dict = {}
1103
+ for i in ensure_tuple(config_file):
1104
+ # split the filename and directory
1105
+ filename = os.path.basename(i)
1106
+ # remove extension
1107
+ filename, _ = os.path.splitext(filename)
1108
+ # because all files are stored as JSON their name parts without extension must be unique
1109
+ if filename in extra_files:
1110
+ raise ValueError(f"Filename part '{filename}' is given multiple times in config file list.")
1111
+ # the file may be JSON or YAML but will get loaded and dumped out again as JSON
1112
+ extra_files[filename] = json.dumps(ConfigParser.load_config_file(i)).encode()
1113
+
1114
+ # add .json extension to all extra files which are always encoded as JSON
1115
+ extra_files = {k + ".json": v for k, v in extra_files.items()}
1116
+
1117
+ save_net_with_metadata(
1118
+ jit_obj=net,
1119
+ filename_prefix_or_stream=filepath,
1120
+ include_config_vals=False,
1121
+ append_timestamp=False,
1122
+ meta_values=parser.get().pop("_meta_", None),
1123
+ more_extra_files=extra_files,
1124
+ )
1125
+ logger.info(f"exported to file: {filepath}.")
1126
+
1127
+
1128
+ def onnx_export(
1129
+ net_id: str | None = None,
1130
+ filepath: PathLike | None = None,
1131
+ ckpt_file: str | None = None,
1132
+ meta_file: str | Sequence[str] | None = None,
1133
+ config_file: str | Sequence[str] | None = None,
1134
+ key_in_ckpt: str | None = None,
1135
+ use_trace: bool | None = None,
1136
+ input_shape: Sequence[int] | None = None,
1137
+ args_file: str | None = None,
1138
+ converter_kwargs: Mapping | None = None,
1139
+ **override: Any,
1140
+ ) -> None:
1141
+ """
1142
+ Export the model checkpoint to an onnx model.
1143
+
1144
+ Typical usage examples:
1145
+
1146
+ .. code-block:: bash
1147
+
1148
+ python -m monai.bundle onnx_export network --filepath <export path> --ckpt_file <checkpoint path> ...
1149
+
1150
+ Args:
1151
+ net_id: ID name of the network component in the config, it must be `torch.nn.Module`.
1152
+ filepath: filepath where the onnx model is saved to.
1153
+ ckpt_file: filepath of the model checkpoint to load.
1154
+ meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
1155
+ config_file: filepath of the config file that contains extract network information,
1156
+ key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
1157
+ weights. if not nested checkpoint, no need to set.
1158
+ use_trace: whether using `torch.jit.trace` to convert the pytorch model to torchscript model.
1159
+ input_shape: a shape used to generate the random input of the network, when converting the model to an
1160
+ 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
1161
+ the `metadata` config.
1162
+ args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that
1163
+ the command line inputs can be simplified.
1164
+ converter_kwargs: extra arguments that are needed by `convert_to_onnx`, except ones that already exist in the
1165
+ input parameters.
1166
+ override: id-value pairs to override or add the corresponding config content.
1167
+ e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.
1168
+
1169
+ """
1170
+ _args = update_kwargs(
1171
+ args=args_file,
1172
+ net_id=net_id,
1173
+ filepath=filepath,
1174
+ meta_file=meta_file,
1175
+ config_file=config_file,
1176
+ ckpt_file=ckpt_file,
1177
+ key_in_ckpt=key_in_ckpt,
1178
+ use_trace=use_trace,
1179
+ input_shape=input_shape,
1180
+ converter_kwargs=converter_kwargs,
1181
+ **override,
1182
+ )
1183
+ _log_input_summary(tag="onnx_export", args=_args)
1184
+ (
1185
+ filepath_,
1186
+ ckpt_file_,
1187
+ config_file_,
1188
+ net_id_,
1189
+ meta_file_,
1190
+ key_in_ckpt_,
1191
+ use_trace_,
1192
+ input_shape_,
1193
+ converter_kwargs_,
1194
+ ) = _pop_args(
1195
+ _args,
1196
+ "filepath",
1197
+ "ckpt_file",
1198
+ "config_file",
1199
+ net_id="",
1200
+ meta_file=None,
1201
+ key_in_ckpt="",
1202
+ use_trace=False,
1203
+ input_shape=None,
1204
+ converter_kwargs={},
1205
+ )
1206
+
1207
+ parser = ConfigParser()
1208
+
1209
+ parser.read_config(f=config_file_)
1210
+ if meta_file_ is not None:
1211
+ parser.read_meta(f=meta_file_)
1212
+
1213
+ # the rest key-values in the _args are to override config content
1214
+ for k, v in _args.items():
1215
+ parser[k] = v
1216
+
1217
+ # The convert_to_onnx must have an `inputs` as input, no matter what the `use_trace` is.
1218
+ # If the `input_shape` is not provided, will try to parse it from the parser to generate a random `inputs`.
1219
+ if not input_shape_:
1220
+ input_shape_ = _get_fake_input_shape(parser=parser)
1221
+
1222
+ inputs_ = [torch.rand(input_shape_)]
1223
+ net = parser.get_parsed_content(net_id_)
1224
+ if has_ignite:
1225
+ # here we use ignite Checkpoint to support nested weights and be compatible with MONAI CheckpointSaver
1226
+ Checkpoint.load_objects(to_load={key_in_ckpt_: net}, checkpoint=ckpt_file_)
1227
+ else:
1228
+ ckpt = torch.load(ckpt_file_)
1229
+ copy_model_state(dst=net, src=ckpt if key_in_ckpt_ == "" else ckpt[key_in_ckpt_])
1230
+
1231
+ converter_kwargs_.update({"inputs": inputs_, "use_trace": use_trace_})
1232
+ onnx_model = convert_to_onnx(model=net, **converter_kwargs_)
1233
+ onnx.save(onnx_model, filepath_)
1234
+
1235
+
1236
+ def ckpt_export(
1237
+ net_id: str | None = None,
1238
+ filepath: PathLike | None = None,
1239
+ ckpt_file: str | None = None,
1240
+ meta_file: str | Sequence[str] | None = None,
1241
+ config_file: str | Sequence[str] | None = None,
1242
+ key_in_ckpt: str | None = None,
1243
+ use_trace: bool | None = None,
1244
+ input_shape: Sequence[int] | None = None,
1245
+ args_file: str | None = None,
1246
+ converter_kwargs: Mapping | None = None,
1247
+ **override: Any,
1248
+ ) -> None:
1249
+ """
1250
+ Export the model checkpoint to the given filepath with metadata and config included as JSON files.
1251
+
1252
+ Typical usage examples:
1253
+
1254
+ .. code-block:: bash
1255
+
1256
+ python -m monai.bundle ckpt_export network --filepath <export path> --ckpt_file <checkpoint path> ...
1257
+
1258
+ Args:
1259
+ net_id: ID name of the network component in the config, it must be `torch.nn.Module`.
1260
+ Default to "network_def".
1261
+ filepath: filepath to export, if filename has no extension it becomes `.ts`.
1262
+ Default to "models/model.ts" under "os.getcwd()" if `bundle_root` is not specified.
1263
+ ckpt_file: filepath of the model checkpoint to load.
1264
+ Default to "models/model.pt" under "os.getcwd()" if `bundle_root` is not specified.
1265
+ meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
1266
+ Default to "configs/metadata.json" under "os.getcwd()" if `bundle_root` is not specified.
1267
+ config_file: filepath of the config file to save in TorchScript model and extract network information,
1268
+ the saved key in the TorchScript model is the config filename without extension, and the saved config
1269
+ value is always serialized in JSON format no matter the original file format is JSON or YAML.
1270
+ it can be a single file or a list of files. if `None`, must be provided in `args_file`.
1271
+ key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
1272
+ weights. if not nested checkpoint, no need to set.
1273
+ use_trace: whether using `torch.jit.trace` to convert the PyTorch model to TorchScript model.
1274
+ input_shape: a shape used to generate the random input of the network, when converting the model to a
1275
+ TorchScript model. Should be a list like [N, C, H, W] or [N, C, H, W, D]. If not given, will try to
1276
+ parse from the `metadata` config.
1277
+ args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that
1278
+ the command line inputs can be simplified.
1279
+ converter_kwargs: extra arguments that are needed by `convert_to_torchscript`, except ones that already exist
1280
+ in the input parameters.
1281
+ override: id-value pairs to override or add the corresponding config content.
1282
+ e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.
1283
+
1284
+ """
1285
+ _args = update_kwargs(
1286
+ args=args_file,
1287
+ net_id=net_id,
1288
+ filepath=filepath,
1289
+ meta_file=meta_file,
1290
+ config_file=config_file,
1291
+ ckpt_file=ckpt_file,
1292
+ key_in_ckpt=key_in_ckpt,
1293
+ use_trace=use_trace,
1294
+ input_shape=input_shape,
1295
+ converter_kwargs=converter_kwargs,
1296
+ **override,
1297
+ )
1298
+ _log_input_summary(tag="ckpt_export", args=_args)
1299
+ (
1300
+ config_file_,
1301
+ filepath_,
1302
+ ckpt_file_,
1303
+ net_id_,
1304
+ meta_file_,
1305
+ key_in_ckpt_,
1306
+ use_trace_,
1307
+ input_shape_,
1308
+ converter_kwargs_,
1309
+ ) = _pop_args(
1310
+ _args,
1311
+ "config_file",
1312
+ filepath=None,
1313
+ ckpt_file=None,
1314
+ net_id=None,
1315
+ meta_file=None,
1316
+ key_in_ckpt="",
1317
+ use_trace=False,
1318
+ input_shape=None,
1319
+ converter_kwargs={},
1320
+ )
1321
+ bundle_root = _args.get("bundle_root", os.getcwd())
1322
+
1323
+ parser = ConfigParser()
1324
+ parser.read_config(f=config_file_)
1325
+ meta_file_ = os.path.join(bundle_root, "configs", "metadata.json") if meta_file_ is None else meta_file_
1326
+ if os.path.exists(meta_file_):
1327
+ parser.read_meta(f=meta_file_)
1328
+
1329
+ # the rest key-values in the _args are to override config content
1330
+ for k, v in _args.items():
1331
+ parser[k] = v
1332
+
1333
+ filepath_ = os.path.join(bundle_root, "models", "model.ts") if filepath_ is None else filepath_
1334
+ ckpt_file_ = os.path.join(bundle_root, "models", "model.pt") if ckpt_file_ is None else ckpt_file_
1335
+ if not os.path.exists(ckpt_file_):
1336
+ raise FileNotFoundError(f'Checkpoint file "{ckpt_file_}" not found, please specify it in argument "ckpt_file".')
1337
+
1338
+ net_id_ = "network_def" if net_id_ is None else net_id_
1339
+ try:
1340
+ parser.get_parsed_content(net_id_)
1341
+ except ValueError as e:
1342
+ raise ValueError(
1343
+ f'Network definition "{net_id_}" cannot be found in "{config_file_}", specify name with argument "net_id".'
1344
+ ) from e
1345
+
1346
+ # When export through torch.jit.trace without providing input_shape, will try to parse one from the parser.
1347
+ if (not input_shape_) and use_trace:
1348
+ input_shape_ = _get_fake_input_shape(parser=parser)
1349
+
1350
+ inputs_: Sequence[Any] | None = [torch.rand(input_shape_)] if input_shape_ else None
1351
+
1352
+ converter_kwargs_.update({"inputs": inputs_, "use_trace": use_trace_})
1353
+ # Use the given converter to convert a model and save with metadata, config content
1354
+ _export(
1355
+ convert_to_torchscript,
1356
+ parser,
1357
+ net_id=net_id_,
1358
+ filepath=filepath_,
1359
+ ckpt_file=ckpt_file_,
1360
+ config_file=config_file_,
1361
+ key_in_ckpt=key_in_ckpt_,
1362
+ **converter_kwargs_,
1363
+ )
1364
+
1365
+
1366
+ def trt_export(
1367
+ net_id: str | None = None,
1368
+ filepath: PathLike | None = None,
1369
+ ckpt_file: str | None = None,
1370
+ meta_file: str | Sequence[str] | None = None,
1371
+ config_file: str | Sequence[str] | None = None,
1372
+ key_in_ckpt: str | None = None,
1373
+ precision: str | None = None,
1374
+ input_shape: Sequence[int] | None = None,
1375
+ use_trace: bool | None = None,
1376
+ dynamic_batchsize: Sequence[int] | None = None,
1377
+ device: int | None = None,
1378
+ use_onnx: bool | None = None,
1379
+ onnx_input_names: Sequence[str] | None = None,
1380
+ onnx_output_names: Sequence[str] | None = None,
1381
+ args_file: str | None = None,
1382
+ converter_kwargs: Mapping | None = None,
1383
+ **override: Any,
1384
+ ) -> None:
1385
+ """
1386
+ Export the model checkpoint to the given filepath as a TensorRT engine-based TorchScript.
1387
+ Currently, this API only supports converting models whose inputs are all tensors.
1388
+
1389
+ There are two ways to export a model:
1390
+ 1, Torch-TensorRT way: PyTorch module ---> TorchScript module ---> TensorRT engine-based TorchScript.
1391
+ 2, ONNX-TensorRT way: PyTorch module ---> TorchScript module ---> ONNX model ---> TensorRT engine --->
1392
+ TensorRT engine-based TorchScript.
1393
+
1394
+ When exporting through the first way, some models suffer from the slowdown problem, since Torch-TensorRT
1395
+ may only convert a little part of the PyTorch model to the TensorRT engine. However when exporting through
1396
+ the second way, some Python data structures like `dict` are not supported. And some TorchScript models are
1397
+ not supported by the ONNX if exported through `torch.jit.script`.
1398
+
1399
+ Typical usage examples:
1400
+
1401
+ .. code-block:: bash
1402
+
1403
+ python -m monai.bundle trt_export --net_id <network definition> --filepath <export path> \
1404
+ --ckpt_file <checkpoint path> --input_shape <input shape> --dynamic_batchsize <batch range> ...
1405
+
1406
+ Args:
1407
+ net_id: ID name of the network component in the config, it must be `torch.nn.Module`.
1408
+ filepath: filepath to export, if filename has no extension, it becomes `.ts`.
1409
+ ckpt_file: filepath of the model checkpoint to load.
1410
+ meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
1411
+ config_file: filepath of the config file to save in the TensorRT based TorchScript model and extract network
1412
+ information, the saved key in the model is the config filename without extension, and the saved config
1413
+ value is always serialized in JSON format no matter the original file format is JSON or YAML.
1414
+ it can be a single file or a list of files. if `None`, must be provided in `args_file`.
1415
+ key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
1416
+ weights. if not nested checkpoint, no need to set.
1417
+ precision: the weight precision of the converted TensorRT engine based TorchScript models. Should be 'fp32' or 'fp16'.
1418
+ input_shape: the input shape that is used to convert the model. Should be a list like [N, C, H, W] or
1419
+ [N, C, H, W, D]. If not given, will try to parse from the `metadata` config.
1420
+ use_trace: whether using `torch.jit.trace` to convert the PyTorch model to a TorchScript model and then convert to
1421
+ a TensorRT engine based TorchScript model or an ONNX model (if `use_onnx` is True).
1422
+ dynamic_batchsize: a sequence with three elements to define the batch size range of the input for the model to be
1423
+ converted. Should be a sequence like [MIN_BATCH, OPT_BATCH, MAX_BATCH]. After converted, the batchsize of
1424
+ model input should between `MIN_BATCH` and `MAX_BATCH` and the `OPT_BATCH` is the best performance batchsize
1425
+ that the TensorRT tries to fit. The `OPT_BATCH` should be the most frequently used input batchsize in
1426
+ the application.
1427
+ device: the target GPU index to convert and verify the model.
1428
+ use_onnx: whether using the ONNX-TensorRT way to export the TensorRT engine-based TorchScript model.
1429
+ onnx_input_names: optional input names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be
1430
+ a sequence like `['input_0', 'input_1', ..., 'input_N']` where N equals to the number of the model inputs. If not
1431
+ given, will use `['input_0']`, which supposes the model only has one input.
1432
+ onnx_output_names: optional output names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be
1433
+ a sequence like `['output_0', 'output_1', ..., 'output_N']` where N equals to the number of the model outputs. If
1434
+ not given, will use `['output_0']`, which supposes the model only has one output.
1435
+ args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that
1436
+ the command line inputs can be simplified.
1437
+ converter_kwargs: extra arguments that are needed by `convert_to_trt`, except ones that already exist in the
1438
+ input parameters.
1439
+ override: id-value pairs to override or add the corresponding config content.
1440
+ e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.
1441
+
1442
+ """
1443
+ _args = update_kwargs(
1444
+ args=args_file,
1445
+ net_id=net_id,
1446
+ filepath=filepath,
1447
+ meta_file=meta_file,
1448
+ config_file=config_file,
1449
+ ckpt_file=ckpt_file,
1450
+ key_in_ckpt=key_in_ckpt,
1451
+ precision=precision,
1452
+ input_shape=input_shape,
1453
+ use_trace=use_trace,
1454
+ dynamic_batchsize=dynamic_batchsize,
1455
+ device=device,
1456
+ use_onnx=use_onnx,
1457
+ onnx_input_names=onnx_input_names,
1458
+ onnx_output_names=onnx_output_names,
1459
+ converter_kwargs=converter_kwargs,
1460
+ **override,
1461
+ )
1462
+ _log_input_summary(tag="trt_export", args=_args)
1463
+ (
1464
+ filepath_,
1465
+ ckpt_file_,
1466
+ config_file_,
1467
+ net_id_,
1468
+ meta_file_,
1469
+ key_in_ckpt_,
1470
+ precision_,
1471
+ input_shape_,
1472
+ use_trace_,
1473
+ dynamic_batchsize_,
1474
+ device_,
1475
+ use_onnx_,
1476
+ onnx_input_names_,
1477
+ onnx_output_names_,
1478
+ converter_kwargs_,
1479
+ ) = _pop_args(
1480
+ _args,
1481
+ "filepath",
1482
+ "ckpt_file",
1483
+ "config_file",
1484
+ net_id="",
1485
+ meta_file=None,
1486
+ key_in_ckpt="",
1487
+ precision="fp32",
1488
+ input_shape=[],
1489
+ use_trace=False,
1490
+ dynamic_batchsize=None,
1491
+ device=None,
1492
+ use_onnx=False,
1493
+ onnx_input_names=["input_0"],
1494
+ onnx_output_names=["output_0"],
1495
+ converter_kwargs={},
1496
+ )
1497
+
1498
+ parser = ConfigParser()
1499
+
1500
+ parser.read_config(f=config_file_)
1501
+ if meta_file_ is not None:
1502
+ parser.read_meta(f=meta_file_)
1503
+
1504
+ # the rest key-values in the _args are to override config content
1505
+ for k, v in _args.items():
1506
+ parser[k] = v
1507
+
1508
+ # The convert_to_trt must have an `input_shape_` as input, no matter what the `use_trace` is.
1509
+ # If the `input_shape` is not provided, will try to parse it from the parser`.
1510
+ if not input_shape_:
1511
+ input_shape_ = _get_fake_input_shape(parser=parser)
1512
+
1513
+ trt_api_parameters = {
1514
+ "precision": precision_,
1515
+ "input_shape": input_shape_,
1516
+ "dynamic_batchsize": dynamic_batchsize_,
1517
+ "use_trace": use_trace_,
1518
+ "device": device_,
1519
+ "use_onnx": use_onnx_,
1520
+ "onnx_input_names": onnx_input_names_,
1521
+ "onnx_output_names": onnx_output_names_,
1522
+ }
1523
+ converter_kwargs_.update(trt_api_parameters)
1524
+
1525
+ _export(
1526
+ convert_to_trt,
1527
+ parser,
1528
+ net_id=net_id_,
1529
+ filepath=filepath_,
1530
+ ckpt_file=ckpt_file_,
1531
+ config_file=config_file_,
1532
+ key_in_ckpt=key_in_ckpt_,
1533
+ **converter_kwargs_,
1534
+ )
1535
+
1536
+
1537
+ def init_bundle(
1538
+ bundle_dir: PathLike,
1539
+ ckpt_file: PathLike | None = None,
1540
+ network: torch.nn.Module | None = None,
1541
+ dataset_license: bool = False,
1542
+ metadata_str: dict | str | None = None,
1543
+ inference_str: dict | str | None = None,
1544
+ ) -> None:
1545
+ """
1546
+ Initialise a new bundle directory with some default configuration files and optionally network weights.
1547
+
1548
+ Typical usage example:
1549
+
1550
+ .. code-block:: bash
1551
+
1552
+ python -m monai.bundle init_bundle /path/to/bundle_dir network_ckpt.pt
1553
+
1554
+ Args:
1555
+ bundle_dir: directory name to create, must not exist but parent direct must exist
1556
+ ckpt_file: optional checkpoint file to copy into bundle
1557
+ network: if given instead of ckpt_file this network's weights will be stored in bundle
1558
+ dataset_license: if `True`, a default license file called "data_license.txt" will be produced. This
1559
+ file is required if there are any license conditions stated for data your bundle uses.
1560
+ metadata_str: optional metadata string to write to bundle, if not given a default will be used.
1561
+ inference_str: optional inference string to write to bundle, if not given a default will be used.
1562
+ """
1563
+ if metadata_str is None:
1564
+ metadata_str = DEFAULT_METADATA
1565
+ if inference_str is None:
1566
+ inference_str = DEFAULT_INFERENCE
1567
+
1568
+ bundle_dir = Path(bundle_dir).absolute()
1569
+
1570
+ if bundle_dir.exists():
1571
+ raise ValueError(f"Specified bundle directory '{str(bundle_dir)}' already exists")
1572
+
1573
+ if not bundle_dir.parent.is_dir():
1574
+ raise ValueError(f"Parent directory of specified bundle directory '{str(bundle_dir)}' does not exist")
1575
+
1576
+ configs_dir = bundle_dir / "configs"
1577
+ models_dir = bundle_dir / "models"
1578
+ docs_dir = bundle_dir / "docs"
1579
+
1580
+ bundle_dir.mkdir()
1581
+ configs_dir.mkdir()
1582
+ models_dir.mkdir()
1583
+ docs_dir.mkdir()
1584
+
1585
+ if isinstance(metadata_str, dict):
1586
+ metadata_str = json.dumps(metadata_str, indent=4)
1587
+
1588
+ if isinstance(inference_str, dict):
1589
+ inference_str = json.dumps(inference_str, indent=4)
1590
+
1591
+ with open(str(configs_dir / "metadata.json"), "w") as o:
1592
+ o.write(metadata_str)
1593
+
1594
+ with open(str(configs_dir / "inference.json"), "w") as o:
1595
+ o.write(inference_str)
1596
+
1597
+ with open(str(docs_dir / "README.md"), "w") as o:
1598
+ readme = """
1599
+ # Your Model Name
1600
+
1601
+ Describe your model here and how to run it, for example using `inference.json`:
1602
+
1603
+ ```
1604
+ python -m monai.bundle run \
1605
+ --meta_file /path/to/bundle/configs/metadata.json \
1606
+ --config_file /path/to/bundle/configs/inference.json \
1607
+ --dataset_dir ./input \
1608
+ --bundle_root /path/to/bundle
1609
+ ```
1610
+ """
1611
+
1612
+ o.write(dedent(readme))
1613
+
1614
+ with open(str(bundle_dir / "LICENSE"), "w") as o:
1615
+ o.write("Select a license and place its terms here\n")
1616
+
1617
+ if dataset_license is True:
1618
+ with open(str(docs_dir / "data_license.txt"), "w") as o:
1619
+ o.write("Select a license for dataset and place its terms here\n")
1620
+
1621
+ if ckpt_file is not None:
1622
+ copyfile(str(ckpt_file), str(models_dir / "model.pt"))
1623
+ elif network is not None:
1624
+ save_state(network, str(models_dir / "model.pt"))
1625
+
1626
+
1627
+ def _add_model_card_metadata(new_modelcard_path):
1628
+ # Extract license from LICENSE file
1629
+ license_name = "unknown"
1630
+ license_path = os.path.join(os.path.dirname(new_modelcard_path), "LICENSE")
1631
+ if os.path.exists(license_path):
1632
+ with open(license_path) as file:
1633
+ content = file.read()
1634
+ if "Apache License" in content and "Version 2.0" in content:
1635
+ license_name = "apache-2.0"
1636
+ elif "MIT License" in content:
1637
+ license_name = "mit"
1638
+ # Add relevant tags
1639
+ tags = "- monai\n- medical\nlibrary_name: monai\n"
1640
+ # Create tag section
1641
+ tag_content = f"---\ntags:\n{tags}license: {license_name}\n---"
1642
+
1643
+ # Update model card
1644
+ with open(new_modelcard_path) as file:
1645
+ content = file.read()
1646
+ new_content = tag_content + "\n" + content
1647
+ with open(new_modelcard_path, "w") as file:
1648
+ file.write(new_content)
1649
+
1650
+
1651
+ def push_to_hf_hub(
1652
+ repo: str,
1653
+ name: str,
1654
+ bundle_dir: str,
1655
+ token: str | None = None,
1656
+ private: bool | None = True,
1657
+ version: str | None = None,
1658
+ tag_as_latest_version: bool | None = False,
1659
+ **upload_folder_kwargs: Any,
1660
+ ) -> Any:
1661
+ """
1662
+ Push a MONAI bundle to the Hugging Face Hub.
1663
+
1664
+ Typical usage examples:
1665
+
1666
+ .. code-block:: bash
1667
+
1668
+ python -m monai.bundle push_to_hf_hub --repo <HF repository id> --name <bundle name> \
1669
+ --bundle_dir <bundle directory> --version <version> ...
1670
+
1671
+ Args:
1672
+ repo: namespace (user or organization) and a repo name separated by a /, e.g. `hf_username/bundle_name`
1673
+ bundle_name: name of the bundle directory to push.
1674
+ bundle_dir: path to the bundle directory.
1675
+ token: Hugging Face authentication token. Default is `None` (will default to the stored token).
1676
+ private: Private visibility of the repository on Hugging Face. Default is `True`.
1677
+ version_name: Name of the version tag to create. Default is `None` (no version tag is created).
1678
+ tag_as_latest_version: Whether to tag the commit as `latest_version`.
1679
+ This version will downloaded by default when using `bundle.download()`. Default is `False`.
1680
+ upload_folder_kwargs: Keyword arguments to pass to `HfApi.upload_folder`.
1681
+
1682
+ Returns:
1683
+ repo_url: URL of the Hugging Face repo
1684
+ """
1685
+ # Connect to API and create repo
1686
+ hf_api = huggingface_hub.HfApi(token=token)
1687
+ hf_api.create_repo(repo_id=repo, private=private, exist_ok=True)
1688
+
1689
+ # Create model card in bundle directory
1690
+ new_modelcard_path = os.path.join(bundle_dir, name, "README.md")
1691
+ modelcard_path = os.path.join(bundle_dir, name, "docs", "README.md")
1692
+ if os.path.exists(modelcard_path):
1693
+ # Copy README from old path if it exists
1694
+ copyfile(modelcard_path, new_modelcard_path)
1695
+ _add_model_card_metadata(new_modelcard_path)
1696
+
1697
+ # Upload bundle folder to repo
1698
+ repo_url = hf_api.upload_folder(repo_id=repo, folder_path=os.path.join(bundle_dir, name), **upload_folder_kwargs)
1699
+
1700
+ # Create version tag if specified
1701
+ if version is not None:
1702
+ hf_api.create_tag(repo_id=repo, tag=version, exist_ok=True)
1703
+
1704
+ # Optionally tag as `latest_version`
1705
+ if tag_as_latest_version:
1706
+ hf_api.create_tag(repo_id=repo, tag="latest_version", exist_ok=True)
1707
+
1708
+ return repo_url
1709
+
1710
+
1711
+ def create_workflow(
1712
+ workflow_name: str | BundleWorkflow | None = None,
1713
+ config_file: str | Sequence[str] | None = None,
1714
+ args_file: str | None = None,
1715
+ **kwargs: Any,
1716
+ ) -> Any:
1717
+ """
1718
+ Specify `bundle workflow` to create monai bundle workflows.
1719
+ The workflow should be subclass of `BundleWorkflow` and be available to import.
1720
+ It can be MONAI existing bundle workflows or user customized workflows.
1721
+
1722
+ Typical usage examples:
1723
+
1724
+ .. code-block:: python
1725
+
1726
+ # Specify config_file path to create workflow:
1727
+ workflow = create_workflow(config_file="/workspace/spleen_ct_segmentation/configs/train.json", workflow_type="train")
1728
+
1729
+ # Set the workflow to other customized BundleWorkflow subclass to create workflow:
1730
+ workflow = create_workflow(workflow_name=CustomizedWorkflow)
1731
+
1732
+ Args:
1733
+ workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow".
1734
+ config_file: filepath of the config file, if it is a list of file paths, the content of them will be merged.
1735
+ args_file: a JSON or YAML file to provide default values for this API.
1736
+ so that the command line inputs can be simplified.
1737
+ kwargs: arguments to instantiate the workflow class.
1738
+
1739
+ """
1740
+ _args = update_kwargs(args=args_file, workflow_name=workflow_name, config_file=config_file, **kwargs)
1741
+ _log_input_summary(tag="run", args=_args)
1742
+ (workflow_name, config_file) = _pop_args(
1743
+ _args, workflow_name=ConfigWorkflow, config_file=None
1744
+ ) # the default workflow name is "ConfigWorkflow"
1745
+ if isinstance(workflow_name, str):
1746
+ workflow_class, has_built_in = optional_import("monai.bundle", name=str(workflow_name)) # search built-in
1747
+ if not has_built_in:
1748
+ workflow_class = locate(str(workflow_name)) # search dotted path
1749
+ if workflow_class is None:
1750
+ raise ValueError(f"cannot locate specified workflow class: {workflow_name}.")
1751
+ elif issubclass(workflow_name, BundleWorkflow): # type: ignore
1752
+ workflow_class = workflow_name
1753
+ else:
1754
+ raise ValueError(
1755
+ "Argument `workflow_name` must be a bundle workflow class name"
1756
+ f"or subclass of BundleWorkflow, got: {workflow_name}."
1757
+ )
1758
+
1759
+ if config_file is not None:
1760
+ workflow_ = workflow_class(config_file=config_file, **_args)
1761
+ else:
1762
+ workflow_ = workflow_class(**_args)
1763
+
1764
+ workflow_.initialize()
1765
+
1766
+ return workflow_
1767
+
1768
+
1769
+ def download_large_files(bundle_path: str | None = None, large_file_name: str | None = None) -> None:
1770
+ """
1771
+ This utility allows you to download large files from a bundle. It supports file suffixes like ".yml", ".yaml", and ".json".
1772
+ If you don't specify a `large_file_name`, it will automatically search for large files among the supported suffixes.
1773
+
1774
+ Typical usage examples:
1775
+ .. code-block:: bash
1776
+
1777
+ # Execute this module as a CLI entry to download large files from a bundle path:
1778
+ python -m monai.bundle download_large_files --bundle_path <bundle_path>
1779
+
1780
+ # Execute this module as a CLI entry to download large files from the bundle path with a specified `large_file_name`:
1781
+ python -m monai.bundle download_large_files --bundle_path <bundle_path> --large_file_name large_files.yaml
1782
+
1783
+ Args:
1784
+ bundle_path: (Optional) The path to the bundle where the files are located. Default is `os.getcwd()`.
1785
+ large_file_name: (Optional) The name of the large file to be downloaded.
1786
+
1787
+ """
1788
+ bundle_path = os.getcwd() if bundle_path is None else bundle_path
1789
+ if large_file_name is None:
1790
+ large_file_path = list(Path(bundle_path).glob("large_files*"))
1791
+ large_file_path = list(filter(lambda x: x.suffix in [".yml", ".yaml", ".json"], large_file_path))
1792
+ if len(large_file_path) == 0:
1793
+ raise FileNotFoundError(f"Cannot find the large_files.yml/yaml/json under {bundle_path}.")
1794
+
1795
+ parser = ConfigParser()
1796
+ parser.read_config(large_file_path)
1797
+ large_files_list = parser.get()["large_files"]
1798
+ for lf_data in large_files_list:
1799
+ lf_data["fuzzy"] = True
1800
+ if "hash_val" in lf_data and lf_data.get("hash_val", "") == "":
1801
+ lf_data.pop("hash_val")
1802
+ if "hash_type" in lf_data and lf_data.get("hash_type", "") == "":
1803
+ lf_data.pop("hash_type")
1804
+ lf_data["filepath"] = os.path.join(bundle_path, lf_data["path"])
1805
+ lf_data.pop("path")
1806
+ download_url(**lf_data)
source_code/SegMamba/monai/bundle/utils.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import zipfile
17
+ from typing import Any
18
+
19
+ from monai.config.deviceconfig import get_config_values
20
+ from monai.utils import optional_import
21
+
22
+ yaml, _ = optional_import("yaml")
23
+
24
+ __all__ = ["ID_REF_KEY", "ID_SEP_KEY", "EXPR_KEY", "MACRO_KEY", "DEFAULT_MLFLOW_SETTINGS", "DEFAULT_EXP_MGMT_SETTINGS"]
25
+
26
+ ID_REF_KEY = "@" # start of a reference to a ConfigItem
27
+ ID_SEP_KEY = "::" # separator for the ID of a ConfigItem
28
+ EXPR_KEY = "$" # start of a ConfigExpression
29
+ MACRO_KEY = "%" # start of a macro of a config
30
+
31
+ _conf_values = get_config_values()
32
+
33
+ DEFAULT_METADATA = {
34
+ "version": "0.0.1",
35
+ "changelog": {"0.0.1": "Initial version"},
36
+ "monai_version": _conf_values["MONAI"],
37
+ "pytorch_version": str(_conf_values["Pytorch"]).split("+")[0].split("a")[0], # 1.9.0a0+df837d0 or 1.13.0+cu117
38
+ "numpy_version": _conf_values["Numpy"],
39
+ "optional_packages_version": {},
40
+ "task": "Describe what the network predicts",
41
+ "description": "A longer description of what the network does, use context, inputs, outputs, etc.",
42
+ "authors": "Your Name Here",
43
+ "copyright": "Copyright (c) Your Name Here",
44
+ "network_data_format": {"inputs": {}, "outputs": {}},
45
+ }
46
+
47
+ DEFAULT_INFERENCE = {
48
+ "imports": ["$import glob"],
49
+ "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')",
50
+ "ckpt_path": "$@bundle_root + '/models/model.pt'",
51
+ "dataset_dir": "/workspace/data",
52
+ "datalist": "$list(sorted(glob.glob(@dataset_dir + '/*.jpeg')))",
53
+ "network_def": {"_target_": "???", "spatial_dims": 2},
54
+ "network": "$@network_def.to(@device)",
55
+ "preprocessing": {
56
+ "_target_": "Compose",
57
+ "transforms": [
58
+ {"_target_": "LoadImaged", "keys": "image"},
59
+ {"_target_": "EnsureChannelFirstd", "keys": "image"},
60
+ {"_target_": "ScaleIntensityd", "keys": "image"},
61
+ {"_target_": "EnsureTyped", "keys": "image", "device": "@device"},
62
+ ],
63
+ },
64
+ "dataset": {"_target_": "Dataset", "data": "$[{'image': i} for i in @datalist]", "transform": "@preprocessing"},
65
+ "dataloader": {
66
+ "_target_": "DataLoader",
67
+ "dataset": "@dataset",
68
+ "batch_size": 1,
69
+ "shuffle": False,
70
+ "num_workers": 0,
71
+ },
72
+ "inferer": {"_target_": "SimpleInferer"},
73
+ "postprocessing": {
74
+ "_target_": "Compose",
75
+ "transforms": [
76
+ {"_target_": "Activationsd", "keys": "pred", "softmax": True},
77
+ {"_target_": "AsDiscreted", "keys": "pred", "argmax": True},
78
+ ],
79
+ },
80
+ "handlers": [
81
+ {
82
+ "_target_": "CheckpointLoader",
83
+ "_disabled_": "$not os.path.exists(@ckpt_path)",
84
+ "load_path": "@ckpt_path",
85
+ "load_dict": {"model": "@network"},
86
+ }
87
+ ],
88
+ "evaluator": {
89
+ "_target_": "SupervisedEvaluator",
90
+ "device": "@device",
91
+ "val_data_loader": "@dataloader",
92
+ "network": "@network",
93
+ "inferer": "@inferer",
94
+ "postprocessing": "@postprocessing",
95
+ "val_handlers": "@handlers",
96
+ },
97
+ "evaluating": ["$@evaluator.run()"],
98
+ }
99
+
100
+ DEFAULT_HANDLERS_ID = {
101
+ "trainer": {"id": "train#trainer", "handlers": "train#handlers"},
102
+ "validator": {"id": "validate#evaluator", "handlers": "validate#handlers"},
103
+ "evaluator": {"id": "evaluator", "handlers": "handlers"},
104
+ }
105
+
106
+ DEFAULT_MLFLOW_SETTINGS = {
107
+ "handlers_id": DEFAULT_HANDLERS_ID,
108
+ "configs": {
109
+ # if no "output_dir" in the bundle config, default to "<bundle root>/eval"
110
+ "output_dir": "$@bundle_root + '/eval'",
111
+ # use URI to support linux, mac and windows os
112
+ "tracking_uri": "$monai.utils.path_to_uri(@output_dir) + '/mlruns'",
113
+ "experiment_name": "monai_experiment",
114
+ "run_name": None,
115
+ # may fill it at runtime
116
+ "save_execute_config": True,
117
+ "is_not_rank0": (
118
+ "$torch.distributed.is_available() \
119
+ and torch.distributed.is_initialized() and torch.distributed.get_rank() > 0"
120
+ ),
121
+ # MLFlowHandler config for the trainer
122
+ "trainer": {
123
+ "_target_": "MLFlowHandler",
124
+ "_disabled_": "@is_not_rank0",
125
+ "tracking_uri": "@tracking_uri",
126
+ "experiment_name": "@experiment_name",
127
+ "run_name": "@run_name",
128
+ "artifacts": "@save_execute_config",
129
+ "iteration_log": True,
130
+ "epoch_log": True,
131
+ "tag_name": "train_loss",
132
+ "output_transform": "$monai.handlers.from_engine(['loss'], first=True)",
133
+ "close_on_complete": True,
134
+ },
135
+ # MLFlowHandler config for the validator
136
+ "validator": {
137
+ "_target_": "MLFlowHandler",
138
+ "_disabled_": "@is_not_rank0",
139
+ "tracking_uri": "@tracking_uri",
140
+ "experiment_name": "@experiment_name",
141
+ "run_name": "@run_name",
142
+ "iteration_log": False,
143
+ },
144
+ # MLFlowHandler config for the evaluator
145
+ "evaluator": {
146
+ "_target_": "MLFlowHandler",
147
+ "_disabled_": "@is_not_rank0",
148
+ "tracking_uri": "@tracking_uri",
149
+ "experiment_name": "@experiment_name",
150
+ "run_name": "@run_name",
151
+ "artifacts": "@save_execute_config",
152
+ "iteration_log": False,
153
+ "close_on_complete": True,
154
+ },
155
+ },
156
+ }
157
+
158
+ DEFAULT_EXP_MGMT_SETTINGS = {"mlflow": DEFAULT_MLFLOW_SETTINGS} # default experiment management settings
159
+
160
+
161
+ def load_bundle_config(bundle_path: str, *config_names: str, **load_kw_args: Any) -> Any:
162
+ """
163
+ Load the metadata and nominated configuration files from a MONAI bundle without loading the network itself.
164
+
165
+ This function will load the information from the bundle, which can be a directory or a zip file containing a
166
+ directory or a Torchscript bundle, and return the parser object with the information. This saves having to load
167
+ the model if only the information is wanted, and can work on any sort of bundle format.
168
+
169
+ Args:
170
+ bundle_path: path to the bundle directory or zip file
171
+ config_names: names of configuration files with extensions to load, should not be full paths but just name+ext
172
+ load_kw_args: keyword arguments to pass to the ConfigParser object when loading
173
+
174
+ Returns:
175
+ ConfigParser object containing the parsed information
176
+ """
177
+
178
+ from monai.bundle.config_parser import ConfigParser # avoids circular import
179
+
180
+ parser = ConfigParser()
181
+
182
+ if not os.path.exists(bundle_path):
183
+ raise ValueError(f"Cannot find bundle file/directory '{bundle_path}'")
184
+
185
+ # bundle is a directory, read files directly
186
+ if os.path.isdir(bundle_path):
187
+ conf_data = []
188
+ parser.read_meta(f=os.path.join(bundle_path, "configs", "metadata.json"), **load_kw_args)
189
+
190
+ for cname in config_names:
191
+ cpath = os.path.join(bundle_path, "configs", cname)
192
+ if not os.path.exists(cpath):
193
+ raise ValueError(f"Cannot find config file '{cpath}'")
194
+
195
+ conf_data.append(cpath)
196
+
197
+ parser.read_config(f=conf_data, **load_kw_args)
198
+ else:
199
+ # bundle is a zip file which is either a zipped directory or a Torchscript archive
200
+
201
+ name, _ = os.path.splitext(os.path.basename(bundle_path))
202
+
203
+ archive = zipfile.ZipFile(bundle_path, "r")
204
+
205
+ all_files = archive.namelist()
206
+
207
+ zip_meta_name = f"{name}/configs/metadata.json"
208
+
209
+ if zip_meta_name in all_files:
210
+ prefix = f"{name}/configs/" # zipped directory location for files
211
+ else:
212
+ zip_meta_name = f"{name}/extra/metadata.json"
213
+ prefix = f"{name}/extra/" # Torchscript location for files
214
+
215
+ meta_json = json.loads(archive.read(zip_meta_name))
216
+ parser.read_meta(f=meta_json)
217
+
218
+ for cname in config_names:
219
+ full_cname = prefix + cname
220
+ if full_cname not in all_files:
221
+ raise ValueError(f"Cannot find config file '{full_cname}'")
222
+
223
+ ardata = archive.read(full_cname)
224
+
225
+ if full_cname.lower().endswith("json"):
226
+ cdata = json.loads(ardata, **load_kw_args)
227
+ elif full_cname.lower().endswith(("yaml", "yml")):
228
+ cdata = yaml.safe_load(ardata, **load_kw_args)
229
+
230
+ parser.read_config(f=cdata)
231
+
232
+ return parser
source_code/SegMamba/monai/bundle/workflows.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import sys
17
+ import time
18
+ from abc import ABC, abstractmethod
19
+ from copy import copy
20
+ from logging.config import fileConfig
21
+ from pathlib import Path
22
+ from typing import Any, Sequence
23
+
24
+ from monai.apps.utils import get_logger
25
+ from monai.bundle.config_parser import ConfigParser
26
+ from monai.bundle.properties import InferProperties, MetaProperties, TrainProperties
27
+ from monai.bundle.utils import DEFAULT_EXP_MGMT_SETTINGS, EXPR_KEY, ID_REF_KEY, ID_SEP_KEY
28
+ from monai.config import PathLike
29
+ from monai.utils import BundleProperty, BundlePropertyConfig, deprecated_arg, deprecated_arg_default, ensure_tuple
30
+
31
+ __all__ = ["BundleWorkflow", "ConfigWorkflow"]
32
+
33
+ logger = get_logger(module_name=__name__)
34
+
35
+
36
+ class BundleWorkflow(ABC):
37
+ """
38
+ Base class for the workflow specification in bundle, it can be a training, evaluation or inference workflow.
39
+ It defines the basic interfaces for the bundle workflow behavior: `initialize`, `run`, `finalize`, etc.
40
+ And also provides the interface to get / set public properties to interact with a bundle workflow.
41
+
42
+ Args:
43
+ workflow_type: specifies the workflow type: "train" or "training" for a training workflow,
44
+ or "infer", "inference", "eval", "evaluation" for a inference workflow,
45
+ other unsupported string will raise a ValueError.
46
+ default to `None` for common workflow.
47
+ workflow: specifies the workflow type: "train" or "training" for a training workflow,
48
+ or "infer", "inference", "eval", "evaluation" for a inference workflow,
49
+ other unsupported string will raise a ValueError.
50
+ default to `None` for common workflow.
51
+ properties_path: the path to the JSON file of properties.
52
+ meta_file: filepath of the metadata file, if this is a list of file paths, their contents will be merged in order.
53
+ logging_file: config file for `logging` module in the program. for more details:
54
+ https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig.
55
+
56
+ """
57
+
58
+ supported_train_type: tuple = ("train", "training")
59
+ supported_infer_type: tuple = ("infer", "inference", "eval", "evaluation")
60
+
61
+ @deprecated_arg(
62
+ "workflow",
63
+ since="1.2",
64
+ removed="1.5",
65
+ new_name="workflow_type",
66
+ msg_suffix="please use `workflow_type` instead.",
67
+ )
68
+ def __init__(
69
+ self,
70
+ workflow_type: str | None = None,
71
+ workflow: str | None = None,
72
+ properties_path: PathLike | None = None,
73
+ meta_file: str | Sequence[str] | None = None,
74
+ logging_file: str | None = None,
75
+ ):
76
+ if logging_file is not None:
77
+ if not os.path.isfile(logging_file):
78
+ raise FileNotFoundError(f"Cannot find the logging config file: {logging_file}.")
79
+ logger.info(f"Setting logging properties based on config: {logging_file}.")
80
+ fileConfig(logging_file, disable_existing_loggers=False)
81
+
82
+ if meta_file is not None:
83
+ if isinstance(meta_file, str) and not os.path.isfile(meta_file):
84
+ logger.error(
85
+ f"Cannot find the metadata config file: {meta_file}. "
86
+ "Please see: https://docs.monai.io/en/stable/mb_specification.html"
87
+ )
88
+ meta_file = None
89
+ if isinstance(meta_file, list):
90
+ for f in meta_file:
91
+ if not os.path.isfile(f):
92
+ logger.error(
93
+ f"Cannot find the metadata config file: {f}. "
94
+ "Please see: https://docs.monai.io/en/stable/mb_specification.html"
95
+ )
96
+ meta_file = None
97
+
98
+ workflow_type = workflow if workflow is not None else workflow_type
99
+ if workflow_type is None and properties_path is None:
100
+ self.properties = copy(MetaProperties)
101
+ self.workflow_type = None
102
+ self.meta_file = meta_file
103
+ return
104
+ if properties_path is not None:
105
+ properties_path = Path(properties_path)
106
+ if not properties_path.is_file():
107
+ raise ValueError(f"Property file {properties_path} does not exist.")
108
+ with open(properties_path) as json_file:
109
+ self.properties = json.load(json_file)
110
+ self.workflow_type = None
111
+ self.meta_file = meta_file
112
+ return
113
+ if workflow_type.lower() in self.supported_train_type: # type: ignore[union-attr]
114
+ self.properties = {**TrainProperties, **MetaProperties}
115
+ self.workflow_type = "train"
116
+ elif workflow_type.lower() in self.supported_infer_type: # type: ignore[union-attr]
117
+ self.properties = {**InferProperties, **MetaProperties}
118
+ self.workflow_type = "infer"
119
+ else:
120
+ raise ValueError(f"Unsupported workflow type: '{workflow_type}'.")
121
+
122
+ self.meta_file = meta_file
123
+
124
+ @abstractmethod
125
+ def initialize(self, *args: Any, **kwargs: Any) -> Any:
126
+ """
127
+ Initialize the bundle workflow before running.
128
+
129
+ """
130
+ raise NotImplementedError()
131
+
132
+ @abstractmethod
133
+ def run(self, *args: Any, **kwargs: Any) -> Any:
134
+ """
135
+ Run the bundle workflow, it can be a training, evaluation or inference.
136
+
137
+ """
138
+ raise NotImplementedError()
139
+
140
+ @abstractmethod
141
+ def finalize(self, *args: Any, **kwargs: Any) -> Any:
142
+ """
143
+ Finalize step after the running of bundle workflow.
144
+
145
+ """
146
+ raise NotImplementedError()
147
+
148
+ @abstractmethod
149
+ def _get_property(self, name: str, property: dict) -> Any:
150
+ """
151
+ With specified property name and information, get the expected property value.
152
+
153
+ Args:
154
+ name: the name of target property.
155
+ property: other information for the target property, defined in `TrainProperties` or `InferProperties`.
156
+
157
+ """
158
+ raise NotImplementedError()
159
+
160
+ @abstractmethod
161
+ def _set_property(self, name: str, property: dict, value: Any) -> Any:
162
+ """
163
+ With specified property name and information, set value for the expected property.
164
+
165
+ Args:
166
+ name: the name of target property.
167
+ property: other information for the target property, defined in `TrainProperties` or `InferProperties`.
168
+ value: value to set for the property.
169
+
170
+ """
171
+ raise NotImplementedError()
172
+
173
+ def __getattr__(self, name):
174
+ if self.properties is not None and name in self.properties:
175
+ return self._get_property(name=name, property=self.properties[name])
176
+ else:
177
+ return self.__getattribute__(name) # getting regular attribute
178
+
179
+ def __setattr__(self, name, value):
180
+ if name != "properties" and self.properties is not None and name in self.properties:
181
+ self._set_property(name=name, property=self.properties[name], value=value)
182
+ else:
183
+ super().__setattr__(name, value) # setting regular attribute
184
+
185
+ def get_workflow_type(self):
186
+ """
187
+ Get the workflow type, it can be `None`, "train", or "infer".
188
+
189
+ """
190
+ return self.workflow_type
191
+
192
+ def get_meta_file(self):
193
+ """
194
+ Get the meta file.
195
+
196
+ """
197
+ return self.meta_file
198
+
199
+ def add_property(self, name: str, required: str, desc: str | None = None) -> None:
200
+ """
201
+ Besides the default predefined properties, some 3rd party applications may need the bundle
202
+ definition to provide additional properties for the specific use cases, if the bundle can't
203
+ provide the property, means it can't work with the application.
204
+ This utility adds the property for the application requirements check and access.
205
+
206
+ Args:
207
+ name: the name of target property.
208
+ required: whether the property is "must-have".
209
+ desc: descriptions for the property.
210
+ """
211
+ if self.properties is None:
212
+ self.properties = {}
213
+ if name in self.properties:
214
+ logger.warn(f"property '{name}' already exists in the properties list, overriding it.")
215
+ self.properties[name] = {BundleProperty.DESC: desc, BundleProperty.REQUIRED: required}
216
+
217
+ def check_properties(self) -> list[str] | None:
218
+ """
219
+ Check whether the required properties are existing in the bundle workflow.
220
+ If no workflow type specified, return None, otherwise, return a list of required but missing properties.
221
+
222
+ """
223
+ if self.properties is None:
224
+ return None
225
+ return [n for n, p in self.properties.items() if p.get(BundleProperty.REQUIRED, False) and not hasattr(self, n)]
226
+
227
+
228
+ class ConfigWorkflow(BundleWorkflow):
229
+ """
230
+ Specification for the config-based bundle workflow.
231
+ Standardized the `initialize`, `run`, `finalize` behavior in a config-based training, evaluation, or inference.
232
+ Before `run`, we add bundle root directory to Python search directories automatically.
233
+ For more information: https://docs.monai.io/en/latest/mb_specification.html.
234
+
235
+ Args:
236
+ config_file: filepath of the config file, if this is a list of file paths, their contents will be merged in order.
237
+ meta_file: filepath of the metadata file, if this is a list of file paths, their contents will be merged in order.
238
+ If None, default to "configs/metadata.json", which is commonly used for bundles in MONAI model zoo.
239
+ logging_file: config file for `logging` module in the program. for more details:
240
+ https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig.
241
+ If None, default to "configs/logging.conf", which is commonly used for bundles in MONAI model zoo.
242
+ init_id: ID name of the expected config expression to initialize before running, default to "initialize".
243
+ allow a config to have no `initialize` logic and the ID.
244
+ run_id: ID name of the expected config expression to run, default to "run".
245
+ to run the config, the target config must contain this ID.
246
+ final_id: ID name of the expected config expression to finalize after running, default to "finalize".
247
+ allow a config to have no `finalize` logic and the ID.
248
+ tracking: if not None, enable the experiment tracking at runtime with optionally configurable and extensible.
249
+ if "mlflow", will add `MLFlowHandler` to the parsed bundle with default tracking settings,
250
+ if other string, treat it as file path to load the tracking settings.
251
+ if `dict`, treat it as tracking settings.
252
+ will patch the target config content with `tracking handlers` and the top-level items of `configs`.
253
+ for detailed usage examples, please check the tutorial:
254
+ https://github.com/Project-MONAI/tutorials/blob/main/experiment_management/bundle_integrate_mlflow.ipynb.
255
+ workflow_type: specifies the workflow type: "train" or "training" for a training workflow,
256
+ or "infer", "inference", "eval", "evaluation" for a inference workflow,
257
+ other unsupported string will raise a ValueError.
258
+ default to `None` for common workflow.
259
+ workflow: specifies the workflow type: "train" or "training" for a training workflow,
260
+ or "infer", "inference", "eval", "evaluation" for a inference workflow,
261
+ other unsupported string will raise a ValueError.
262
+ default to `None` for common workflow.
263
+ properties_path: the path to the JSON file of properties.
264
+ override: id-value pairs to override or add the corresponding config content.
265
+ e.g. ``--net#input_chns 42``, ``--net %/data/other.json#net_arg``
266
+
267
+ """
268
+
269
+ @deprecated_arg(
270
+ "workflow",
271
+ since="1.2",
272
+ removed="1.5",
273
+ new_name="workflow_type",
274
+ msg_suffix="please use `workflow_type` instead.",
275
+ )
276
+ @deprecated_arg_default("workflow_type", None, "train", since="1.2", replaced="1.4")
277
+ def __init__(
278
+ self,
279
+ config_file: str | Sequence[str],
280
+ meta_file: str | Sequence[str] | None = None,
281
+ logging_file: str | None = None,
282
+ init_id: str = "initialize",
283
+ run_id: str = "run",
284
+ final_id: str = "finalize",
285
+ tracking: str | dict | None = None,
286
+ workflow_type: str | None = None,
287
+ workflow: str | None = None,
288
+ properties_path: PathLike | None = None,
289
+ **override: Any,
290
+ ) -> None:
291
+ workflow_type = workflow if workflow is not None else workflow_type
292
+ if config_file is not None:
293
+ _config_files = ensure_tuple(config_file)
294
+ config_root_path = Path(_config_files[0]).parent
295
+ for _config_file in _config_files:
296
+ _config_file = Path(_config_file)
297
+ if _config_file.parent != config_root_path:
298
+ logger.warn(
299
+ f"Not all config files are in {config_root_path}. If logging_file and meta_file are"
300
+ f"not specified, {config_root_path} will be used as the default config root directory."
301
+ )
302
+ if not _config_file.is_file():
303
+ raise FileNotFoundError(f"Cannot find the config file: {_config_file}.")
304
+ else:
305
+ config_root_path = Path("configs")
306
+ meta_file = str(config_root_path / "metadata.json") if meta_file is None else meta_file
307
+ super().__init__(workflow_type=workflow_type, meta_file=meta_file, properties_path=properties_path)
308
+ self.config_root_path = config_root_path
309
+ logging_file = str(self.config_root_path / "logging.conf") if logging_file is None else logging_file
310
+ if logging_file is not None:
311
+ if not os.path.isfile(logging_file):
312
+ if logging_file == str(self.config_root_path / "logging.conf"):
313
+ logger.warn(f"Default logging file in {logging_file} does not exist, skipping logging.")
314
+ else:
315
+ raise FileNotFoundError(f"Cannot find the logging config file: {logging_file}.")
316
+ else:
317
+ logger.info(f"Setting logging properties based on config: {logging_file}.")
318
+ fileConfig(logging_file, disable_existing_loggers=False)
319
+
320
+ self.parser = ConfigParser()
321
+ self.parser.read_config(f=config_file)
322
+ if self.meta_file is not None:
323
+ self.parser.read_meta(f=self.meta_file)
324
+
325
+ # the rest key-values in the _args are to override config content
326
+ self.parser.update(pairs=override)
327
+ self.init_id = init_id
328
+ self.run_id = run_id
329
+ self.final_id = final_id
330
+ # set tracking configs for experiment management
331
+ if tracking is not None:
332
+ if isinstance(tracking, str) and tracking in DEFAULT_EXP_MGMT_SETTINGS:
333
+ settings_ = DEFAULT_EXP_MGMT_SETTINGS[tracking]
334
+ else:
335
+ settings_ = ConfigParser.load_config_files(tracking)
336
+ self.patch_bundle_tracking(parser=self.parser, settings=settings_)
337
+ self._is_initialized: bool = False
338
+
339
+ def initialize(self) -> Any:
340
+ """
341
+ Initialize the bundle workflow before running.
342
+
343
+ """
344
+ # reset the "reference_resolver" buffer at initialization stage
345
+ self.parser.parse(reset=True)
346
+ self._is_initialized = True
347
+ return self._run_expr(id=self.init_id)
348
+
349
+ def run(self) -> Any:
350
+ """
351
+ Run the bundle workflow, it can be a training, evaluation or inference.
352
+ Before run, we add bundle root directory to Python search directories automatically.
353
+
354
+ """
355
+ _bundle_root_path = (
356
+ self.config_root_path.parent if self.config_root_path.name == "configs" else self.config_root_path
357
+ )
358
+ sys.path.insert(1, str(_bundle_root_path))
359
+ if self.run_id not in self.parser:
360
+ raise ValueError(f"run ID '{self.run_id}' doesn't exist in the config file.")
361
+ return self._run_expr(id=self.run_id)
362
+
363
+ def finalize(self) -> Any:
364
+ """
365
+ Finalize step after the running of bundle workflow.
366
+
367
+ """
368
+ return self._run_expr(id=self.final_id)
369
+
370
+ def check_properties(self) -> list[str] | None:
371
+ """
372
+ Check whether the required properties are existing in the bundle workflow.
373
+ If the optional properties have reference in the config, will also check whether the properties are existing.
374
+ If no workflow type specified, return None, otherwise, return a list of required but missing properties.
375
+
376
+ """
377
+ ret = super().check_properties()
378
+ if self.properties is None:
379
+ logger.warn("No available properties had been set, skipping check.")
380
+ return None
381
+ if ret:
382
+ logger.warn(f"Loaded bundle does not contain the following required properties: {ret}")
383
+ # also check whether the optional properties use correct ID name if existing
384
+ wrong_props = []
385
+ for n, p in self.properties.items():
386
+ if not p.get(BundleProperty.REQUIRED, False) and not self._check_optional_id(name=n, property=p):
387
+ wrong_props.append(n)
388
+ if wrong_props:
389
+ logger.warn(f"Loaded bundle defines the following optional properties with wrong ID: {wrong_props}")
390
+ if ret is not None:
391
+ ret.extend(wrong_props)
392
+ return ret
393
+
394
+ def _run_expr(self, id: str, **kwargs: dict) -> Any:
395
+ return self.parser.get_parsed_content(id, **kwargs) if id in self.parser else None
396
+
397
+ def _get_prop_id(self, name: str, property: dict) -> Any:
398
+ prop_id = property[BundlePropertyConfig.ID]
399
+ if prop_id not in self.parser:
400
+ if not property.get(BundleProperty.REQUIRED, False):
401
+ return None
402
+ else:
403
+ raise KeyError(f"Property '{name}' with config ID '{prop_id}' not in the config.")
404
+ return prop_id
405
+
406
+ def _get_property(self, name: str, property: dict) -> Any:
407
+ """
408
+ With specified property name and information, get the parsed property value from config.
409
+
410
+ Args:
411
+ name: the name of target property.
412
+ property: other information for the target property, defined in `TrainProperties` or `InferProperties`.
413
+
414
+ """
415
+ if not self._is_initialized:
416
+ raise RuntimeError("Please execute 'initialize' before getting any parsed content.")
417
+ prop_id = self._get_prop_id(name, property)
418
+ return self.parser.get_parsed_content(id=prop_id) if prop_id is not None else None
419
+
420
+ def _set_property(self, name: str, property: dict, value: Any) -> None:
421
+ """
422
+ With specified property name and information, set value for the expected property.
423
+
424
+ Args:
425
+ name: the name of target property.
426
+ property: other information for the target property, defined in `TrainProperties` or `InferProperties`.
427
+ value: value to set for the property.
428
+
429
+ """
430
+ prop_id = self._get_prop_id(name, property)
431
+ if prop_id is not None:
432
+ self.parser[prop_id] = value
433
+ # must parse the config again after changing the content
434
+ self._is_initialized = False
435
+ self.parser.ref_resolver.reset()
436
+
437
+ def add_property( # type: ignore[override]
438
+ self, name: str, required: str, config_id: str, desc: str | None = None
439
+ ) -> None:
440
+ """
441
+ Besides the default predefined properties, some 3rd party applications may need the bundle
442
+ definition to provide additional properties for the specific use cases, if the bundle can't
443
+ provide the property, means it can't work with the application.
444
+ This utility adds the property for the application requirements check and access.
445
+
446
+ Args:
447
+ name: the name of target property.
448
+ required: whether the property is "must-have".
449
+ config_id: the config ID of target property in the bundle definition.
450
+ desc: descriptions for the property.
451
+
452
+ """
453
+ super().add_property(name=name, required=required, desc=desc)
454
+ self.properties[name][BundlePropertyConfig.ID] = config_id
455
+
456
+ def _check_optional_id(self, name: str, property: dict) -> bool:
457
+ """
458
+ If an optional property has reference in the config, check whether the property is existing.
459
+ If `ValidationHandler` is defined for a training workflow, will check whether the optional properties
460
+ "evaluator" and "val_interval" are existing.
461
+
462
+ Args:
463
+ name: the name of target property.
464
+ property: other information for the target property, defined in `TrainProperties` or `InferProperties`.
465
+
466
+ """
467
+ id = property.get(BundlePropertyConfig.ID, None)
468
+ ref_id = property.get(BundlePropertyConfig.REF_ID, None)
469
+ if ref_id is None:
470
+ # no ID of reference config item, skipping check for this optional property
471
+ return True
472
+ # check validation `validator` and `interval` properties as the handler index of ValidationHandler is unknown
473
+ ref: str | None = None
474
+ if name in ("evaluator", "val_interval"):
475
+ if f"train{ID_SEP_KEY}handlers" in self.parser:
476
+ for h in self.parser[f"train{ID_SEP_KEY}handlers"]:
477
+ if h["_target_"] == "ValidationHandler":
478
+ ref = h.get(ref_id, None)
479
+ else:
480
+ ref = self.parser.get(ref_id, None)
481
+ # for reference IDs that not refer to a property directly but using expressions, skip the check
482
+ if ref is not None and not ref.startswith(EXPR_KEY) and ref != ID_REF_KEY + id:
483
+ return False
484
+ return True
485
+
486
+ @staticmethod
487
+ def patch_bundle_tracking(parser: ConfigParser, settings: dict) -> None:
488
+ """
489
+ Patch the loaded bundle config with a new handler logic to enable experiment tracking features.
490
+
491
+ Args:
492
+ parser: loaded config content to patch the handler.
493
+ settings: settings for the experiment tracking, should follow the pattern of default settings.
494
+
495
+ """
496
+ for k, v in settings["configs"].items():
497
+ if k in settings["handlers_id"]:
498
+ engine = parser.get(settings["handlers_id"][k]["id"])
499
+ if engine is not None:
500
+ handlers = parser.get(settings["handlers_id"][k]["handlers"])
501
+ if handlers is None:
502
+ engine["train_handlers" if k == "trainer" else "val_handlers"] = [v]
503
+ else:
504
+ handlers.append(v)
505
+ elif k not in parser:
506
+ parser[k] = v
507
+ # save the executed config into file
508
+ default_name = f"config_{time.strftime('%Y%m%d_%H%M%S')}.json"
509
+ # Users can set the `save_execute_config` to `False`, `/path/to/artifacts` or `True`.
510
+ # If set to False, nothing will be recorded. If set to True, the default path will be logged.
511
+ # If set to a file path, the given path will be logged.
512
+ filepath = parser.get("save_execute_config", True)
513
+ if filepath:
514
+ if isinstance(filepath, bool):
515
+ if "output_dir" not in parser:
516
+ # if no "output_dir" in the bundle config, default to "<bundle root>/eval"
517
+ parser["output_dir"] = f"{EXPR_KEY}{ID_REF_KEY}bundle_root + '/eval'"
518
+ # experiment management tools can refer to this config item to track the config info
519
+ parser["save_execute_config"] = parser["output_dir"] + f" + '/{default_name}'"
520
+ filepath = os.path.join(parser.get_parsed_content("output_dir"), default_name)
521
+ Path(filepath).parent.mkdir(parents=True, exist_ok=True)
522
+ parser.export_config_file(parser.get(), filepath)
523
+ else:
524
+ parser["save_execute_config"] = None
source_code/SegMamba/monai/config/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from .deviceconfig import (
15
+ USE_COMPILED,
16
+ USE_META_DICT,
17
+ IgniteInfo,
18
+ get_config_values,
19
+ get_gpu_info,
20
+ get_optional_config_values,
21
+ get_system_info,
22
+ print_config,
23
+ print_debug_info,
24
+ print_gpu_info,
25
+ print_system_info,
26
+ )
27
+ from .type_definitions import (
28
+ DtypeLike,
29
+ IndexSelection,
30
+ KeysCollection,
31
+ NdarrayOrTensor,
32
+ NdarrayTensor,
33
+ PathLike,
34
+ SequenceStr,
35
+ TensorOrList,
36
+ )
source_code/SegMamba/monai/config/deviceconfig.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import getpass
15
+ import os
16
+ import platform
17
+ import re
18
+ import sys
19
+ from collections import OrderedDict
20
+ from typing import TextIO
21
+
22
+ import numpy as np
23
+ import torch
24
+
25
+ import monai
26
+ from monai.utils.module import OptionalImportError, get_package_version, optional_import
27
+
28
+ try:
29
+ _, HAS_EXT = optional_import("monai._C")
30
+ USE_COMPILED = HAS_EXT and os.getenv("BUILD_MONAI", "0") == "1"
31
+ except (OptionalImportError, ImportError, AttributeError):
32
+ HAS_EXT = USE_COMPILED = False
33
+
34
+ USE_META_DICT = os.environ.get("USE_META_DICT", "0") == "1" # set to True for compatibility, use meta dict.
35
+
36
+ psutil, has_psutil = optional_import("psutil")
37
+ psutil_version = psutil.__version__ if has_psutil else "NOT INSTALLED or UNKNOWN VERSION."
38
+
39
+ __all__ = [
40
+ "print_config",
41
+ "get_system_info",
42
+ "print_system_info",
43
+ "get_gpu_info",
44
+ "print_gpu_info",
45
+ "print_debug_info",
46
+ "USE_COMPILED",
47
+ "USE_META_DICT",
48
+ "IgniteInfo",
49
+ ]
50
+
51
+
52
+ def get_config_values():
53
+ """
54
+ Read the package versions into a dictionary.
55
+ """
56
+ output = OrderedDict()
57
+
58
+ output["MONAI"] = monai.__version__
59
+ output["Numpy"] = np.version.full_version
60
+ output["Pytorch"] = torch.__version__
61
+
62
+ return output
63
+
64
+
65
+ def get_optional_config_values():
66
+ """
67
+ Read the optional package versions into a dictionary.
68
+ """
69
+ output = OrderedDict()
70
+
71
+ output["Pytorch Ignite"] = get_package_version("ignite")
72
+ output["ITK"] = get_package_version("itk")
73
+ output["Nibabel"] = get_package_version("nibabel")
74
+ output["scikit-image"] = get_package_version("skimage")
75
+ output["scipy"] = get_package_version("scipy")
76
+ output["Pillow"] = get_package_version("PIL")
77
+ output["Tensorboard"] = get_package_version("tensorboard")
78
+ output["gdown"] = get_package_version("gdown")
79
+ output["TorchVision"] = get_package_version("torchvision")
80
+ output["tqdm"] = get_package_version("tqdm")
81
+ output["lmdb"] = get_package_version("lmdb")
82
+ output["psutil"] = psutil_version
83
+ output["pandas"] = get_package_version("pandas")
84
+ output["einops"] = get_package_version("einops")
85
+ output["transformers"] = get_package_version("transformers")
86
+ output["mlflow"] = get_package_version("mlflow")
87
+ output["pynrrd"] = get_package_version("nrrd")
88
+ output["clearml"] = get_package_version("clearml")
89
+
90
+ return output
91
+
92
+
93
+ def print_config(file=sys.stdout):
94
+ """
95
+ Print the package versions to `file`.
96
+
97
+ Args:
98
+ file: `print()` text stream file. Defaults to `sys.stdout`.
99
+ """
100
+ for k, v in get_config_values().items():
101
+ print(f"{k} version: {v}", file=file, flush=True)
102
+ print(f"MONAI flags: HAS_EXT = {HAS_EXT}, USE_COMPILED = {USE_COMPILED}, USE_META_DICT = {USE_META_DICT}")
103
+ print(f"MONAI rev id: {monai.__revision_id__}")
104
+ username = getpass.getuser()
105
+ masked_file_path = re.sub(username, "<username>", monai.__file__)
106
+ print(f"MONAI __file__: {masked_file_path}", file=file, flush=True)
107
+ print("\nOptional dependencies:", file=file, flush=True)
108
+ for k, v in get_optional_config_values().items():
109
+ print(f"{k} version: {v}", file=file, flush=True)
110
+ print("\nFor details about installing the optional dependencies, please visit:", file=file, flush=True)
111
+ print(
112
+ " https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n",
113
+ file=file,
114
+ flush=True,
115
+ )
116
+
117
+
118
+ def _dict_append(in_dict, key, fn):
119
+ try:
120
+ in_dict[key] = fn() if callable(fn) else fn
121
+ except BaseException:
122
+ in_dict[key] = "UNKNOWN for given OS"
123
+
124
+
125
+ def get_system_info() -> OrderedDict:
126
+ """
127
+ Get system info as an ordered dictionary.
128
+ """
129
+ output: OrderedDict = OrderedDict()
130
+
131
+ _dict_append(output, "System", platform.system)
132
+ if output["System"] == "Windows":
133
+ _dict_append(output, "Win32 version", platform.win32_ver)
134
+ if hasattr(platform, "win32_edition"):
135
+ _dict_append(output, "Win32 edition", platform.win32_edition)
136
+
137
+ elif output["System"] == "Darwin":
138
+ _dict_append(output, "Mac version", lambda: platform.mac_ver()[0])
139
+ else:
140
+ with open("/etc/os-release") as rel_f:
141
+ linux_ver = re.search(r'PRETTY_NAME="(.*)"', rel_f.read())
142
+ if linux_ver:
143
+ _dict_append(output, "Linux version", lambda: linux_ver.group(1))
144
+
145
+ _dict_append(output, "Platform", platform.platform)
146
+ _dict_append(output, "Processor", platform.processor)
147
+ _dict_append(output, "Machine", platform.machine)
148
+ _dict_append(output, "Python version", platform.python_version)
149
+
150
+ if not has_psutil:
151
+ _dict_append(output, "`psutil` missing", lambda: "run `pip install monai[psutil]`")
152
+ else:
153
+ p = psutil.Process()
154
+ with p.oneshot():
155
+ _dict_append(output, "Process name", p.name)
156
+ _dict_append(output, "Command", p.cmdline)
157
+ _dict_append(output, "Open files", p.open_files)
158
+ _dict_append(output, "Num physical CPUs", lambda: psutil.cpu_count(logical=False))
159
+ _dict_append(output, "Num logical CPUs", lambda: psutil.cpu_count(logical=True))
160
+ _dict_append(output, "Num usable CPUs", lambda: len(psutil.Process().cpu_affinity()))
161
+ _dict_append(output, "CPU usage (%)", lambda: psutil.cpu_percent(percpu=True))
162
+ _dict_append(output, "CPU freq. (MHz)", lambda: round(psutil.cpu_freq(percpu=False)[0]))
163
+ _dict_append(
164
+ output,
165
+ "Load avg. in last 1, 5, 15 mins (%)",
166
+ lambda: [round(x / psutil.cpu_count() * 100, 1) for x in psutil.getloadavg()],
167
+ )
168
+ _dict_append(output, "Disk usage (%)", lambda: psutil.disk_usage(os.getcwd()).percent)
169
+ _dict_append(
170
+ output,
171
+ "Avg. sensor temp. (Celsius)",
172
+ lambda: np.round(
173
+ np.mean([item.current for sublist in psutil.sensors_temperatures().values() for item in sublist], 1)
174
+ ),
175
+ )
176
+ mem = psutil.virtual_memory()
177
+ _dict_append(output, "Total physical memory (GB)", lambda: round(mem.total / 1024**3, 1))
178
+ _dict_append(output, "Available memory (GB)", lambda: round(mem.available / 1024**3, 1))
179
+ _dict_append(output, "Used memory (GB)", lambda: round(mem.used / 1024**3, 1))
180
+
181
+ return output
182
+
183
+
184
+ def print_system_info(file: TextIO = sys.stdout) -> None:
185
+ """
186
+ Print system info to `file`. Requires the optional library, `psutil`.
187
+
188
+ Args:
189
+ file: `print()` text stream file. Defaults to `sys.stdout`.
190
+ """
191
+ if not has_psutil:
192
+ print("`psutil` required for `print_system_info`", file=file, flush=True)
193
+ else:
194
+ for k, v in get_system_info().items():
195
+ print(f"{k}: {v}", file=file, flush=True)
196
+
197
+
198
+ def get_gpu_info() -> OrderedDict:
199
+ output: OrderedDict = OrderedDict()
200
+
201
+ num_gpus = torch.cuda.device_count()
202
+ _dict_append(output, "Num GPUs", lambda: num_gpus)
203
+
204
+ _dict_append(output, "Has CUDA", lambda: bool(torch.cuda.is_available()))
205
+
206
+ if output["Has CUDA"]:
207
+ _dict_append(output, "CUDA version", lambda: torch.version.cuda)
208
+ cudnn_ver = torch.backends.cudnn.version()
209
+ _dict_append(output, "cuDNN enabled", lambda: bool(cudnn_ver))
210
+ _dict_append(output, "NVIDIA_TF32_OVERRIDE", os.environ.get("NVIDIA_TF32_OVERRIDE"))
211
+ _dict_append(output, "TORCH_ALLOW_TF32_CUBLAS_OVERRIDE", os.environ.get("TORCH_ALLOW_TF32_CUBLAS_OVERRIDE"))
212
+
213
+ if cudnn_ver:
214
+ _dict_append(output, "cuDNN version", lambda: cudnn_ver)
215
+
216
+ if num_gpus > 0:
217
+ _dict_append(output, "Current device", torch.cuda.current_device)
218
+ _dict_append(output, "Library compiled for CUDA architectures", torch.cuda.get_arch_list)
219
+
220
+ for gpu in range(num_gpus):
221
+ gpu_info = torch.cuda.get_device_properties(gpu)
222
+ _dict_append(output, f"GPU {gpu} Name", gpu_info.name)
223
+ _dict_append(output, f"GPU {gpu} Is integrated", bool(gpu_info.is_integrated))
224
+ _dict_append(output, f"GPU {gpu} Is multi GPU board", bool(gpu_info.is_multi_gpu_board))
225
+ _dict_append(output, f"GPU {gpu} Multi processor count", gpu_info.multi_processor_count)
226
+ _dict_append(output, f"GPU {gpu} Total memory (GB)", round(gpu_info.total_memory / 1024**3, 1))
227
+ _dict_append(output, f"GPU {gpu} CUDA capability (maj.min)", f"{gpu_info.major}.{gpu_info.minor}")
228
+
229
+ return output
230
+
231
+
232
+ def print_gpu_info(file: TextIO = sys.stdout) -> None:
233
+ """
234
+ Print GPU info to `file`.
235
+
236
+ Args:
237
+ file: `print()` text stream file. Defaults to `sys.stdout`.
238
+ """
239
+ for k, v in get_gpu_info().items():
240
+ print(f"{k}: {v}", file=file, flush=True)
241
+
242
+
243
+ def print_debug_info(file: TextIO = sys.stdout) -> None:
244
+ """
245
+ Print config (installed dependencies, etc.) and system info for debugging.
246
+
247
+ Args:
248
+ file: `print()` text stream file. Defaults to `sys.stdout`.
249
+ """
250
+ print("================================", file=file, flush=True)
251
+ print("Printing MONAI config...", file=file, flush=True)
252
+ print("================================", file=file, flush=True)
253
+ print_config(file)
254
+ print("\n================================", file=file, flush=True)
255
+ print("Printing system config...")
256
+ print("================================", file=file, flush=True)
257
+ print_system_info(file)
258
+ print("\n================================", file=file, flush=True)
259
+ print("Printing GPU config...")
260
+ print("================================", file=file, flush=True)
261
+ print_gpu_info(file)
262
+
263
+
264
+ class IgniteInfo:
265
+ """
266
+ Config information of the PyTorch ignite package.
267
+
268
+ """
269
+
270
+ OPT_IMPORT_VERSION = "0.4.4"
271
+
272
+
273
+ if __name__ == "__main__":
274
+ print_debug_info()
source_code/SegMamba/monai/config/type_definitions.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from typing import Collection, Hashable, Iterable, Sequence, TypeVar, Union
16
+
17
+ import numpy as np
18
+ import torch
19
+
20
+ # Commonly used concepts
21
+ # This module provides naming and type specifications for commonly used concepts
22
+ # within the MONAI package. The intent is to explicitly identify information
23
+ # that should be used consistently throughout the entire MONAI package.
24
+ #
25
+ # A type would be named as type_definitions.KeysCollection
26
+ # which includes a meaningful name for the consent in the name itself. The
27
+ # definitions in this file map context meaningful names to the underlying
28
+ # object properties that define the expected API.
29
+ #
30
+ # A conceptual type is represented by a new type name but is also one which
31
+ # can be different depending on an environment (i.e. differences for python 3.6 vs 3.9
32
+ # may be implemented). Consistent use of the concept and recorded documentation of
33
+ # the rationale and convention behind it lowers the learning curve for new
34
+ # developers. For readability, short names are preferred.
35
+ __all__ = [
36
+ "KeysCollection",
37
+ "IndexSelection",
38
+ "DtypeLike",
39
+ "NdarrayTensor",
40
+ "NdarrayOrTensor",
41
+ "TensorOrList",
42
+ "PathLike",
43
+ "SequenceStr",
44
+ ]
45
+
46
+ #: KeysCollection
47
+ #
48
+ # The KeyCollection type is used to for defining variables
49
+ # that store a subset of keys to select items from a dictionary.
50
+ # The container of keys must contain hashable elements.
51
+ # NOTE: `Hashable` is not a collection, but is provided as a
52
+ # convenience to end-users. All supplied values will be
53
+ # internally converted to a tuple of `Hashable`'s before
54
+ # use
55
+ KeysCollection = Union[Collection[Hashable], Hashable]
56
+
57
+ #: IndexSelection
58
+ #
59
+ # The IndexSelection type is used to for defining variables
60
+ # that store a subset of indices to select items from a List or Array like objects.
61
+ # The indices must be integers, and if a container of indices is specified, the
62
+ # container must be iterable.
63
+ IndexSelection = Union[Iterable[int], int]
64
+
65
+ #: Type of datatypes: Adapted from https://github.com/numpy/numpy/blob/v1.21.4/numpy/typing/_dtype_like.py#L121
66
+ DtypeLike = Union[np.dtype, type, str, None]
67
+
68
+ #: NdarrayOrTensor: Union of numpy.ndarray and torch.Tensor to be used for typing
69
+ NdarrayOrTensor = Union[np.ndarray, torch.Tensor]
70
+
71
+ #: NdarrayTensor
72
+ #
73
+ # Generic type which can represent either a numpy.ndarray or a torch.Tensor
74
+ # Unlike Union can create a dependence between parameter(s) / return(s)
75
+ NdarrayTensor = TypeVar("NdarrayTensor", bound=NdarrayOrTensor)
76
+
77
+ #: TensorOrList: The TensorOrList type is used for defining `batch-first Tensor` or `list of channel-first Tensor`.
78
+ TensorOrList = Union[torch.Tensor, Sequence[torch.Tensor]]
79
+
80
+ #: PathLike: The PathLike type is used for defining a file path.
81
+ PathLike = Union[str, os.PathLike]
82
+
83
+ #: SequenceStr
84
+ # string or a sequence of strings for `mode` types.
85
+ SequenceStr = Union[Sequence[str], str]
source_code/SegMamba/monai/csrc/ext.cpp ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright (c) MONAI Consortium
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, software
8
+ distributed under the License is distributed on an "AS IS" BASIS,
9
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ See the License for the specific language governing permissions and
11
+ limitations under the License.
12
+ */
13
+
14
+ #include <torch/extension.h>
15
+
16
+ #include "filtering/filtering.h"
17
+ #include "lltm/lltm.h"
18
+ #include "resample/pushpull.h"
19
+ #include "utils/resample_utils.h"
20
+
21
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
22
+ // filtering
23
+ m.def("bilateral_filter", &BilateralFilter, "Bilateral Filter");
24
+ m.def("phl_filter", &PermutohedralFilter, "Permutohedral Filter");
25
+ m.def("tbf_forward", &TrainableBilateralFilterForward, "Trainable Bilateral Filter Forward");
26
+ m.def("tbf_backward", &TrainableBilateralFilterBackward, "Trainable Bilateral Filter Backward");
27
+ m.def("tjbf_forward", &TrainableJointBilateralFilterForward, "Trainable Joint Bilateral Filter Forward");
28
+ m.def("tjbf_backward", &TrainableJointBilateralFilterBackward, "Trainable Joint Bilateral Filter Backward");
29
+
30
+ // lltm
31
+ m.def("lltm_forward", &lltm_forward, "LLTM forward");
32
+ m.def("lltm_backward", &lltm_backward, "LLTM backward");
33
+
34
+ // resample bound mode
35
+ py::enum_<monai::BoundType>(m, "BoundType")
36
+ .value("replicate", monai::BoundType::Replicate, "a a a | a b c d | d d d")
37
+ .value("nearest", monai::BoundType::Replicate, "a a a | a b c d | d d d")
38
+ .value("border", monai::BoundType::Replicate, "a a a | a b c d | d d d")
39
+ .value("dct1", monai::BoundType::DCT1, "d c b | a b c d | c b a")
40
+ .value("mirror", monai::BoundType::DCT1, "d c b | a b c d | c b a")
41
+ .value("dct2", monai::BoundType::DCT2, "c b a | a b c d | d c b")
42
+ .value("reflect", monai::BoundType::DCT2, "c b a | a b c d | d c b")
43
+ .value("dst1", monai::BoundType::DST1, "-b -a 0 | a b c d | 0 -d -c")
44
+ .value("antimirror", monai::BoundType::DST1, "-b -a 0 | a b c d | 0 -d -c")
45
+ .value("dst2", monai::BoundType::DST2, "-c -b -a | a b c d | -d -c -b")
46
+ .value("antireflect", monai::BoundType::DST2, "-c -b -a | a b c d | -d -c -b")
47
+ .value("dft", monai::BoundType::DFT, "b c d | a b c d | a b c")
48
+ .value("wrap", monai::BoundType::DFT, "b c d | a b c d | a b c")
49
+ // .value("sliding", monai::BoundType::Sliding)
50
+ .value("zero", monai::BoundType::Zero, "0 0 0 | a b c d | 0 0 0")
51
+ .value("zeros", monai::BoundType::Zero, "0 0 0 | a b c d | 0 0 0")
52
+ .export_values();
53
+
54
+ // resample interpolation mode
55
+ py::enum_<monai::InterpolationType>(m, "InterpolationType")
56
+ .value("nearest", monai::InterpolationType::Nearest)
57
+ .value("linear", monai::InterpolationType::Linear)
58
+ .value("quadratic", monai::InterpolationType::Quadratic)
59
+ .value("cubic", monai::InterpolationType::Cubic)
60
+ .value("fourth", monai::InterpolationType::FourthOrder)
61
+ .value("fifth", monai::InterpolationType::FifthOrder)
62
+ .value("sixth", monai::InterpolationType::SixthOrder)
63
+ .value("seventh", monai::InterpolationType::SeventhOrder)
64
+ .export_values();
65
+
66
+ // resample
67
+ m.def("grid_pull", &monai::grid_pull, "GridPull");
68
+ m.def("grid_pull_backward", &monai::grid_pull_backward, "GridPull backward");
69
+ m.def("grid_push", &monai::grid_push, "GridPush");
70
+ m.def("grid_push_backward", &monai::grid_push_backward, "GridPush backward");
71
+ m.def("grid_count", &monai::grid_count, "GridCount");
72
+ m.def("grid_count_backward", &monai::grid_count_backward, "GridCount backward");
73
+ m.def("grid_grad", &monai::grid_grad, "GridGrad");
74
+ m.def("grid_grad_backward", &monai::grid_grad_backward, "GridGrad backward");
75
+ }
source_code/SegMamba/monai/engines/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from .evaluator import EnsembleEvaluator, Evaluator, SupervisedEvaluator
15
+ from .trainer import GanTrainer, SupervisedTrainer, Trainer
16
+ from .utils import (
17
+ IterationEvents,
18
+ PrepareBatch,
19
+ PrepareBatchDefault,
20
+ PrepareBatchExtraInput,
21
+ default_make_latent,
22
+ default_metric_cmp_fn,
23
+ default_prepare_batch,
24
+ engine_apply_transform,
25
+ get_devices_spec,
26
+ )
27
+ from .workflow import Workflow
source_code/SegMamba/monai/engines/evaluator.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import warnings
15
+ from typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence
16
+
17
+ import torch
18
+ from torch.utils.data import DataLoader
19
+
20
+ from monai.config import IgniteInfo, KeysCollection
21
+ from monai.data import MetaTensor
22
+ from monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batch
23
+ from monai.engines.workflow import Workflow
24
+ from monai.inferers import Inferer, SimpleInferer
25
+ from monai.networks.utils import eval_mode, train_mode
26
+ from monai.transforms import Transform
27
+ from monai.utils import ForwardMode, ensure_tuple, min_version, optional_import
28
+ from monai.utils.enums import CommonKeys as Keys
29
+ from monai.utils.enums import EngineStatsKeys as ESKeys
30
+ from monai.utils.module import look_up_option, pytorch_after
31
+
32
+ if TYPE_CHECKING:
33
+ from ignite.engine import Engine, EventEnum
34
+ from ignite.metrics import Metric
35
+ else:
36
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
37
+ Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric")
38
+ EventEnum, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum")
39
+
40
+ __all__ = ["Evaluator", "SupervisedEvaluator", "EnsembleEvaluator"]
41
+
42
+
43
+ class Evaluator(Workflow):
44
+ """
45
+ Base class for all kinds of evaluators, inherits from Workflow.
46
+
47
+ Args:
48
+ device: an object representing the device on which to run.
49
+ val_data_loader: Ignite engine use data_loader to run, must be Iterable or torch.DataLoader.
50
+ epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`.
51
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
52
+ with respect to the host. For other cases, this argument has no effect.
53
+ prepare_batch: function to parse expected data (usually `image`, `label` and other network args)
54
+ from `engine.state.batch` for every iteration, for more details please refer to:
55
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
56
+ iteration_update: the callable function for every iteration, expect to accept `engine`
57
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
58
+ if not provided, use `self._iteration()` instead. for more details please refer to:
59
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
60
+ postprocessing: execute additional transformation for the model output data.
61
+ Typically, several Tensor based transforms composed by `Compose`.
62
+ key_val_metric: compute metric when every iteration completed, and save average value to
63
+ engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the
64
+ checkpoint into files.
65
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
66
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
67
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
68
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
69
+ val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
70
+ CheckpointHandler, StatsHandler, etc.
71
+ amp: whether to enable auto-mixed-precision evaluation, default is False.
72
+ mode: model forward mode during evaluation, should be 'eval' or 'train',
73
+ which maps to `model.eval()` or `model.train()`, default to 'eval'.
74
+ event_names: additional custom ignite events that will register to the engine.
75
+ new events can be a list of str or `ignite.engine.events.EventEnum`.
76
+ event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`.
77
+ for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html
78
+ #ignite.engine.engine.Engine.register_events.
79
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
80
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
81
+ default to `True`.
82
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
83
+ `device`, `non_blocking`.
84
+ amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details:
85
+ https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast.
86
+
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ device: torch.device | str,
92
+ val_data_loader: Iterable | DataLoader,
93
+ epoch_length: int | None = None,
94
+ non_blocking: bool = False,
95
+ prepare_batch: Callable = default_prepare_batch,
96
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
97
+ postprocessing: Transform | None = None,
98
+ key_val_metric: dict[str, Metric] | None = None,
99
+ additional_metrics: dict[str, Metric] | None = None,
100
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
101
+ val_handlers: Sequence | None = None,
102
+ amp: bool = False,
103
+ mode: ForwardMode | str = ForwardMode.EVAL,
104
+ event_names: list[str | EventEnum | type[EventEnum]] | None = None,
105
+ event_to_attr: dict | None = None,
106
+ decollate: bool = True,
107
+ to_kwargs: dict | None = None,
108
+ amp_kwargs: dict | None = None,
109
+ ) -> None:
110
+ super().__init__(
111
+ device=device,
112
+ max_epochs=1,
113
+ data_loader=val_data_loader,
114
+ epoch_length=epoch_length,
115
+ non_blocking=non_blocking,
116
+ prepare_batch=prepare_batch,
117
+ iteration_update=iteration_update,
118
+ postprocessing=postprocessing,
119
+ key_metric=key_val_metric,
120
+ additional_metrics=additional_metrics,
121
+ metric_cmp_fn=metric_cmp_fn,
122
+ handlers=val_handlers,
123
+ amp=amp,
124
+ event_names=event_names,
125
+ event_to_attr=event_to_attr,
126
+ decollate=decollate,
127
+ to_kwargs=to_kwargs,
128
+ amp_kwargs=amp_kwargs,
129
+ )
130
+ mode = look_up_option(mode, ForwardMode)
131
+ if mode == ForwardMode.EVAL:
132
+ self.mode = eval_mode
133
+ elif mode == ForwardMode.TRAIN:
134
+ self.mode = train_mode
135
+ else:
136
+ raise ValueError(f"unsupported mode: {mode}, should be 'eval' or 'train'.")
137
+
138
+ def run(self, global_epoch: int = 1) -> None: # type: ignore[override]
139
+ """
140
+ Execute validation/evaluation based on Ignite Engine.
141
+
142
+ Args:
143
+ global_epoch: the overall epoch if during a training. evaluator engine can get it from trainer.
144
+
145
+ """
146
+ # init env value for current validation process
147
+ self.state.max_epochs = max(global_epoch, 1) # at least one epoch of validation
148
+ self.state.epoch = global_epoch - 1
149
+ self.state.iteration = 0
150
+ super().run()
151
+
152
+ def get_stats(self, *vars):
153
+ """
154
+ Get the statistics information of the validation process.
155
+ Default to return the `rank`, `best_validation_epoch` and `best_validation_metric`.
156
+
157
+ Args:
158
+ vars: except for the default stats, other variables name in the `self.state` to return,
159
+ will use the variable name as the key and the state content as the value.
160
+ if the variable doesn't exist, default value is `None`.
161
+
162
+ """
163
+ stats = {
164
+ ESKeys.RANK: self.state.rank,
165
+ ESKeys.BEST_VALIDATION_EPOCH: self.state.best_metric_epoch,
166
+ ESKeys.BEST_VALIDATION_METRIC: self.state.best_metric,
167
+ }
168
+ for k in vars:
169
+ stats[k] = getattr(self.state, k, None)
170
+ return stats
171
+
172
+
173
+ class SupervisedEvaluator(Evaluator):
174
+ """
175
+ Standard supervised evaluation method with image and label(optional), inherits from evaluator and Workflow.
176
+
177
+ Args:
178
+ device: an object representing the device on which to run.
179
+ val_data_loader: Ignite engine use data_loader to run, must be Iterable, typically be torch.DataLoader.
180
+ network: network to evaluate in the evaluator, should be regular PyTorch `torch.nn.Module`.
181
+ epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`.
182
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
183
+ with respect to the host. For other cases, this argument has no effect.
184
+ prepare_batch: function to parse expected data (usually `image`, `label` and other network args)
185
+ from `engine.state.batch` for every iteration, for more details please refer to:
186
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
187
+ iteration_update: the callable function for every iteration, expect to accept `engine`
188
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
189
+ if not provided, use `self._iteration()` instead. for more details please refer to:
190
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
191
+ inferer: inference method that execute model forward on input data, like: SlidingWindow, etc.
192
+ postprocessing: execute additional transformation for the model output data.
193
+ Typically, several Tensor based transforms composed by `Compose`.
194
+ key_val_metric: compute metric when every iteration completed, and save average value to
195
+ engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the
196
+ checkpoint into files.
197
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
198
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
199
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
200
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
201
+ val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
202
+ CheckpointHandler, StatsHandler, etc.
203
+ amp: whether to enable auto-mixed-precision evaluation, default is False.
204
+ mode: model forward mode during evaluation, should be 'eval' or 'train',
205
+ which maps to `model.eval()` or `model.train()`, default to 'eval'.
206
+ event_names: additional custom ignite events that will register to the engine.
207
+ new events can be a list of str or `ignite.engine.events.EventEnum`.
208
+ event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`.
209
+ for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html
210
+ #ignite.engine.engine.Engine.register_events.
211
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
212
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
213
+ default to `True`.
214
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
215
+ `device`, `non_blocking`.
216
+ amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details:
217
+ https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast.
218
+ compile: whether to use `torch.compile`, default is False. If True, MetaTensor inputs will be converted to
219
+ `torch.Tensor` before forward pass, then converted back afterward with copied meta information.
220
+ compile_kwargs: dict of the args for `torch.compile()` API, for more details:
221
+ https://pytorch.org/docs/stable/generated/torch.compile.html#torch-compile.
222
+
223
+ """
224
+
225
+ def __init__(
226
+ self,
227
+ device: torch.device,
228
+ val_data_loader: Iterable | DataLoader,
229
+ network: torch.nn.Module,
230
+ epoch_length: int | None = None,
231
+ non_blocking: bool = False,
232
+ prepare_batch: Callable = default_prepare_batch,
233
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
234
+ inferer: Inferer | None = None,
235
+ postprocessing: Transform | None = None,
236
+ key_val_metric: dict[str, Metric] | None = None,
237
+ additional_metrics: dict[str, Metric] | None = None,
238
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
239
+ val_handlers: Sequence | None = None,
240
+ amp: bool = False,
241
+ mode: ForwardMode | str = ForwardMode.EVAL,
242
+ event_names: list[str | EventEnum | type[EventEnum]] | None = None,
243
+ event_to_attr: dict | None = None,
244
+ decollate: bool = True,
245
+ to_kwargs: dict | None = None,
246
+ amp_kwargs: dict | None = None,
247
+ compile: bool = False,
248
+ compile_kwargs: dict | None = None,
249
+ ) -> None:
250
+ super().__init__(
251
+ device=device,
252
+ val_data_loader=val_data_loader,
253
+ epoch_length=epoch_length,
254
+ non_blocking=non_blocking,
255
+ prepare_batch=prepare_batch,
256
+ iteration_update=iteration_update,
257
+ postprocessing=postprocessing,
258
+ key_val_metric=key_val_metric,
259
+ additional_metrics=additional_metrics,
260
+ metric_cmp_fn=metric_cmp_fn,
261
+ val_handlers=val_handlers,
262
+ amp=amp,
263
+ mode=mode,
264
+ event_names=event_names,
265
+ event_to_attr=event_to_attr,
266
+ decollate=decollate,
267
+ to_kwargs=to_kwargs,
268
+ amp_kwargs=amp_kwargs,
269
+ )
270
+ if compile:
271
+ if pytorch_after(2, 1):
272
+ compile_kwargs = {} if compile_kwargs is None else compile_kwargs
273
+ network = torch.compile(network, **compile_kwargs) # type: ignore[assignment]
274
+ else:
275
+ warnings.warn(
276
+ "Network compilation (compile=True) not supported for Pytorch versions before 2.1, no compilation done"
277
+ )
278
+ self.network = network
279
+ self.compile = compile
280
+ self.inferer = SimpleInferer() if inferer is None else inferer
281
+
282
+ def _iteration(self, engine: SupervisedEvaluator, batchdata: dict[str, torch.Tensor]) -> dict:
283
+ """
284
+ callback function for the Supervised Evaluation processing logic of 1 iteration in Ignite Engine.
285
+ Return below items in a dictionary:
286
+ - IMAGE: image Tensor data for model input, already moved to device.
287
+ - LABEL: label Tensor data corresponding to the image, already moved to device.
288
+ - PRED: prediction result of model.
289
+
290
+ Args:
291
+ engine: `SupervisedEvaluator` to execute operation for an iteration.
292
+ batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data.
293
+
294
+ Raises:
295
+ ValueError: When ``batchdata`` is None.
296
+
297
+ """
298
+ if batchdata is None:
299
+ raise ValueError("Must provide batch data for current iteration.")
300
+ batch = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs)
301
+ if len(batch) == 2:
302
+ inputs, targets = batch
303
+ args: tuple = ()
304
+ kwargs: dict = {}
305
+ else:
306
+ inputs, targets, args, kwargs = batch
307
+ # FIXME: workaround for https://github.com/pytorch/pytorch/issues/117026
308
+ if self.compile:
309
+ inputs_meta, targets_meta, inputs_applied_operations, targets_applied_operations = None, None, None, None
310
+ if isinstance(inputs, MetaTensor):
311
+ warnings.warn(
312
+ "Will convert to PyTorch Tensor if using compile, and casting back to MetaTensor after the forward pass."
313
+ )
314
+ inputs, inputs_meta, inputs_applied_operations = (
315
+ inputs.as_tensor(),
316
+ inputs.meta,
317
+ inputs.applied_operations,
318
+ )
319
+ if isinstance(targets, MetaTensor):
320
+ targets, targets_meta, targets_applied_operations = (
321
+ targets.as_tensor(),
322
+ targets.meta,
323
+ targets.applied_operations,
324
+ )
325
+
326
+ # put iteration outputs into engine.state
327
+ engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: targets}
328
+ # execute forward computation
329
+ with engine.mode(engine.network):
330
+ if engine.amp:
331
+ with torch.cuda.amp.autocast(**engine.amp_kwargs):
332
+ engine.state.output[Keys.PRED] = engine.inferer(inputs, engine.network, *args, **kwargs)
333
+ else:
334
+ engine.state.output[Keys.PRED] = engine.inferer(inputs, engine.network, *args, **kwargs)
335
+ # copy back meta info
336
+ if self.compile:
337
+ if inputs_meta is not None:
338
+ engine.state.output[Keys.IMAGE] = MetaTensor(
339
+ inputs, meta=inputs_meta, applied_operations=inputs_applied_operations
340
+ )
341
+ engine.state.output[Keys.PRED] = MetaTensor(
342
+ engine.state.output[Keys.PRED], meta=inputs_meta, applied_operations=inputs_applied_operations
343
+ )
344
+ if targets_meta is not None:
345
+ engine.state.output[Keys.LABEL] = MetaTensor(
346
+ targets, meta=targets_meta, applied_operations=targets_applied_operations
347
+ )
348
+ engine.fire_event(IterationEvents.FORWARD_COMPLETED)
349
+ engine.fire_event(IterationEvents.MODEL_COMPLETED)
350
+
351
+ return engine.state.output
352
+
353
+
354
+ class EnsembleEvaluator(Evaluator):
355
+ """
356
+ Ensemble evaluation for multiple models, inherits from evaluator and Workflow.
357
+ It accepts a list of models for inference and outputs a list of predictions for further operations.
358
+
359
+ Args:
360
+ device: an object representing the device on which to run.
361
+ val_data_loader: Ignite engine use data_loader to run, must be Iterable, typically be torch.DataLoader.
362
+ epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`.
363
+ networks: networks to evaluate in order in the evaluator, should be regular PyTorch `torch.nn.Module`.
364
+ pred_keys: the keys to store every prediction data.
365
+ the length must exactly match the number of networks.
366
+ if None, use "pred_{index}" as key corresponding to N networks, index from `0` to `N-1`.
367
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
368
+ with respect to the host. For other cases, this argument has no effect.
369
+ prepare_batch: function to parse expected data (usually `image`, `label` and other network args)
370
+ from `engine.state.batch` for every iteration, for more details please refer to:
371
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
372
+ iteration_update: the callable function for every iteration, expect to accept `engine`
373
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
374
+ if not provided, use `self._iteration()` instead. for more details please refer to:
375
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
376
+ inferer: inference method that execute model forward on input data, like: SlidingWindow, etc.
377
+ postprocessing: execute additional transformation for the model output data.
378
+ Typically, several Tensor based transforms composed by `Compose`.
379
+ key_val_metric: compute metric when every iteration completed, and save average value to
380
+ engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the
381
+ checkpoint into files.
382
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
383
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
384
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
385
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
386
+ val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
387
+ CheckpointHandler, StatsHandler, etc.
388
+ amp: whether to enable auto-mixed-precision evaluation, default is False.
389
+ mode: model forward mode during evaluation, should be 'eval' or 'train',
390
+ which maps to `model.eval()` or `model.train()`, default to 'eval'.
391
+ event_names: additional custom ignite events that will register to the engine.
392
+ new events can be a list of str or `ignite.engine.events.EventEnum`.
393
+ event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`.
394
+ for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html
395
+ #ignite.engine.engine.Engine.register_events.
396
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
397
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
398
+ default to `True`.
399
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
400
+ `device`, `non_blocking`.
401
+ amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details:
402
+ https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast.
403
+
404
+ """
405
+
406
+ def __init__(
407
+ self,
408
+ device: torch.device,
409
+ val_data_loader: Iterable | DataLoader,
410
+ networks: Sequence[torch.nn.Module],
411
+ pred_keys: KeysCollection | None = None,
412
+ epoch_length: int | None = None,
413
+ non_blocking: bool = False,
414
+ prepare_batch: Callable = default_prepare_batch,
415
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
416
+ inferer: Inferer | None = None,
417
+ postprocessing: Transform | None = None,
418
+ key_val_metric: dict[str, Metric] | None = None,
419
+ additional_metrics: dict[str, Metric] | None = None,
420
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
421
+ val_handlers: Sequence | None = None,
422
+ amp: bool = False,
423
+ mode: ForwardMode | str = ForwardMode.EVAL,
424
+ event_names: list[str | EventEnum | type[EventEnum]] | None = None,
425
+ event_to_attr: dict | None = None,
426
+ decollate: bool = True,
427
+ to_kwargs: dict | None = None,
428
+ amp_kwargs: dict | None = None,
429
+ ) -> None:
430
+ super().__init__(
431
+ device=device,
432
+ val_data_loader=val_data_loader,
433
+ epoch_length=epoch_length,
434
+ non_blocking=non_blocking,
435
+ prepare_batch=prepare_batch,
436
+ iteration_update=iteration_update,
437
+ postprocessing=postprocessing,
438
+ key_val_metric=key_val_metric,
439
+ additional_metrics=additional_metrics,
440
+ metric_cmp_fn=metric_cmp_fn,
441
+ val_handlers=val_handlers,
442
+ amp=amp,
443
+ mode=mode,
444
+ event_names=event_names,
445
+ event_to_attr=event_to_attr,
446
+ decollate=decollate,
447
+ to_kwargs=to_kwargs,
448
+ amp_kwargs=amp_kwargs,
449
+ )
450
+
451
+ self.networks = ensure_tuple(networks)
452
+ self.pred_keys = (
453
+ [f"{Keys.PRED}_{i}" for i in range(len(self.networks))] if pred_keys is None else ensure_tuple(pred_keys)
454
+ )
455
+ if len(self.pred_keys) != len(self.networks):
456
+ raise ValueError("length of `pred_keys` must be same as the length of `networks`.")
457
+ self.inferer = SimpleInferer() if inferer is None else inferer
458
+
459
+ def _iteration(self, engine: EnsembleEvaluator, batchdata: dict[str, torch.Tensor]) -> dict:
460
+ """
461
+ callback function for the Supervised Evaluation processing logic of 1 iteration in Ignite Engine.
462
+ Return below items in a dictionary:
463
+ - IMAGE: image Tensor data for model input, already moved to device.
464
+ - LABEL: label Tensor data corresponding to the image, already moved to device.
465
+ - pred_keys[0]: prediction result of network 0.
466
+ - pred_keys[1]: prediction result of network 1.
467
+ - ... ...
468
+ - pred_keys[N]: prediction result of network N.
469
+
470
+ Args:
471
+ engine: `EnsembleEvaluator` to execute operation for an iteration.
472
+ batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data.
473
+
474
+ Raises:
475
+ ValueError: When ``batchdata`` is None.
476
+
477
+ """
478
+ if batchdata is None:
479
+ raise ValueError("Must provide batch data for current iteration.")
480
+ batch = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs)
481
+ if len(batch) == 2:
482
+ inputs, targets = batch
483
+ args: tuple = ()
484
+ kwargs: dict = {}
485
+ else:
486
+ inputs, targets, args, kwargs = batch
487
+
488
+ # put iteration outputs into engine.state
489
+ engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: targets}
490
+
491
+ for idx, network in enumerate(engine.networks):
492
+ with engine.mode(network):
493
+ if engine.amp:
494
+ with torch.cuda.amp.autocast(**engine.amp_kwargs):
495
+ if isinstance(engine.state.output, dict):
496
+ engine.state.output.update(
497
+ {engine.pred_keys[idx]: engine.inferer(inputs, network, *args, **kwargs)}
498
+ )
499
+ else:
500
+ if isinstance(engine.state.output, dict):
501
+ engine.state.output.update(
502
+ {engine.pred_keys[idx]: engine.inferer(inputs, network, *args, **kwargs)}
503
+ )
504
+ engine.fire_event(IterationEvents.FORWARD_COMPLETED)
505
+ engine.fire_event(IterationEvents.MODEL_COMPLETED)
506
+
507
+ return engine.state.output
source_code/SegMamba/monai/engines/trainer.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import warnings
15
+ from typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence
16
+
17
+ import torch
18
+ from torch.optim.optimizer import Optimizer
19
+ from torch.utils.data import DataLoader
20
+
21
+ from monai.config import IgniteInfo
22
+ from monai.data import MetaTensor
23
+ from monai.engines.utils import IterationEvents, default_make_latent, default_metric_cmp_fn, default_prepare_batch
24
+ from monai.engines.workflow import Workflow
25
+ from monai.inferers import Inferer, SimpleInferer
26
+ from monai.transforms import Transform
27
+ from monai.utils import GanKeys, min_version, optional_import
28
+ from monai.utils.enums import CommonKeys as Keys
29
+ from monai.utils.enums import EngineStatsKeys as ESKeys
30
+ from monai.utils.module import pytorch_after
31
+
32
+ if TYPE_CHECKING:
33
+ from ignite.engine import Engine, EventEnum
34
+ from ignite.metrics import Metric
35
+ else:
36
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
37
+ Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric")
38
+ EventEnum, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum")
39
+
40
+ __all__ = ["Trainer", "SupervisedTrainer", "GanTrainer"]
41
+
42
+
43
+ class Trainer(Workflow):
44
+ """
45
+ Base class for all kinds of trainers, inherits from Workflow.
46
+
47
+ """
48
+
49
+ def run(self) -> None: # type: ignore[override]
50
+ """
51
+ Execute training based on Ignite Engine.
52
+ If call this function multiple times, it will continuously run from the previous state.
53
+
54
+ """
55
+ self.scaler = torch.cuda.amp.GradScaler() if self.amp else None
56
+ super().run()
57
+
58
+ def get_stats(self, *vars):
59
+ """
60
+ Get the statistics information of the training process.
61
+ Default to return the `rank`, `current_epoch`, `current_iteration`, `total_epochs`, `total_iterations`.
62
+
63
+ Args:
64
+ vars: except for the default stats, other variables name in the `self.state` to return,
65
+ will use the variable name as the key and the state content as the value.
66
+ if the variable doesn't exist, default value is `None`.
67
+
68
+ """
69
+ stats = {
70
+ ESKeys.RANK: self.state.rank,
71
+ ESKeys.CURRENT_EPOCH: self.state.epoch,
72
+ ESKeys.CURRENT_ITERATION: self.state.iteration,
73
+ ESKeys.TOTAL_EPOCHS: self.state.max_epochs,
74
+ ESKeys.TOTAL_ITERATIONS: self.state.epoch_length,
75
+ }
76
+ for k in vars:
77
+ stats[k] = getattr(self.state, k, None)
78
+ return stats
79
+
80
+
81
+ class SupervisedTrainer(Trainer):
82
+ """
83
+ Standard supervised training method with image and label, inherits from ``Trainer`` and ``Workflow``.
84
+
85
+ Args:
86
+ device: an object representing the device on which to run.
87
+ max_epochs: the total epoch number for trainer to run.
88
+ train_data_loader: Ignite engine use data_loader to run, must be Iterable or torch.DataLoader.
89
+ network: network to train in the trainer, should be regular PyTorch `torch.nn.Module`.
90
+ optimizer: the optimizer associated to the network, should be regular PyTorch optimizer from `torch.optim`
91
+ or its subclass.
92
+ loss_function: the loss function associated to the optimizer, should be regular PyTorch loss,
93
+ which inherit from `torch.nn.modules.loss`.
94
+ epoch_length: number of iterations for one epoch, default to `len(train_data_loader)`.
95
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
96
+ with respect to the host. For other cases, this argument has no effect.
97
+ prepare_batch: function to parse expected data (usually `image`, `label` and other network args)
98
+ from `engine.state.batch` for every iteration, for more details please refer to:
99
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
100
+ iteration_update: the callable function for every iteration, expect to accept `engine`
101
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
102
+ if not provided, use `self._iteration()` instead. for more details please refer to:
103
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
104
+ inferer: inference method that execute model forward on input data, like: SlidingWindow, etc.
105
+ postprocessing: execute additional transformation for the model output data.
106
+ Typically, several Tensor based transforms composed by `Compose`.
107
+ key_train_metric: compute metric when every iteration completed, and save average value to
108
+ engine.state.metrics when epoch completed. key_train_metric is the main metric to compare and save the
109
+ checkpoint into files.
110
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
111
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
112
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
113
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
114
+ train_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
115
+ CheckpointHandler, StatsHandler, etc.
116
+ amp: whether to enable auto-mixed-precision training, default is False.
117
+ event_names: additional custom ignite events that will register to the engine.
118
+ new events can be a list of str or `ignite.engine.events.EventEnum`.
119
+ event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`.
120
+ for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html
121
+ #ignite.engine.engine.Engine.register_events.
122
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
123
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
124
+ default to `True`.
125
+ optim_set_to_none: when calling `optimizer.zero_grad()`, instead of setting to zero, set the grads to None.
126
+ more details: https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html.
127
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
128
+ `device`, `non_blocking`.
129
+ amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details:
130
+ https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast.
131
+ compile: whether to use `torch.compile`, default is False. If True, MetaTensor inputs will be converted to
132
+ `torch.Tensor` before forward pass, then converted back afterward with copied meta information.
133
+ compile_kwargs: dict of the args for `torch.compile()` API, for more details:
134
+ https://pytorch.org/docs/stable/generated/torch.compile.html#torch-compile.
135
+ """
136
+
137
+ def __init__(
138
+ self,
139
+ device: str | torch.device,
140
+ max_epochs: int,
141
+ train_data_loader: Iterable | DataLoader,
142
+ network: torch.nn.Module,
143
+ optimizer: Optimizer,
144
+ loss_function: Callable,
145
+ epoch_length: int | None = None,
146
+ non_blocking: bool = False,
147
+ prepare_batch: Callable = default_prepare_batch,
148
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
149
+ inferer: Inferer | None = None,
150
+ postprocessing: Transform | None = None,
151
+ key_train_metric: dict[str, Metric] | None = None,
152
+ additional_metrics: dict[str, Metric] | None = None,
153
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
154
+ train_handlers: Sequence | None = None,
155
+ amp: bool = False,
156
+ event_names: list[str | EventEnum | type[EventEnum]] | None = None,
157
+ event_to_attr: dict | None = None,
158
+ decollate: bool = True,
159
+ optim_set_to_none: bool = False,
160
+ to_kwargs: dict | None = None,
161
+ amp_kwargs: dict | None = None,
162
+ compile: bool = False,
163
+ compile_kwargs: dict | None = None,
164
+ ) -> None:
165
+ super().__init__(
166
+ device=device,
167
+ max_epochs=max_epochs,
168
+ data_loader=train_data_loader,
169
+ epoch_length=epoch_length,
170
+ non_blocking=non_blocking,
171
+ prepare_batch=prepare_batch,
172
+ iteration_update=iteration_update,
173
+ postprocessing=postprocessing,
174
+ key_metric=key_train_metric,
175
+ additional_metrics=additional_metrics,
176
+ metric_cmp_fn=metric_cmp_fn,
177
+ handlers=train_handlers,
178
+ amp=amp,
179
+ event_names=event_names,
180
+ event_to_attr=event_to_attr,
181
+ decollate=decollate,
182
+ to_kwargs=to_kwargs,
183
+ amp_kwargs=amp_kwargs,
184
+ )
185
+ if compile:
186
+ if pytorch_after(2, 1):
187
+ compile_kwargs = {} if compile_kwargs is None else compile_kwargs
188
+ network = torch.compile(network, **compile_kwargs) # type: ignore[assignment]
189
+ else:
190
+ warnings.warn(
191
+ "Network compilation (compile=True) not supported for Pytorch versions before 2.1, no compilation done"
192
+ )
193
+ self.network = network
194
+ self.compile = compile
195
+ self.optimizer = optimizer
196
+ self.loss_function = loss_function
197
+ self.inferer = SimpleInferer() if inferer is None else inferer
198
+ self.optim_set_to_none = optim_set_to_none
199
+
200
+ def _iteration(self, engine: SupervisedTrainer, batchdata: dict[str, torch.Tensor]) -> dict:
201
+ """
202
+ Callback function for the Supervised Training processing logic of 1 iteration in Ignite Engine.
203
+ Return below items in a dictionary:
204
+ - IMAGE: image Tensor data for model input, already moved to device.
205
+ - LABEL: label Tensor data corresponding to the image, already moved to device.
206
+ - PRED: prediction result of model.
207
+ - LOSS: loss value computed by loss function.
208
+
209
+ Args:
210
+ engine: `SupervisedTrainer` to execute operation for an iteration.
211
+ batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data.
212
+
213
+ Raises:
214
+ ValueError: When ``batchdata`` is None.
215
+
216
+ """
217
+ if batchdata is None:
218
+ raise ValueError("Must provide batch data for current iteration.")
219
+ batch = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs)
220
+ if len(batch) == 2:
221
+ inputs, targets = batch
222
+ args: tuple = ()
223
+ kwargs: dict = {}
224
+ else:
225
+ inputs, targets, args, kwargs = batch
226
+ # FIXME: workaround for https://github.com/pytorch/pytorch/issues/117026
227
+ if self.compile:
228
+ inputs_meta, targets_meta, inputs_applied_operations, targets_applied_operations = None, None, None, None
229
+ if isinstance(inputs, MetaTensor):
230
+ warnings.warn(
231
+ "Will convert to PyTorch Tensor if using compile, and casting back to MetaTensor after the forward pass."
232
+ )
233
+ inputs, inputs_meta, inputs_applied_operations = (
234
+ inputs.as_tensor(),
235
+ inputs.meta,
236
+ inputs.applied_operations,
237
+ )
238
+ if isinstance(targets, MetaTensor):
239
+ targets, targets_meta, targets_applied_operations = (
240
+ targets.as_tensor(),
241
+ targets.meta,
242
+ targets.applied_operations,
243
+ )
244
+
245
+ # put iteration outputs into engine.state
246
+ engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: targets}
247
+
248
+ def _compute_pred_loss():
249
+ engine.state.output[Keys.PRED] = engine.inferer(inputs, engine.network, *args, **kwargs)
250
+ engine.fire_event(IterationEvents.FORWARD_COMPLETED)
251
+ engine.state.output[Keys.LOSS] = engine.loss_function(engine.state.output[Keys.PRED], targets).mean()
252
+ engine.fire_event(IterationEvents.LOSS_COMPLETED)
253
+
254
+ engine.network.train()
255
+ engine.optimizer.zero_grad(set_to_none=engine.optim_set_to_none)
256
+
257
+ if engine.amp and engine.scaler is not None:
258
+ with torch.cuda.amp.autocast(**engine.amp_kwargs):
259
+ _compute_pred_loss()
260
+ engine.scaler.scale(engine.state.output[Keys.LOSS]).backward()
261
+ engine.fire_event(IterationEvents.BACKWARD_COMPLETED)
262
+ engine.scaler.step(engine.optimizer)
263
+ engine.scaler.update()
264
+ else:
265
+ _compute_pred_loss()
266
+ engine.state.output[Keys.LOSS].backward()
267
+ engine.fire_event(IterationEvents.BACKWARD_COMPLETED)
268
+ engine.optimizer.step()
269
+ # copy back meta info
270
+ if self.compile:
271
+ if inputs_meta is not None:
272
+ engine.state.output[Keys.IMAGE] = MetaTensor(
273
+ inputs, meta=inputs_meta, applied_operations=inputs_applied_operations
274
+ )
275
+ engine.state.output[Keys.PRED] = MetaTensor(
276
+ engine.state.output[Keys.PRED], meta=inputs_meta, applied_operations=inputs_applied_operations
277
+ )
278
+ if targets_meta is not None:
279
+ engine.state.output[Keys.LABEL] = MetaTensor(
280
+ targets, meta=targets_meta, applied_operations=targets_applied_operations
281
+ )
282
+ engine.fire_event(IterationEvents.MODEL_COMPLETED)
283
+
284
+ return engine.state.output
285
+
286
+
287
+ class GanTrainer(Trainer):
288
+ """
289
+ Generative adversarial network training based on Goodfellow et al. 2014 https://arxiv.org/abs/1406.266,
290
+ inherits from ``Trainer`` and ``Workflow``.
291
+
292
+ Training Loop: for each batch of data size `m`
293
+ 1. Generate `m` fakes from random latent codes.
294
+ 2. Update discriminator with these fakes and current batch reals, repeated d_train_steps times.
295
+ 3. If g_update_latents, generate `m` fakes from new random latent codes.
296
+ 4. Update generator with these fakes using discriminator feedback.
297
+
298
+ Args:
299
+ device: an object representing the device on which to run.
300
+ max_epochs: the total epoch number for engine to run.
301
+ train_data_loader: Core ignite engines uses `DataLoader` for training loop batchdata.
302
+ g_network: generator (G) network architecture.
303
+ g_optimizer: G optimizer function.
304
+ g_loss_function: G loss function for optimizer.
305
+ d_network: discriminator (D) network architecture.
306
+ d_optimizer: D optimizer function.
307
+ d_loss_function: D loss function for optimizer.
308
+ epoch_length: number of iterations for one epoch, default to `len(train_data_loader)`.
309
+ g_inferer: inference method to execute G model forward. Defaults to ``SimpleInferer()``.
310
+ d_inferer: inference method to execute D model forward. Defaults to ``SimpleInferer()``.
311
+ d_train_steps: number of times to update D with real data minibatch. Defaults to ``1``.
312
+ latent_shape: size of G input latent code. Defaults to ``64``.
313
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
314
+ with respect to the host. For other cases, this argument has no effect.
315
+ d_prepare_batch: callback function to prepare batchdata for D inferer.
316
+ Defaults to return ``GanKeys.REALS`` in batchdata dict. for more details please refer to:
317
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
318
+ g_prepare_batch: callback function to create batch of latent input for G inferer.
319
+ Defaults to return random latents. for more details please refer to:
320
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
321
+ g_update_latents: Calculate G loss with new latent codes. Defaults to ``True``.
322
+ iteration_update: the callable function for every iteration, expect to accept `engine`
323
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
324
+ if not provided, use `self._iteration()` instead. for more details please refer to:
325
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
326
+ postprocessing: execute additional transformation for the model output data.
327
+ Typically, several Tensor based transforms composed by `Compose`.
328
+ key_train_metric: compute metric when every iteration completed, and save average value to
329
+ engine.state.metrics when epoch completed. key_train_metric is the main metric to compare and save the
330
+ checkpoint into files.
331
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
332
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
333
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
334
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
335
+ train_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
336
+ CheckpointHandler, StatsHandler, etc.
337
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
338
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
339
+ default to `True`.
340
+ optim_set_to_none: when calling `optimizer.zero_grad()`, instead of setting to zero, set the grads to None.
341
+ more details: https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html.
342
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
343
+ `device`, `non_blocking`.
344
+ amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details:
345
+ https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast.
346
+
347
+ """
348
+
349
+ def __init__(
350
+ self,
351
+ device: str | torch.device,
352
+ max_epochs: int,
353
+ train_data_loader: DataLoader,
354
+ g_network: torch.nn.Module,
355
+ g_optimizer: Optimizer,
356
+ g_loss_function: Callable,
357
+ d_network: torch.nn.Module,
358
+ d_optimizer: Optimizer,
359
+ d_loss_function: Callable,
360
+ epoch_length: int | None = None,
361
+ g_inferer: Inferer | None = None,
362
+ d_inferer: Inferer | None = None,
363
+ d_train_steps: int = 1,
364
+ latent_shape: int = 64,
365
+ non_blocking: bool = False,
366
+ d_prepare_batch: Callable = default_prepare_batch,
367
+ g_prepare_batch: Callable = default_make_latent,
368
+ g_update_latents: bool = True,
369
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
370
+ postprocessing: Transform | None = None,
371
+ key_train_metric: dict[str, Metric] | None = None,
372
+ additional_metrics: dict[str, Metric] | None = None,
373
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
374
+ train_handlers: Sequence | None = None,
375
+ decollate: bool = True,
376
+ optim_set_to_none: bool = False,
377
+ to_kwargs: dict | None = None,
378
+ amp_kwargs: dict | None = None,
379
+ ):
380
+ if not isinstance(train_data_loader, DataLoader):
381
+ raise ValueError("train_data_loader must be PyTorch DataLoader.")
382
+
383
+ # set up Ignite engine and environments
384
+ super().__init__(
385
+ device=device,
386
+ max_epochs=max_epochs,
387
+ data_loader=train_data_loader,
388
+ epoch_length=epoch_length,
389
+ non_blocking=non_blocking,
390
+ prepare_batch=d_prepare_batch,
391
+ iteration_update=iteration_update,
392
+ key_metric=key_train_metric,
393
+ additional_metrics=additional_metrics,
394
+ metric_cmp_fn=metric_cmp_fn,
395
+ handlers=train_handlers,
396
+ postprocessing=postprocessing,
397
+ decollate=decollate,
398
+ to_kwargs=to_kwargs,
399
+ amp_kwargs=amp_kwargs,
400
+ )
401
+ self.g_network = g_network
402
+ self.g_optimizer = g_optimizer
403
+ self.g_loss_function = g_loss_function
404
+ self.g_inferer = SimpleInferer() if g_inferer is None else g_inferer
405
+ self.d_network = d_network
406
+ self.d_optimizer = d_optimizer
407
+ self.d_loss_function = d_loss_function
408
+ self.d_inferer = SimpleInferer() if d_inferer is None else d_inferer
409
+ self.d_train_steps = d_train_steps
410
+ self.latent_shape = latent_shape
411
+ self.g_prepare_batch = g_prepare_batch
412
+ self.g_update_latents = g_update_latents
413
+ self.optim_set_to_none = optim_set_to_none
414
+
415
+ def _iteration(
416
+ self, engine: GanTrainer, batchdata: dict | Sequence
417
+ ) -> dict[str, torch.Tensor | int | float | bool]:
418
+ """
419
+ Callback function for Adversarial Training processing logic of 1 iteration in Ignite Engine.
420
+
421
+ Args:
422
+ engine: `GanTrainer` to execute operation for an iteration.
423
+ batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data.
424
+
425
+ Raises:
426
+ ValueError: must provide batch data for current iteration.
427
+
428
+ """
429
+ if batchdata is None:
430
+ raise ValueError("must provide batch data for current iteration.")
431
+
432
+ d_input = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs)
433
+ batch_size = engine.data_loader.batch_size # type: ignore
434
+ g_input = engine.g_prepare_batch(
435
+ num_latents=batch_size,
436
+ latent_size=engine.latent_shape,
437
+ device=engine.state.device,
438
+ non_blocking=engine.non_blocking,
439
+ **engine.to_kwargs,
440
+ )
441
+ g_output = engine.g_inferer(g_input, engine.g_network)
442
+
443
+ # Train Discriminator
444
+ d_total_loss = torch.zeros(1)
445
+ for _ in range(engine.d_train_steps):
446
+ engine.d_optimizer.zero_grad(set_to_none=engine.optim_set_to_none)
447
+ dloss = engine.d_loss_function(g_output, d_input)
448
+ dloss.backward()
449
+ engine.d_optimizer.step()
450
+ d_total_loss += dloss.item()
451
+
452
+ # Train Generator
453
+ if engine.g_update_latents:
454
+ g_input = engine.g_prepare_batch(
455
+ num_latents=batch_size,
456
+ latent_size=engine.latent_shape,
457
+ device=engine.state.device,
458
+ non_blocking=engine.non_blocking,
459
+ **engine.to_kwargs,
460
+ )
461
+ g_output = engine.g_inferer(g_input, engine.g_network)
462
+ engine.g_optimizer.zero_grad(set_to_none=engine.optim_set_to_none)
463
+ g_loss = engine.g_loss_function(g_output)
464
+ g_loss.backward()
465
+ engine.g_optimizer.step()
466
+
467
+ return {
468
+ GanKeys.REALS: d_input,
469
+ GanKeys.FAKES: g_output,
470
+ GanKeys.LATENTS: g_input,
471
+ GanKeys.GLOSS: g_loss.item(),
472
+ GanKeys.DLOSS: d_total_loss.item(),
473
+ }
source_code/SegMamba/monai/engines/utils.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from abc import ABC, abstractmethod
15
+ from collections.abc import Callable, Sequence
16
+ from typing import TYPE_CHECKING, Any, cast
17
+
18
+ import torch
19
+
20
+ from monai.config import IgniteInfo
21
+ from monai.transforms import apply_transform
22
+ from monai.utils import ensure_tuple, min_version, optional_import
23
+ from monai.utils.enums import CommonKeys, GanKeys
24
+
25
+ if TYPE_CHECKING:
26
+ from ignite.engine import EventEnum
27
+ else:
28
+ EventEnum, _ = optional_import(
29
+ "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum", as_type="base"
30
+ )
31
+
32
+ __all__ = [
33
+ "IterationEvents",
34
+ "get_devices_spec",
35
+ "default_prepare_batch",
36
+ "PrepareBatch",
37
+ "PrepareBatchDefault",
38
+ "PrepareBatchExtraInput",
39
+ "default_make_latent",
40
+ "engine_apply_transform",
41
+ "default_metric_cmp_fn",
42
+ ]
43
+
44
+
45
+ class IterationEvents(EventEnum):
46
+ """
47
+ Additional Events engine can register and trigger in the iteration process.
48
+ Refer to the example in ignite: https://pytorch.org/ignite/generated/ignite.engine.events.EventEnum.html.
49
+ These Events can be triggered during training iteration:
50
+ `FORWARD_COMPLETED` is the Event when `network(image, label)` completed.
51
+ `LOSS_COMPLETED` is the Event when `loss(pred, label)` completed.
52
+ `BACKWARD_COMPLETED` is the Event when `loss.backward()` completed.
53
+ `MODEL_COMPLETED` is the Event when all the model related operations completed.
54
+ `INNER_ITERATION_STARTED` is the Event when the iteration has an inner loop and the loop is started.
55
+ `INNER_ITERATION_COMPLETED` is the Event when the iteration has an inner loop and the loop is completed.
56
+ """
57
+
58
+ FORWARD_COMPLETED = "forward_completed"
59
+ LOSS_COMPLETED = "loss_completed"
60
+ BACKWARD_COMPLETED = "backward_completed"
61
+ MODEL_COMPLETED = "model_completed"
62
+ INNER_ITERATION_STARTED = "inner_iteration_started"
63
+ INNER_ITERATION_COMPLETED = "inner_iteration_completed"
64
+
65
+
66
+ def get_devices_spec(devices: Sequence[torch.device | str] | None = None) -> list[torch.device]:
67
+ """
68
+ Get a valid specification for one or more devices. If `devices` is None get devices for all CUDA devices available.
69
+ If `devices` is and zero-length structure a single CPU compute device is returned. In any other cases `devices` is
70
+ returned unchanged.
71
+
72
+ Args:
73
+ devices: list of devices to request, None for all GPU devices, [] for CPU.
74
+
75
+ Raises:
76
+ RuntimeError: When all GPUs are selected (``devices=None``) but no GPUs are available.
77
+
78
+ Returns:
79
+ list of torch.device: list of devices.
80
+
81
+ """
82
+ if devices is None:
83
+ devices = [torch.device(f"cuda:{d:d}") for d in range(torch.cuda.device_count())]
84
+
85
+ if not devices:
86
+ raise RuntimeError("No GPU devices available.")
87
+
88
+ elif len(devices) == 0:
89
+ devices = [torch.device("cpu")]
90
+
91
+ else:
92
+ devices = list(devices)
93
+
94
+ devices = [torch.device(d) if isinstance(d, str) else d for d in devices]
95
+ return devices # type: ignore
96
+
97
+
98
+ def default_prepare_batch(
99
+ batchdata: dict[str, torch.Tensor] | torch.Tensor | Sequence[torch.Tensor],
100
+ device: str | torch.device | None = None,
101
+ non_blocking: bool = False,
102
+ **kwargs: Any,
103
+ ) -> tuple[torch.Tensor, torch.Tensor | None] | torch.Tensor:
104
+ """
105
+ Default function to prepare the data for current iteration.
106
+
107
+ The input `batchdata` is either a single tensor, a pair of tensors, or a dictionary of data. In the first case the
108
+ return value is the tensor and None, in the second case the return value is the two tensors, and in the dictionary
109
+ case the return value depends on what keys are present. if `CommonKeys.IMAGE` and `CommonKeys.LABEL` are present
110
+ then the tensors they key to are returned, if only `CommonKeys.IMAGE` is present that tensor and None is returned.
111
+ If `CommonKeys.REALS` is present this is returned with None. All returned tensors are moved to the given device
112
+ using the given non-blocking argument before being returned.
113
+
114
+ This function implements the expected API for a `prepare_batch` callable in Ignite:
115
+ https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html
116
+
117
+ Args:
118
+ batchdata: input batch data which is either a single tensor, a pair, or a dictionary
119
+ device: device to move every returned tensor to
120
+ non_blocking: equivalent argument for `Tensor.to`
121
+ kwargs: further arguments for `Tensor.to`
122
+
123
+ Returns:
124
+ image, label(optional).
125
+ """
126
+ if not isinstance(batchdata, dict):
127
+ if isinstance(batchdata, torch.Tensor):
128
+ return batchdata.to(device=device, non_blocking=non_blocking, **kwargs), None
129
+ elif len(batchdata) == 2:
130
+ image, label = batchdata
131
+ return (
132
+ image.to(device=device, non_blocking=non_blocking, **kwargs),
133
+ label.to(device=device, non_blocking=non_blocking, **kwargs),
134
+ )
135
+
136
+ raise AssertionError("Default prepare_batch expects a single tensor, a tensor pair, or dictionary input data.")
137
+
138
+ if isinstance(batchdata.get(CommonKeys.LABEL), torch.Tensor):
139
+ return (
140
+ batchdata[CommonKeys.IMAGE].to(device=device, non_blocking=non_blocking, **kwargs),
141
+ batchdata[CommonKeys.LABEL].to(device=device, non_blocking=non_blocking, **kwargs),
142
+ )
143
+
144
+ if GanKeys.REALS in batchdata:
145
+ return batchdata[GanKeys.REALS].to(device=device, non_blocking=non_blocking, **kwargs)
146
+
147
+ return batchdata[CommonKeys.IMAGE].to(device=device, non_blocking=non_blocking, **kwargs), None
148
+
149
+
150
+ class PrepareBatch(ABC):
151
+ """
152
+ Interface of customized prepare_batch in the trainer or evaluator workflows.
153
+ It takes the data of current batch, target device and non_blocking flag as input.
154
+ Args `batchdata`, `device`, `non_blocking` refer to the ignite API:
155
+ https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html.
156
+ `kwargs` supports other args for `Tensor.to()` API.
157
+ """
158
+
159
+ @abstractmethod
160
+ def __call__(
161
+ self,
162
+ batchdata: dict[str, torch.Tensor],
163
+ device: str | torch.device | None = None,
164
+ non_blocking: bool = False,
165
+ **kwargs: Any,
166
+ ) -> Any:
167
+ raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.")
168
+
169
+
170
+ class PrepareBatchDefault(PrepareBatch):
171
+ """
172
+ This wraps `default_prepare_batch` to return `image` and `label` only, so is consistent with its API.
173
+ """
174
+
175
+ def __call__(
176
+ self,
177
+ batchdata: dict[str, torch.Tensor] | torch.Tensor | Sequence[torch.Tensor],
178
+ device: str | torch.device | None = None,
179
+ non_blocking: bool = False,
180
+ **kwargs: Any,
181
+ ) -> tuple[torch.Tensor, torch.Tensor | None] | torch.Tensor:
182
+ """
183
+ Args `batchdata`, `device`, `non_blocking` refer to the ignite API:
184
+ https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html.
185
+ `kwargs` supports other args for `Tensor.to()` API.
186
+
187
+ """
188
+ return default_prepare_batch(batchdata, device, non_blocking, **kwargs)
189
+
190
+
191
+ class PrepareBatchExtraInput(PrepareBatch):
192
+ """
193
+ Customized prepare batch callable for trainers or evaluators which support extra input data for the network.
194
+ Extra items are specified by the `extra_keys` parameter and are extracted from the input dictionary (ie. the batch).
195
+ This uses `default_prepare_batch` but requires dictionary inputs.
196
+
197
+ Args:
198
+ extra_keys: If a string or sequence of strings is provided, values from the input dictionary are extracted from
199
+ those keys and passed to the network as extra positional arguments. If a dictionary is provided, every pair
200
+ `(k, v)` in that dictionary will become a new keyword argument assigning to `k` the value in the input
201
+ dictionary keyed to `v`.
202
+ """
203
+
204
+ def __init__(self, extra_keys: str | Sequence[str] | dict[str, str]) -> None:
205
+ self.extra_keys = extra_keys
206
+
207
+ def __call__(
208
+ self,
209
+ batchdata: dict[str, torch.Tensor],
210
+ device: str | torch.device | None = None,
211
+ non_blocking: bool = False,
212
+ **kwargs: Any,
213
+ ) -> tuple[torch.Tensor, torch.Tensor, tuple, dict]:
214
+ """
215
+ Args `batchdata`, `device`, `non_blocking` refer to the ignite API:
216
+ https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html.
217
+ `kwargs` supports other args for `Tensor.to()` API.
218
+ """
219
+ image, label = default_prepare_batch(batchdata, device, non_blocking, **kwargs)
220
+ args_ = list()
221
+ kwargs_ = dict()
222
+
223
+ def _get_data(key: str) -> torch.Tensor:
224
+ data = batchdata[key]
225
+
226
+ if isinstance(data, torch.Tensor):
227
+ data = data.to(device=device, non_blocking=non_blocking, **kwargs)
228
+
229
+ return data
230
+
231
+ if isinstance(self.extra_keys, (str, list, tuple)):
232
+ for k in ensure_tuple(self.extra_keys):
233
+ args_.append(_get_data(k))
234
+ elif isinstance(self.extra_keys, dict):
235
+ for k, v in self.extra_keys.items():
236
+ kwargs_.update({k: _get_data(v)})
237
+
238
+ return cast(torch.Tensor, image), cast(torch.Tensor, label), tuple(args_), kwargs_
239
+
240
+
241
+ def default_make_latent(
242
+ num_latents: int,
243
+ latent_size: int,
244
+ device: str | torch.device | None = None,
245
+ non_blocking: bool = False,
246
+ **kwargs: Any,
247
+ ) -> torch.Tensor:
248
+ return torch.randn(num_latents, latent_size).to(device=device, non_blocking=non_blocking, **kwargs)
249
+
250
+
251
+ def engine_apply_transform(batch: Any, output: Any, transform: Callable[..., dict]) -> tuple[Any, Any]:
252
+ """
253
+ Apply transform on `batch` and `output`.
254
+ If `batch` and `output` are dictionaries, temporarily combine them for the transform,
255
+ otherwise, apply the transform for `output` data only.
256
+
257
+ """
258
+ if isinstance(batch, dict) and isinstance(output, dict):
259
+ data = dict(batch)
260
+ data.update(output)
261
+ transformed_data = apply_transform(transform, data)
262
+
263
+ if not isinstance(transformed_data, dict):
264
+ raise AssertionError("With a dict supplied to apply_transform a single dict return is expected.")
265
+
266
+ for k, v in transformed_data.items():
267
+ # split the output data of post transforms into `output` and `batch`,
268
+ # `batch` should be read-only, so save the generated key-value into `output`
269
+ if k in output or k not in batch:
270
+ output[k] = v
271
+ else:
272
+ batch[k] = v
273
+ else:
274
+ output = apply_transform(transform, output)
275
+
276
+ return batch, output
277
+
278
+
279
+ def default_metric_cmp_fn(current_metric: float, prev_best: float) -> bool:
280
+ """
281
+ The default function to compare metric values between current metric and previous best metric.
282
+
283
+ Args:
284
+ current_metric: metric value of current round computation.
285
+ prev_best: the best metric value of previous rounds to compare with.
286
+
287
+ """
288
+ return current_metric > prev_best
source_code/SegMamba/monai/engines/workflow.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import warnings
15
+ from collections.abc import Callable, Iterable, Sequence
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ import torch
19
+ import torch.distributed as dist
20
+ from torch.utils.data import DataLoader
21
+ from torch.utils.data.distributed import DistributedSampler
22
+
23
+ from monai.config import IgniteInfo
24
+ from monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batch
25
+ from monai.transforms import Decollated
26
+ from monai.utils import ensure_tuple, is_scalar, min_version, optional_import
27
+
28
+ from .utils import engine_apply_transform
29
+
30
+ State, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "State")
31
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
32
+
33
+ if TYPE_CHECKING:
34
+ from ignite.engine import Engine, EventEnum
35
+ from ignite.metrics import Metric
36
+ else:
37
+ Engine, _ = optional_import(
38
+ "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine", as_type="decorator"
39
+ )
40
+ Metric, _ = optional_import(
41
+ "ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric", as_type="decorator"
42
+ )
43
+ EventEnum, _ = optional_import(
44
+ "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum", as_type="decorator"
45
+ )
46
+
47
+
48
+ class Workflow(Engine):
49
+ """
50
+ Workflow defines the core work process inheriting from Ignite engine.
51
+ All trainer, validator and evaluator share this same workflow as base class,
52
+ because they all can be treated as same Ignite engine loops.
53
+ It initializes all the sharable data in Ignite engine.state.
54
+ And attach additional processing logics to Ignite engine based on Event-Handler mechanism.
55
+
56
+ Users should consider inheriting from `trainer` or `evaluator` to develop more trainers or evaluators.
57
+
58
+ Args:
59
+ device: an object representing the device on which to run.
60
+ max_epochs: the total epoch number for engine to run, validator and evaluator have only 1 epoch.
61
+ data_loader: Ignite engine use data_loader to run, must be Iterable or torch.DataLoader.
62
+ epoch_length: number of iterations for one epoch, default to `len(data_loader)`.
63
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
64
+ with respect to the host. For other cases, this argument has no effect.
65
+ prepare_batch: function to parse expected data (usually `image`, `label` and other network args)
66
+ from `engine.state.batch` for every iteration, for more details please refer to:
67
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
68
+ iteration_update: the callable function for every iteration, expect to accept `engine`
69
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
70
+ if not provided, use `self._iteration()` instead. for more details please refer to:
71
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
72
+ postprocessing: execute additional transformation for the model output data.
73
+ Typically, several Tensor based transforms composed by `Compose`.
74
+ key_metric: compute metric when every iteration completed, and save average value to
75
+ engine.state.metrics when epoch completed. key_metric is the main metric to compare and save the
76
+ checkpoint into files.
77
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
78
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
79
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
80
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
81
+ handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
82
+ CheckpointHandler, StatsHandler, etc.
83
+ amp: whether to enable auto-mixed-precision training or inference, default is False.
84
+ event_names: additional custom ignite events that will register to the engine.
85
+ new events can be a list of str or `ignite.engine.events.EventEnum`.
86
+ event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`.
87
+ for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html
88
+ #ignite.engine.engine.Engine.register_events.
89
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
90
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
91
+ default to `True`.
92
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
93
+ `device`, `non_blocking`.
94
+ amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details:
95
+ https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast.
96
+
97
+ Raises:
98
+ TypeError: When ``data_loader`` is not a ``torch.utils.data.DataLoader``.
99
+ TypeError: When ``key_metric`` is not a ``Optional[dict]``.
100
+ TypeError: When ``additional_metrics`` is not a ``Optional[dict]``.
101
+
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ device: torch.device | str,
107
+ max_epochs: int,
108
+ data_loader: Iterable | DataLoader,
109
+ epoch_length: int | None = None,
110
+ non_blocking: bool = False,
111
+ prepare_batch: Callable = default_prepare_batch,
112
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
113
+ postprocessing: Callable | None = None,
114
+ key_metric: dict[str, Metric] | None = None,
115
+ additional_metrics: dict[str, Metric] | None = None,
116
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
117
+ handlers: Sequence | None = None,
118
+ amp: bool = False,
119
+ event_names: list[str | EventEnum | type[EventEnum]] | None = None,
120
+ event_to_attr: dict | None = None,
121
+ decollate: bool = True,
122
+ to_kwargs: dict | None = None,
123
+ amp_kwargs: dict | None = None,
124
+ ) -> None:
125
+ if iteration_update is not None:
126
+ super().__init__(iteration_update)
127
+ else:
128
+ super().__init__(self._iteration)
129
+
130
+ if isinstance(data_loader, DataLoader):
131
+ sampler = data_loader.__dict__["sampler"]
132
+ if isinstance(sampler, DistributedSampler):
133
+
134
+ @self.on(Events.EPOCH_STARTED)
135
+ def set_sampler_epoch(engine: Engine) -> None:
136
+ sampler.set_epoch(engine.state.epoch)
137
+
138
+ if epoch_length is None:
139
+ epoch_length = len(data_loader)
140
+ else:
141
+ if epoch_length is None:
142
+ raise ValueError("If data_loader is not PyTorch DataLoader, must specify the epoch_length.")
143
+
144
+ # set all sharable data for the workflow based on Ignite engine.state
145
+ self.state: Any = State(
146
+ rank=dist.get_rank() if dist.is_available() and dist.is_initialized() else 0,
147
+ seed=0,
148
+ iteration=0,
149
+ epoch=0,
150
+ max_epochs=max_epochs,
151
+ epoch_length=epoch_length,
152
+ output=None,
153
+ batch=None,
154
+ metrics={},
155
+ metric_details={},
156
+ dataloader=None,
157
+ device=device if isinstance(device, torch.device) or device is None else torch.device(device),
158
+ key_metric_name=None, # we can set many metrics, only use key_metric to compare and save the best model
159
+ best_metric=-1,
160
+ best_metric_epoch=-1,
161
+ )
162
+ self.data_loader = data_loader
163
+ self.non_blocking = non_blocking
164
+ self.prepare_batch = prepare_batch
165
+ self.metric_cmp_fn = metric_cmp_fn
166
+ self.amp = amp
167
+ self.to_kwargs = {} if to_kwargs is None else to_kwargs
168
+ self.amp_kwargs = {} if amp_kwargs is None else amp_kwargs
169
+ self.scaler: torch.cuda.amp.GradScaler | None = None
170
+
171
+ if event_names is None:
172
+ event_names = [IterationEvents]
173
+ else:
174
+ if not isinstance(event_names, list):
175
+ raise ValueError("`event_names` must be a list of strings or EventEnums.")
176
+ event_names += [IterationEvents]
177
+ for name in event_names:
178
+ if isinstance(name, (str, EventEnum)):
179
+ self.register_events(name, event_to_attr=event_to_attr) # type: ignore[arg-type]
180
+ elif issubclass(name, EventEnum):
181
+ self.register_events(*name, event_to_attr=event_to_attr)
182
+ else:
183
+ raise ValueError("`event_names` must be a list of strings or EventEnums.")
184
+
185
+ if decollate:
186
+ self._register_decollate()
187
+
188
+ if postprocessing is not None:
189
+ # tips: if `decollate=False` and `postprocessing` is MONAI transforms, it may not work well
190
+ # because all the MONAI transforms expect `channel-first` data
191
+ self._register_postprocessing(postprocessing)
192
+ if key_metric is not None:
193
+ self._register_metrics(key_metric, additional_metrics)
194
+ if handlers is not None:
195
+ self._register_handlers(handlers)
196
+
197
+ def _register_decollate(self):
198
+ """
199
+ Register the decollate operation for batch data, will execute after model forward and loss forward.
200
+
201
+ """
202
+
203
+ @self.on(IterationEvents.MODEL_COMPLETED)
204
+ def _decollate_data(engine: Engine) -> None:
205
+ # replicate the scalar values to make sure all the items have batch dimension, then decollate
206
+ transform = Decollated(keys=None, detach=True)
207
+ if isinstance(engine.state.batch, (list, dict)):
208
+ engine.state.batch = transform(engine.state.batch)
209
+ if isinstance(engine.state.output, (list, dict)):
210
+ engine.state.output = transform(engine.state.output)
211
+
212
+ def _register_postprocessing(self, posttrans: Callable) -> None:
213
+ """
214
+ Register the postprocessing logic to the engine, will execute them as a chain when iteration completed.
215
+
216
+ """
217
+
218
+ @self.on(IterationEvents.MODEL_COMPLETED)
219
+ def _run_postprocessing(engine: Engine) -> None:
220
+ if not isinstance(engine.state.batch, list) or not isinstance(engine.state.output, list):
221
+ engine.state.batch, engine.state.output = engine_apply_transform(
222
+ batch=engine.state.batch, output=engine.state.output, transform=posttrans
223
+ )
224
+ else:
225
+ for i, (b, o) in enumerate(zip(engine.state.batch, engine.state.output)):
226
+ engine.state.batch[i], engine.state.output[i] = engine_apply_transform(b, o, posttrans)
227
+
228
+ def _register_metrics(self, k_metric: dict, add_metrics: dict | None = None) -> None:
229
+ """
230
+ Register the key metric and additional metrics to the engine, supports ignite Metrics.
231
+
232
+ """
233
+ if not isinstance(k_metric, dict):
234
+ raise TypeError(f"`key_metric` must be None or a dict but is {type(k_metric).__name__}.")
235
+ self.state.key_metric_name = list(k_metric.keys())[0]
236
+ metrics = dict(k_metric)
237
+ if add_metrics is not None and len(add_metrics) > 0:
238
+ if not isinstance(add_metrics, dict):
239
+ raise TypeError(f"Additional metrics must be None or a dict but is {type(add_metrics).__name__}.")
240
+ metrics.update(add_metrics)
241
+ for name, metric in metrics.items():
242
+ metric.attach(self, name)
243
+
244
+ @self.on(Events.EPOCH_COMPLETED)
245
+ def _compare_metrics(engine: Workflow) -> None:
246
+ key_metric_name = engine.state.key_metric_name
247
+ if key_metric_name is not None:
248
+ current_val_metric = engine.state.metrics[key_metric_name]
249
+ if not is_scalar(current_val_metric):
250
+ warnings.warn(
251
+ "Key metric is not a scalar value, skip the metric comparison with the current best metric."
252
+ "Please set other metrics as the key metric, or change the `reduction` mode to 'mean'."
253
+ )
254
+ return
255
+
256
+ if engine.state.best_metric_epoch == -1 or self.metric_cmp_fn(
257
+ current_val_metric, engine.state.best_metric
258
+ ):
259
+ self.logger.info(f"Got new best metric of {key_metric_name}: {current_val_metric}")
260
+ engine.state.best_metric = current_val_metric
261
+ engine.state.best_metric_epoch = engine.state.epoch
262
+
263
+ def _register_handlers(self, handlers: Sequence) -> None:
264
+ """
265
+ Register the handlers to the engine, supports ignite Handlers with `attach` API.
266
+
267
+ """
268
+ handlers_ = ensure_tuple(handlers)
269
+ for handler in handlers_:
270
+ handler.attach(self)
271
+
272
+ def run(self) -> None: # type: ignore[override]
273
+ """
274
+ Execute training, validation or evaluation based on Ignite Engine.
275
+ """
276
+ if self.state.epoch_length == 0:
277
+ warnings.warn(
278
+ "`dataloader` is empty or the specified `epoch_length` is 0, skip the `run`."
279
+ " If running distributed training, the program may hang in `all-gather`, `all-reduce`, etc."
280
+ " because not all the ranks run the same computation logic."
281
+ )
282
+ return
283
+ super().run(data=self.data_loader, max_epochs=self.state.max_epochs)
284
+
285
+ def _iteration(self, engine: Any, batchdata: dict[str, torch.Tensor]) -> dict:
286
+ """
287
+ Abstract callback function for the processing logic of 1 iteration in Ignite Engine.
288
+ Need subclass to implement different logics, like SupervisedTrainer/Evaluator, GANTrainer, etc.
289
+
290
+ Args:
291
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
292
+ batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data.
293
+
294
+ Raises:
295
+ NotImplementedError: When the subclass does not override this method.
296
+
297
+ """
298
+ raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.")
299
+
300
+ def get_stats(self, *vars):
301
+ """
302
+ Get the statistics information of the workflow process.
303
+
304
+ Args:
305
+ vars: variables name in the `self.state`, will use the variable name as the key
306
+ and the state content as the value. if the variable doesn't exist, default value is `None`.
307
+
308
+ """
309
+ return {k: getattr(self.state, k, None) for k in vars}
source_code/SegMamba/monai/fl/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
source_code/SegMamba/monai/handlers/__init__.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from .checkpoint_loader import CheckpointLoader
15
+ from .checkpoint_saver import CheckpointSaver
16
+ from .classification_saver import ClassificationSaver
17
+ from .clearml_handlers import ClearMLHandler, ClearMLImageHandler, ClearMLStatsHandler
18
+ from .confusion_matrix import ConfusionMatrix
19
+ from .decollate_batch import DecollateBatch
20
+ from .earlystop_handler import EarlyStopHandler
21
+ from .garbage_collector import GarbageCollector
22
+ from .hausdorff_distance import HausdorffDistance
23
+ from .ignite_metric import IgniteMetric, IgniteMetricHandler
24
+ from .logfile_handler import LogfileHandler
25
+ from .lr_schedule_handler import LrScheduleHandler
26
+ from .mean_dice import MeanDice
27
+ from .mean_iou import MeanIoUHandler
28
+ from .metric_logger import MetricLogger, MetricLoggerKeys
29
+ from .metrics_reloaded_handler import MetricsReloadedBinaryHandler, MetricsReloadedCategoricalHandler
30
+ from .metrics_saver import MetricsSaver
31
+ from .mlflow_handler import MLFlowHandler
32
+ from .nvtx_handlers import MarkHandler, RangeHandler, RangePopHandler, RangePushHandler
33
+ from .panoptic_quality import PanopticQuality
34
+ from .parameter_scheduler import ParamSchedulerHandler
35
+ from .postprocessing import PostProcessing
36
+ from .probability_maps import ProbMapProducer
37
+ from .regression_metrics import MeanAbsoluteError, MeanSquaredError, PeakSignalToNoiseRatio, RootMeanSquaredError
38
+ from .roc_auc import ROCAUC
39
+ from .smartcache_handler import SmartCacheHandler
40
+ from .stats_handler import StatsHandler
41
+ from .surface_distance import SurfaceDistance
42
+ from .tensorboard_handlers import TensorBoardHandler, TensorBoardImageHandler, TensorBoardStatsHandler
43
+ from .utils import from_engine, ignore_data, stopping_fn_from_loss, stopping_fn_from_metric, write_metrics_reports
44
+ from .validation_handler import ValidationHandler
source_code/SegMamba/monai/handlers/checkpoint_loader.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import warnings
16
+ from typing import TYPE_CHECKING
17
+
18
+ import torch
19
+
20
+ from monai.config import IgniteInfo
21
+ from monai.networks.utils import copy_model_state
22
+ from monai.utils import min_version, optional_import
23
+
24
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
25
+ Checkpoint, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Checkpoint")
26
+ if TYPE_CHECKING:
27
+ from ignite.engine import Engine
28
+ else:
29
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
30
+
31
+
32
+ class CheckpointLoader:
33
+ """
34
+ CheckpointLoader acts as an Ignite handler to load checkpoint data from file.
35
+ It can load variables for network, optimizer, lr_scheduler, etc.
36
+ If saving checkpoint after `torch.nn.DataParallel`, need to save `model.module` instead
37
+ as PyTorch recommended and then use this loader to load the model.
38
+
39
+ Usage example::
40
+
41
+ trainer = SupervisedTrainer(...)
42
+ save_dict = {
43
+ "trainer": trainer,
44
+ "net": network,
45
+ "opt": optimizer,
46
+ "lr": lr_scheduler,
47
+ }
48
+
49
+ map_location = "cuda:0"
50
+ # checkpoint needs to have same save_dict for this to work
51
+ handler = CheckpointLoader(load_path="/test/checkpoint.pt", load_dict=save_dict, map_location=map_location, strict=True)
52
+ handler(trainer)
53
+ # Trainer now has the same state as stored, including the number of epochs and iterations completed
54
+ # so you can resume an interrupted training at the place where it left
55
+
56
+ Args:
57
+ load_path: the file path of checkpoint, it should be a PyTorch `pth` file.
58
+ load_dict: target objects that load checkpoint to. examples::
59
+
60
+ {'network': net, 'optimizer': optimizer, 'lr_scheduler': lr_scheduler}
61
+
62
+ name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``.
63
+ map_location: when loading the module for distributed training/evaluation,
64
+ need to provide an appropriate map_location argument to prevent a process
65
+ to step into others’ devices. If map_location is missing, torch.load will
66
+ first load the module to CPU and then copy each parameter to where it was
67
+ saved, which would result in all processes on the same machine using the
68
+ same set of devices.
69
+ strict: whether to strictly enforce that the keys and data shape in the `state_dict` of every item
70
+ of `load_dict` match the `state_dict` of the corresponding items of checkpoint, default to `True`.
71
+ strict_shape: whether to enforce the data shape of the matched layers in the checkpoint,
72
+ `if `False`, it will skip the layers that have different data shape with checkpoint content,
73
+ and ignore the `strict` arg. this can be useful advanced feature for transfer learning.
74
+ users should totally understand which layers will have different shape. default to `True`.
75
+
76
+ Note: if `strict_shape=False`, will only load checkpoint for `torch.nn.Module` and skip other
77
+ items in the `load_dict`. For example, if the shape of some layers in current model can't
78
+ match the checkpoint, the `parameter_group` of current optimizer may also can't match the
79
+ checkpoint, so skip loading checkpoint for optimizer.
80
+
81
+ For more details about loading checkpoint, please refer to:
82
+ https://pytorch.org/ignite/v0.4.5/generated/ignite.handlers.checkpoint.Checkpoint.html
83
+ #ignite.handlers.checkpoint.Checkpoint.load_objects.
84
+ https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.load_state_dict.
85
+
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ load_path: str,
91
+ load_dict: dict,
92
+ name: str | None = None,
93
+ map_location: dict | None = None,
94
+ strict: bool = True,
95
+ strict_shape: bool = True,
96
+ ) -> None:
97
+ if load_path is None:
98
+ raise AssertionError("must provide clear path to load checkpoint.")
99
+ self.load_path = load_path
100
+ if load_dict is None or len(load_dict) <= 0:
101
+ raise AssertionError("must provide target objects to load.")
102
+ self.logger = logging.getLogger(name)
103
+ self.load_dict = load_dict
104
+ self._name = name
105
+ self.map_location = map_location
106
+ if strict and not strict_shape:
107
+ warnings.warn("as `strict_shape` is already False, change `strict` to False.")
108
+ strict = False
109
+ self.strict = strict
110
+ self.strict_shape = strict_shape
111
+
112
+ def attach(self, engine: Engine) -> None:
113
+ """
114
+ Args:
115
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
116
+ """
117
+ if self._name is None:
118
+ self.logger = engine.logger
119
+ engine.add_event_handler(Events.STARTED, self)
120
+
121
+ def __call__(self, engine: Engine) -> None:
122
+ """
123
+ Args:
124
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
125
+ """
126
+ checkpoint = torch.load(self.load_path, map_location=self.map_location)
127
+
128
+ k, _ = list(self.load_dict.items())[0]
129
+ # single object and checkpoint is directly a state_dict
130
+ if len(self.load_dict) == 1 and k not in checkpoint:
131
+ checkpoint = {k: checkpoint}
132
+
133
+ if not self.strict_shape:
134
+ pop_items: list[str] = []
135
+ for k, obj in self.load_dict.items():
136
+ if isinstance(obj, torch.nn.Module):
137
+ # skip items that don't match key name or data shape
138
+ checkpoint[k] = copy_model_state(obj, checkpoint, inplace=False)[0]
139
+ else:
140
+ warnings.warn("`strict_shape` is False, load checkpoint for model, skip others in `load_dict`.")
141
+ pop_items.append(k)
142
+ for i in pop_items:
143
+ self.load_dict.pop(i)
144
+
145
+ # save current max epochs setting in the engine, don't overwrite it if larger than max_epochs in checkpoint
146
+ prior_max_epochs = engine.state.max_epochs
147
+ Checkpoint.load_objects(to_load=self.load_dict, checkpoint=checkpoint, strict=self.strict)
148
+ if prior_max_epochs is not None and engine.state.epoch > prior_max_epochs:
149
+ raise ValueError(
150
+ f"Epoch count ({engine.state.epoch}) in checkpoint is larger than "
151
+ f"the `engine.state.max_epochs` ({prior_max_epochs}) of engine. To further train from checkpoint, "
152
+ "construct trainer with `max_epochs` larger than checkpoint's epoch count. "
153
+ "To use checkpoint for inference, no need to load state_dict for the engine."
154
+ )
155
+ engine.state.max_epochs = prior_max_epochs
156
+
157
+ self.logger.info(f"Restored all variables from {self.load_path}")
source_code/SegMamba/monai/handlers/checkpoint_saver.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ import warnings
17
+ from collections.abc import Mapping
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ from monai.config import IgniteInfo
21
+ from monai.utils import is_scalar, min_version, optional_import
22
+
23
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
24
+
25
+ if TYPE_CHECKING:
26
+ from ignite.engine import Engine
27
+ from ignite.handlers import Checkpoint, DiskSaver
28
+ else:
29
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
30
+ DiskSaver, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "DiskSaver")
31
+ Checkpoint, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Checkpoint")
32
+
33
+
34
+ class CheckpointSaver:
35
+ """
36
+ CheckpointSaver acts as an Ignite handler to save checkpoint data into files.
37
+ It supports to save according to metrics result, epoch number, iteration number
38
+ and last model or exception.
39
+
40
+ Args:
41
+ save_dir: the target directory to save the checkpoints.
42
+ save_dict: source objects that save to the checkpoint. examples::
43
+
44
+ {'network': net, 'optimizer': optimizer, 'lr_scheduler': lr_scheduler}
45
+
46
+ name: identifier of logging.logger to use, if None, defaulting to ``engine.logger``.
47
+ file_prefix: prefix for the filenames to which objects will be saved.
48
+ save_final: whether to save checkpoint or session at final iteration or exception.
49
+ If checkpoints are to be saved when an exception is raised, put this handler before
50
+ `StatsHandler` in the handler list, because the logic with Ignite can only trigger
51
+ the first attached handler for `EXCEPTION_RAISED` event.
52
+ final_filename: set a fixed filename to save the final model if `save_final=True`.
53
+ If None, default to `checkpoint_final_iteration=N.pt`.
54
+ save_key_metric: whether to save checkpoint or session when the value of key_metric is
55
+ higher than all the previous values during training.keep 4 decimal places of metric,
56
+ checkpoint name is: {file_prefix}_key_metric=0.XXXX.pth.
57
+ key_metric_name: the name of key_metric in ignite metrics dictionary.
58
+ If None, use `engine.state.key_metric` instead.
59
+ key_metric_n_saved: save top N checkpoints or sessions, sorted by the value of key
60
+ metric in descending order.
61
+ key_metric_filename: set a fixed filename to set the best metric model, if not None,
62
+ `key_metric_n_saved` should be 1 and only keep the best metric model.
63
+ key_metric_save_state: whether to save the tracking list of key metric in the checkpoint file.
64
+ if `True`, then will save an object in the checkpoint file with key `checkpointer` to be
65
+ consistent with the `include_self` arg of `Checkpoint` in ignite:
66
+ https://pytorch.org/ignite/v0.4.5/generated/ignite.handlers.checkpoint.Checkpoint.html.
67
+ typically, it's used to resume training and compare current metric with previous N values.
68
+ key_metric_greater_or_equal: if `True`, the latest equally scored model is stored. Otherwise,
69
+ save the first equally scored model. default to `False`.
70
+ key_metric_negative_sign: whether adding a negative sign to the metric score to compare metrics,
71
+ because for error-like metrics, smaller is better(objects with larger score are retained).
72
+ default to `False`.
73
+ epoch_level: save checkpoint during training for every N epochs or every N iterations.
74
+ `True` is epoch level, `False` is iteration level.
75
+ save_interval: save checkpoint every N epochs, default is 0 to save no checkpoint.
76
+ n_saved: save latest N checkpoints of epoch level or iteration level, 'None' is to save all.
77
+
78
+ Note:
79
+ CheckpointHandler can be used during training, validation or evaluation.
80
+ example of saved files:
81
+
82
+ - checkpoint_iteration=400.pt
83
+ - checkpoint_iteration=800.pt
84
+ - checkpoint_epoch=1.pt
85
+ - checkpoint_final_iteration=1000.pt
86
+ - checkpoint_key_metric=0.9387.pt
87
+
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ save_dir: str,
93
+ save_dict: dict,
94
+ name: str | None = None,
95
+ file_prefix: str = "",
96
+ save_final: bool = False,
97
+ final_filename: str | None = None,
98
+ save_key_metric: bool = False,
99
+ key_metric_name: str | None = None,
100
+ key_metric_n_saved: int = 1,
101
+ key_metric_filename: str | None = None,
102
+ key_metric_save_state: bool = False,
103
+ key_metric_greater_or_equal: bool = False,
104
+ key_metric_negative_sign: bool = False,
105
+ epoch_level: bool = True,
106
+ save_interval: int = 0,
107
+ n_saved: int | None = None,
108
+ ) -> None:
109
+ if save_dir is None:
110
+ raise AssertionError("must provide directory to save the checkpoints.")
111
+ self.save_dir = save_dir
112
+ if not (save_dict is not None and len(save_dict) > 0):
113
+ raise AssertionError("must provide source objects to save.")
114
+ self.save_dict = save_dict
115
+ self.logger = logging.getLogger(name)
116
+ self.epoch_level = epoch_level
117
+ self.save_interval = save_interval
118
+ self._final_checkpoint: Checkpoint | None = None
119
+ self._key_metric_checkpoint: Checkpoint | None = None
120
+ self._interval_checkpoint: Checkpoint | None = None
121
+ self._name = name
122
+ self._final_filename = final_filename
123
+
124
+ class _DiskSaver(DiskSaver):
125
+ """
126
+ Enhance the DiskSaver to support fixed filename.
127
+
128
+ """
129
+
130
+ def __init__(self, dirname: str, filename: str | None = None):
131
+ # set `atomic=False` as `atomic=True` only gives read/write permission to the user who saved the file,
132
+ # without group/others read permission
133
+ super().__init__(dirname=dirname, require_empty=False, atomic=False)
134
+ self.filename = filename
135
+
136
+ def __call__(self, checkpoint: Mapping, filename: str, metadata: Mapping | None = None) -> None:
137
+ if self.filename is not None:
138
+ filename = self.filename
139
+ super().__call__(checkpoint=checkpoint, filename=filename, metadata=metadata)
140
+
141
+ def remove(self, filename: str) -> None:
142
+ if self.filename is not None:
143
+ filename = self.filename
144
+ super().remove(filename=filename)
145
+
146
+ if save_final:
147
+
148
+ def _final_func(engine: Engine) -> Any:
149
+ return engine.state.iteration
150
+
151
+ self._final_checkpoint = Checkpoint(
152
+ to_save=self.save_dict,
153
+ save_handler=_DiskSaver(dirname=self.save_dir, filename=self._final_filename),
154
+ filename_prefix=file_prefix,
155
+ score_function=_final_func,
156
+ score_name="final_iteration",
157
+ )
158
+
159
+ if save_key_metric:
160
+
161
+ def _score_func(engine: Engine) -> Any:
162
+ if isinstance(key_metric_name, str):
163
+ metric_name = key_metric_name
164
+ elif hasattr(engine.state, "key_metric_name"):
165
+ metric_name = engine.state.key_metric_name
166
+ else:
167
+ raise ValueError(
168
+ f"Incompatible values: save_key_metric=True and key_metric_name={key_metric_name}."
169
+ )
170
+ metric = engine.state.metrics[metric_name]
171
+ if not is_scalar(metric):
172
+ warnings.warn(
173
+ "key metric is not a scalar value, skip metric comparison and don't save a model."
174
+ "please use other metrics as key metric, or change the `reduction` mode to 'mean'."
175
+ f"got metric: {metric_name}={metric}."
176
+ )
177
+ return -1
178
+ return (-1 if key_metric_negative_sign else 1) * metric
179
+
180
+ if key_metric_filename is not None and key_metric_n_saved > 1:
181
+ raise ValueError("if using fixed filename to save the best metric model, we should only save 1 model.")
182
+
183
+ self._key_metric_checkpoint = Checkpoint(
184
+ to_save=self.save_dict,
185
+ save_handler=_DiskSaver(dirname=self.save_dir, filename=key_metric_filename),
186
+ filename_prefix=file_prefix,
187
+ score_function=_score_func,
188
+ score_name="key_metric",
189
+ n_saved=key_metric_n_saved,
190
+ include_self=key_metric_save_state,
191
+ greater_or_equal=key_metric_greater_or_equal,
192
+ )
193
+
194
+ if save_interval > 0:
195
+
196
+ def _interval_func(engine: Engine) -> Any:
197
+ return engine.state.epoch if self.epoch_level else engine.state.iteration
198
+
199
+ self._interval_checkpoint = Checkpoint(
200
+ to_save=self.save_dict,
201
+ save_handler=_DiskSaver(dirname=self.save_dir),
202
+ filename_prefix=file_prefix,
203
+ score_function=_interval_func,
204
+ score_name="epoch" if self.epoch_level else "iteration",
205
+ n_saved=n_saved,
206
+ )
207
+
208
+ def load_state_dict(self, state_dict: dict) -> None:
209
+ """
210
+ Utility to resume the internal state of key metric tracking list if configured to save
211
+ checkpoints based on the key metric value.
212
+ Note to set `key_metric_save_state=True` when saving the previous checkpoint.
213
+
214
+ Example::
215
+
216
+ CheckpointSaver(
217
+ ...
218
+ save_key_metric=True,
219
+ key_metric_save_state=True, # config to also save the state of this saver
220
+ ).attach(engine)
221
+ engine.run(...)
222
+
223
+ # resumed training with a new CheckpointSaver
224
+ saver = CheckpointSaver(save_key_metric=True, ...)
225
+ # load the previous key metric tracking list into saver
226
+ CheckpointLoader("/test/model.pt"), {"checkpointer": saver}).attach(engine)
227
+
228
+ """
229
+ if self._key_metric_checkpoint is not None:
230
+ self._key_metric_checkpoint.load_state_dict(state_dict)
231
+ else:
232
+ warnings.warn("no key metric checkpoint saver to resume the key metric tracking list.")
233
+
234
+ def attach(self, engine: Engine) -> None:
235
+ """
236
+ Args:
237
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
238
+ """
239
+ if self._name is None:
240
+ self.logger = engine.logger
241
+ if self._final_checkpoint is not None:
242
+ engine.add_event_handler(Events.COMPLETED, self.completed)
243
+ engine.add_event_handler(Events.EXCEPTION_RAISED, self.exception_raised)
244
+ if self._key_metric_checkpoint is not None:
245
+ engine.add_event_handler(Events.EPOCH_COMPLETED, self.metrics_completed)
246
+ if self._interval_checkpoint is not None:
247
+ if self.epoch_level:
248
+ engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.save_interval), self.interval_completed)
249
+ else:
250
+ engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.save_interval), self.interval_completed)
251
+
252
+ def _delete_previous_final_ckpt(self):
253
+ if self._final_checkpoint is not None:
254
+ saved = self._final_checkpoint._saved
255
+ if len(saved) > 0:
256
+ item = saved.pop(0)
257
+ self._final_checkpoint.save_handler.remove(item.filename)
258
+ self.logger.info(f"Deleted previous saved final checkpoint: {item.filename}")
259
+
260
+ def completed(self, engine: Engine) -> None:
261
+ """Callback for train or validation/evaluation completed Event.
262
+ Save final checkpoint if configure save_final is True.
263
+
264
+ Args:
265
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
266
+ """
267
+ if not callable(self._final_checkpoint):
268
+ raise AssertionError("Error: _final_checkpoint function not specified.")
269
+ # delete previous saved final checkpoint if existing
270
+ self._delete_previous_final_ckpt()
271
+ self._final_checkpoint(engine)
272
+ if self.logger is None:
273
+ raise AssertionError
274
+ if not hasattr(self.logger, "info"):
275
+ raise AssertionError("Error, provided logger has not info attribute.")
276
+ if self._final_filename is not None:
277
+ _final_checkpoint_path = os.path.join(self.save_dir, self._final_filename)
278
+ else:
279
+ _final_checkpoint_path = self._final_checkpoint.last_checkpoint # type: ignore[assignment]
280
+ self.logger.info(f"Train completed, saved final checkpoint: {_final_checkpoint_path}")
281
+
282
+ def exception_raised(self, engine: Engine, e: Exception) -> None:
283
+ """Callback for train or validation/evaluation exception raised Event.
284
+ Save current data as final checkpoint if configure save_final is True. This callback may be skipped
285
+ because the logic with Ignite can only trigger the first attached handler for `EXCEPTION_RAISED` event.
286
+
287
+ Args:
288
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
289
+ e: the exception caught in Ignite during engine.run().
290
+ """
291
+ if not callable(self._final_checkpoint):
292
+ raise AssertionError("Error: _final_checkpoint function not specified.")
293
+ # delete previous saved final checkpoint if existing
294
+ self._delete_previous_final_ckpt()
295
+ self._final_checkpoint(engine)
296
+ if self.logger is None:
297
+ raise AssertionError
298
+ if not hasattr(self.logger, "info"):
299
+ raise AssertionError("Error, provided logger has not info attribute.")
300
+ if self._final_filename is not None:
301
+ _final_checkpoint_path = os.path.join(self.save_dir, self._final_filename)
302
+ else:
303
+ _final_checkpoint_path = self._final_checkpoint.last_checkpoint # type: ignore[assignment]
304
+ self.logger.info(f"Exception raised, saved the last checkpoint: {_final_checkpoint_path}")
305
+ raise e
306
+
307
+ def metrics_completed(self, engine: Engine) -> None:
308
+ """Callback to compare metrics and save models in train or validation when epoch completed.
309
+
310
+ Args:
311
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
312
+ """
313
+ if not callable(self._key_metric_checkpoint):
314
+ raise AssertionError("Error: _key_metric_checkpoint function not specified.")
315
+ self._key_metric_checkpoint(engine)
316
+
317
+ def interval_completed(self, engine: Engine) -> None:
318
+ """Callback for train epoch/iteration completed Event.
319
+ Save checkpoint if configure save_interval = N
320
+
321
+ Args:
322
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
323
+ """
324
+ if not callable(self._interval_checkpoint):
325
+ raise AssertionError("Error: _interval_checkpoint function not specified.")
326
+ self._interval_checkpoint(engine)
327
+ if self.logger is None:
328
+ raise AssertionError
329
+ if not hasattr(self.logger, "info"):
330
+ raise AssertionError("Error, provided logger has not info attribute.")
331
+ if self.epoch_level:
332
+ self.logger.info(f"Saved checkpoint at epoch: {engine.state.epoch}")
333
+ else:
334
+ self.logger.info(f"Saved checkpoint at iteration: {engine.state.iteration}")
source_code/SegMamba/monai/handlers/classification_saver.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import warnings
16
+ from collections.abc import Callable
17
+ from typing import TYPE_CHECKING
18
+
19
+ import torch
20
+
21
+ from monai.config import IgniteInfo
22
+ from monai.data import CSVSaver, decollate_batch
23
+ from monai.utils import ImageMetaKey as Key
24
+ from monai.utils import evenly_divisible_all_gather, min_version, optional_import, string_list_all_gather
25
+
26
+ idist, _ = optional_import("ignite", IgniteInfo.OPT_IMPORT_VERSION, min_version, "distributed")
27
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
28
+ if TYPE_CHECKING:
29
+ from ignite.engine import Engine
30
+ else:
31
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
32
+
33
+
34
+ class ClassificationSaver:
35
+ """
36
+ Event handler triggered on completing every iteration to save the classification predictions as CSV file.
37
+ If running in distributed data parallel, only saves CSV file in the specified rank.
38
+
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ output_dir: str = "./",
44
+ filename: str = "predictions.csv",
45
+ delimiter: str = ",",
46
+ overwrite: bool = True,
47
+ batch_transform: Callable = lambda x: x,
48
+ output_transform: Callable = lambda x: x,
49
+ name: str | None = None,
50
+ save_rank: int = 0,
51
+ saver: CSVSaver | None = None,
52
+ ) -> None:
53
+ """
54
+ Args:
55
+ output_dir: if `saver=None`, output CSV file directory.
56
+ filename: if `saver=None`, name of the saved CSV file name.
57
+ delimiter: the delimiter character in the saved file, default to "," as the default output type is `csv`.
58
+ to be consistent with: https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter.
59
+ overwrite: if `saver=None`, whether to overwriting existing file content, if True,
60
+ will clear the file before saving. otherwise, will append new content to the file.
61
+ batch_transform: a callable that is used to extract the `meta_data` dictionary of
62
+ the input images from `ignite.engine.state.batch`. the purpose is to get the input
63
+ filenames from the `meta_data` and store with classification results together.
64
+ `engine.state` and `batch_transform` inherit from the ignite concept:
65
+ https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial:
66
+ https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb.
67
+ output_transform: a callable that is used to extract the model prediction data from
68
+ `ignite.engine.state.output`. the first dimension of its output will be treated as
69
+ the batch dimension. each item in the batch will be saved individually.
70
+ `engine.state` and `output_transform` inherit from the ignite concept:
71
+ https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial:
72
+ https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb.
73
+ name: identifier of logging.logger to use, defaulting to `engine.logger`.
74
+ save_rank: only the handler on specified rank will save to CSV file in multi-gpus validation,
75
+ default to 0.
76
+ saver: the saver instance to save classification results, if None, create a CSVSaver internally.
77
+ the saver must provide `save_batch(batch_data, meta_data)` and `finalize()` APIs.
78
+
79
+ """
80
+ self.save_rank = save_rank
81
+ self.output_dir = output_dir
82
+ self.filename = filename
83
+ self.delimiter = delimiter
84
+ self.overwrite = overwrite
85
+ self.batch_transform = batch_transform
86
+ self.output_transform = output_transform
87
+ self.saver = saver
88
+
89
+ self.logger = logging.getLogger(name)
90
+ self._name = name
91
+ self._outputs: list[torch.Tensor] = []
92
+ self._filenames: list[str] = []
93
+
94
+ def attach(self, engine: Engine) -> None:
95
+ """
96
+ Args:
97
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
98
+ """
99
+ if self._name is None:
100
+ self.logger = engine.logger
101
+ if not engine.has_event_handler(self._started, Events.EPOCH_STARTED):
102
+ engine.add_event_handler(Events.EPOCH_STARTED, self._started)
103
+ if not engine.has_event_handler(self, Events.ITERATION_COMPLETED):
104
+ engine.add_event_handler(Events.ITERATION_COMPLETED, self)
105
+ if not engine.has_event_handler(self._finalize, Events.EPOCH_COMPLETED):
106
+ engine.add_event_handler(Events.EPOCH_COMPLETED, self._finalize)
107
+
108
+ def _started(self, _engine: Engine) -> None:
109
+ """
110
+ Initialize internal buffers.
111
+
112
+ Args:
113
+ _engine: Ignite Engine, unused argument.
114
+
115
+ """
116
+ self._outputs = []
117
+ self._filenames = []
118
+
119
+ def __call__(self, engine: Engine) -> None:
120
+ """
121
+ This method assumes self.batch_transform will extract metadata from the input batch.
122
+
123
+ Args:
124
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
125
+ """
126
+ meta_data = self.batch_transform(engine.state.batch)
127
+ if isinstance(meta_data, dict):
128
+ # decollate the `dictionary of list` to `list of dictionaries`
129
+ meta_data = decollate_batch(meta_data)
130
+ engine_output = self.output_transform(engine.state.output)
131
+ for m, o in zip(meta_data, engine_output):
132
+ self._filenames.append(f"{m.get(Key.FILENAME_OR_OBJ)}")
133
+ if isinstance(o, torch.Tensor):
134
+ o = o.detach()
135
+ self._outputs.append(o)
136
+
137
+ def _finalize(self, _engine: Engine) -> None:
138
+ """
139
+ All gather classification results from ranks and save to CSV file.
140
+
141
+ Args:
142
+ _engine: Ignite Engine, unused argument.
143
+ """
144
+ ws = idist.get_world_size()
145
+ if self.save_rank >= ws:
146
+ raise ValueError("target save rank is greater than the distributed group size.")
147
+
148
+ outputs = torch.stack(self._outputs, dim=0)
149
+ filenames = self._filenames
150
+ if ws > 1:
151
+ outputs = evenly_divisible_all_gather(outputs, concat=True)
152
+ filenames = string_list_all_gather(filenames)
153
+
154
+ if len(filenames) == 0:
155
+ meta_dict = None
156
+ else:
157
+ if len(filenames) != len(outputs):
158
+ warnings.warn(f"filenames length: {len(filenames)} doesn't match outputs length: {len(outputs)}.")
159
+ meta_dict = {Key.FILENAME_OR_OBJ: filenames}
160
+
161
+ # save to CSV file only in the expected rank
162
+ if idist.get_rank() == self.save_rank:
163
+ saver = self.saver or CSVSaver(
164
+ output_dir=self.output_dir, filename=self.filename, overwrite=self.overwrite, delimiter=self.delimiter
165
+ )
166
+ saver.save_batch(outputs, meta_dict)
167
+ saver.finalize()
source_code/SegMamba/monai/handlers/confusion_matrix.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+
16
+ from monai.handlers.ignite_metric import IgniteMetricHandler
17
+ from monai.metrics import ConfusionMatrixMetric
18
+ from monai.utils.enums import MetricReduction
19
+
20
+
21
+ class ConfusionMatrix(IgniteMetricHandler):
22
+ """
23
+ Compute confusion matrix related metrics from full size Tensor and collects average over batch, class-channels, iterations.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ include_background: bool = True,
29
+ metric_name: str = "hit_rate",
30
+ compute_sample: bool = False,
31
+ reduction: MetricReduction | str = MetricReduction.MEAN,
32
+ output_transform: Callable = lambda x: x,
33
+ save_details: bool = True,
34
+ ) -> None:
35
+ """
36
+
37
+ Args:
38
+ include_background: whether to include metric computation on the first channel of
39
+ the predicted output. Defaults to True.
40
+ metric_name: [``"sensitivity"``, ``"specificity"``, ``"precision"``, ``"negative predictive value"``,
41
+ ``"miss rate"``, ``"fall out"``, ``"false discovery rate"``, ``"false omission rate"``,
42
+ ``"prevalence threshold"``, ``"threat score"``, ``"accuracy"``, ``"balanced accuracy"``,
43
+ ``"f1 score"``, ``"matthews correlation coefficient"``, ``"fowlkes mallows index"``,
44
+ ``"informedness"``, ``"markedness"``]
45
+ Some of the metrics have multiple aliases (as shown in the wikipedia page aforementioned),
46
+ and you can also input those names instead.
47
+ compute_sample: when reducing, if ``True``, each sample's metric will be computed based on each confusion matrix first.
48
+ if ``False``, compute reduction on the confusion matrices first, defaults to ``False``.
49
+ reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values,
50
+ available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``,
51
+ ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction.
52
+ output_transform: callable to extract `y_pred` and `y` from `ignite.engine.state.output` then
53
+ construct `(y_pred, y)` pair, where `y_pred` and `y` can be `batch-first` Tensors or
54
+ lists of `channel-first` Tensors. the form of `(y_pred, y)` is required by the `update()`.
55
+ `engine.state` and `output_transform` inherit from the ignite concept:
56
+ https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial:
57
+ https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb.
58
+ save_details: whether to save metric computation details per image, for example: TP/TN/FP/FN of every image.
59
+ default to True, will save to `engine.state.metric_details` dict with the metric name as key.
60
+
61
+ See also:
62
+ :py:meth:`monai.metrics.confusion_matrix`
63
+ """
64
+ metric_fn = ConfusionMatrixMetric(
65
+ include_background=include_background,
66
+ metric_name=metric_name,
67
+ compute_sample=compute_sample,
68
+ reduction=reduction,
69
+ )
70
+ self.metric_name = metric_name
71
+ super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details)
source_code/SegMamba/monai/handlers/decollate_batch.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING
15
+
16
+ from monai.config import IgniteInfo, KeysCollection
17
+ from monai.engines.utils import IterationEvents
18
+ from monai.transforms import Decollated
19
+ from monai.utils import min_version, optional_import
20
+
21
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
22
+ if TYPE_CHECKING:
23
+ from ignite.engine import Engine
24
+ else:
25
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
26
+
27
+
28
+ class DecollateBatch:
29
+ """
30
+ Ignite handler to execute the `decollate batch` logic for `engine.state.batch` and `engine.state.output`.
31
+ Typical usage is to set `decollate=False` in the engine and execute some postprocessing logic first
32
+ then decollate the batch, otherwise, engine will decollate batch before the postprocessing.
33
+
34
+ Args:
35
+ event: expected EVENT to attach the handler, should be "MODEL_COMPLETED" or "ITERATION_COMPLETED".
36
+ default to "MODEL_COMPLETED".
37
+ detach: whether to detach the tensors. scalars tensors will be detached into number types
38
+ instead of torch tensors.
39
+ decollate_batch: whether to decollate `engine.state.batch` of ignite engine.
40
+ batch_keys: if `decollate_batch=True`, specify the keys of the corresponding items to decollate
41
+ in `engine.state.batch`, note that it will delete other keys not specified. if None,
42
+ will decollate all the keys. it replicates the scalar values to every item of the decollated list.
43
+ decollate_output: whether to decollate `engine.state.output` of ignite engine.
44
+ output_keys: if `decollate_output=True`, specify the keys of the corresponding items to decollate
45
+ in `engine.state.output`, note that it will delete other keys not specified. if None,
46
+ will decollate all the keys. it replicates the scalar values to every item of the decollated list.
47
+ allow_missing_keys: don't raise exception if key is missing.
48
+
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ event: str = "MODEL_COMPLETED",
54
+ detach: bool = True,
55
+ decollate_batch: bool = True,
56
+ batch_keys: KeysCollection | None = None,
57
+ decollate_output: bool = True,
58
+ output_keys: KeysCollection | None = None,
59
+ allow_missing_keys: bool = False,
60
+ ):
61
+ event = event.upper()
62
+ if event not in ("MODEL_COMPLETED", "ITERATION_COMPLETED"):
63
+ raise ValueError("event should be `MODEL_COMPLETED` or `ITERATION_COMPLETED`.")
64
+ self.event = event
65
+
66
+ self.batch_transform = (
67
+ Decollated(keys=batch_keys, detach=detach, allow_missing_keys=allow_missing_keys)
68
+ if decollate_batch
69
+ else None
70
+ )
71
+
72
+ self.output_transform = (
73
+ Decollated(keys=output_keys, detach=detach, allow_missing_keys=allow_missing_keys)
74
+ if decollate_output
75
+ else None
76
+ )
77
+
78
+ def attach(self, engine: Engine) -> None:
79
+ """
80
+ Args:
81
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
82
+ """
83
+ if self.event == "MODEL_COMPLETED":
84
+ engine.add_event_handler(IterationEvents.MODEL_COMPLETED, self)
85
+ else:
86
+ engine.add_event_handler(Events.ITERATION_COMPLETED, self)
87
+
88
+ def __call__(self, engine: Engine) -> None:
89
+ """
90
+ Args:
91
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
92
+ """
93
+ if self.batch_transform is not None and isinstance(engine.state.batch, (list, dict)):
94
+ engine.state.batch = self.batch_transform(engine.state.batch)
95
+ if self.output_transform is not None and isinstance(engine.state.output, (list, dict)):
96
+ engine.state.output = self.output_transform(engine.state.output)
source_code/SegMamba/monai/handlers/earlystop_handler.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+ from typing import TYPE_CHECKING
16
+
17
+ from monai.config import IgniteInfo
18
+ from monai.utils import min_version, optional_import
19
+
20
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
21
+ EarlyStopping, _ = optional_import("ignite.handlers", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EarlyStopping")
22
+
23
+ if TYPE_CHECKING:
24
+ from ignite.engine import Engine
25
+ else:
26
+ Engine, _ = optional_import(
27
+ "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine", as_type="decorator"
28
+ )
29
+
30
+
31
+ class EarlyStopHandler:
32
+ """
33
+ EarlyStopHandler acts as an Ignite handler to stop training if no improvement after a given number of events.
34
+ It‘s based on the `EarlyStopping` handler in ignite.
35
+
36
+ Args:
37
+ patience: number of events to wait if no improvement and then stop the training.
38
+ score_function: It should be a function taking a single argument, an :class:`~ignite.engine.engine.Engine`
39
+ object that the handler attached, can be a trainer or validator, and return a score `float`.
40
+ an improvement is considered if the score is higher.
41
+ trainer: trainer engine to stop the run if no improvement, if None, must call `set_trainer()` before training.
42
+ min_delta: a minimum increase in the score to qualify as an improvement,
43
+ i.e. an increase of less than or equal to `min_delta`, will count as no improvement.
44
+ cumulative_delta: if True, `min_delta` defines an increase since the last `patience` reset, otherwise,
45
+ it defines an increase after the last event, default to False.
46
+ epoch_level: check early stopping for every epoch or every iteration of the attached engine,
47
+ `True` is epoch level, `False` is iteration level, default to epoch level.
48
+
49
+ Note:
50
+ If in distributed training and uses loss value of every iteration to detect early stopping,
51
+ the values may be different in different ranks. When using this handler with distributed training,
52
+ please also note that to prevent "dist.destroy_process_group()" hangs, you can use an "all_reduce" operation
53
+ to synchronize the stop signal across all ranks. The mechanism can be implemented in the `score_function`. The following
54
+ is an example:
55
+
56
+ .. code-block:: python
57
+
58
+ import os
59
+
60
+ import torch
61
+ import torch.distributed as dist
62
+
63
+
64
+ def score_function(engine):
65
+ val_metric = engine.state.metrics["val_mean_dice"]
66
+ if dist.is_initialized():
67
+ device = torch.device("cuda:" + os.environ["LOCAL_RANK"])
68
+ val_metric = torch.tensor([val_metric]).to(device)
69
+ dist.all_reduce(val_metric, op=dist.ReduceOp.SUM)
70
+ val_metric /= dist.get_world_size()
71
+ return val_metric.item()
72
+ return val_metric
73
+
74
+
75
+ User may attach this handler to validator engine to detect validation metrics and stop the training,
76
+ in this case, the `score_function` is executed on validator engine and `trainer` is the trainer engine.
77
+
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ patience: int,
83
+ score_function: Callable,
84
+ trainer: Engine | None = None,
85
+ min_delta: float = 0.0,
86
+ cumulative_delta: bool = False,
87
+ epoch_level: bool = True,
88
+ ) -> None:
89
+ self.patience = patience
90
+ self.score_function = score_function
91
+ self.min_delta = min_delta
92
+ self.cumulative_delta = cumulative_delta
93
+ self.epoch_level = epoch_level
94
+ self._handler = None
95
+
96
+ if trainer is not None:
97
+ self.set_trainer(trainer=trainer)
98
+
99
+ def attach(self, engine: Engine) -> None:
100
+ """
101
+ Args:
102
+ engine: Ignite Engine, it can be a trainer, validator or evaluator.
103
+ """
104
+ if self.epoch_level:
105
+ engine.add_event_handler(Events.EPOCH_COMPLETED, self)
106
+ else:
107
+ engine.add_event_handler(Events.ITERATION_COMPLETED, self)
108
+
109
+ def set_trainer(self, trainer: Engine) -> None:
110
+ """
111
+ Set trainer to execute early stop if not setting properly in `__init__()`.
112
+ """
113
+ self._handler = EarlyStopping(
114
+ patience=self.patience,
115
+ score_function=self.score_function,
116
+ trainer=trainer,
117
+ min_delta=self.min_delta,
118
+ cumulative_delta=self.cumulative_delta,
119
+ )
120
+
121
+ def __call__(self, engine: Engine) -> None:
122
+ if self._handler is None:
123
+ raise RuntimeError("please set trainer in __init__() or call set_trainer() before training.")
124
+ self._handler(engine)
source_code/SegMamba/monai/handlers/garbage_collector.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ import gc
15
+ from typing import TYPE_CHECKING
16
+
17
+ from monai.config import IgniteInfo
18
+ from monai.utils import min_version, optional_import
19
+
20
+ if TYPE_CHECKING:
21
+ from ignite.engine import Engine, Events
22
+ from ignite.engine.events import CallableEventWithFilter
23
+ else:
24
+ CallableEventWithFilter, _ = optional_import(
25
+ "ignite.engine.events", IgniteInfo.OPT_IMPORT_VERSION, min_version, "CallableEventWithFilter"
26
+ )
27
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
28
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
29
+
30
+
31
+ class GarbageCollector:
32
+ """
33
+ Run garbage collector after each epoch
34
+
35
+ Args:
36
+ trigger_event: the event that trigger a call to this handler.
37
+ - "epoch", after completion of each epoch (equivalent of ignite.engine.Events.EPOCH_COMPLETED)
38
+ - "iteration", after completion of each iteration (equivalent of ignite.engine.Events.ITERATION_COMPLETED)
39
+ - any ignite built-in event from ignite.engine.Events.
40
+ Defaults to "epoch".
41
+ log_level: log level (integer) for some garbage collection information as below. Defaults to 10 (DEBUG).
42
+ - 50 (CRITICAL)
43
+ - 40 (ERROR)
44
+ - 30 (WARNING)
45
+ - 20 (INFO)
46
+ - 10 (DEBUG)
47
+ - 0 (NOTSET)
48
+ """
49
+
50
+ def __init__(self, trigger_event: str | Events | CallableEventWithFilter = "epoch", log_level: int = 10):
51
+ self.trigger_event: Events | CallableEventWithFilter
52
+ if isinstance(trigger_event, (Events, CallableEventWithFilter)):
53
+ self.trigger_event = trigger_event
54
+ elif trigger_event.lower() == "epoch":
55
+ self.trigger_event = Events.EPOCH_COMPLETED
56
+ elif trigger_event.lower() == "iteration":
57
+ self.trigger_event = Events.ITERATION_COMPLETED
58
+ else:
59
+ raise ValueError(
60
+ f"'trigger_event' should be either epoch, iteration, or an ignite built-in event from"
61
+ f" ignite.engine.Events, '{trigger_event}' was given."
62
+ )
63
+
64
+ self.log_level = log_level
65
+
66
+ def attach(self, engine: Engine) -> None:
67
+ if not engine.has_event_handler(self, self.trigger_event):
68
+ engine.add_event_handler(self.trigger_event, self)
69
+
70
+ def __call__(self, engine: Engine) -> None:
71
+ """
72
+ This method calls python garbage collector.
73
+
74
+ Args:
75
+ engine: Ignite Engine, it should be either a trainer or validator.
76
+ """
77
+ # get count before garbage collection
78
+ pre_count = gc.get_count()
79
+ # first call to garbage collector
80
+ gc.collect()
81
+ # second call to garbage collector
82
+ unreachable = gc.collect()
83
+ # get count after garbage collection
84
+ after_count = gc.get_count()
85
+ engine.logger.log(
86
+ self.log_level,
87
+ f"Garbage Count: [before: {pre_count}] -> [after: {after_count}] (unreachable : {unreachable})",
88
+ )