Repository navigation
Expand file tree
/
Copy pathHiRAM_inference.py
More file actions
578 lines (499 loc) · 29.5 KB
/
Copy pathHiRAM_inference.py
File metadata and controls
578 lines (499 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import inspect
import itertools
import multiprocessing
import os
from copy import deepcopy
from time import sleep
from typing import Tuple, Union, List, Optional
import numpy as np
import torch
from tqdm import tqdm
import yaml
import sys
import importlib
from acvl_utils.cropping_and_padding.padding import pad_nd_image
from batchgenerators.dataloading.multi_threaded_augmenter import MultiThreadedAugmenter
from batchgenerators.utilities.file_and_folder_operations import load_json, join, isfile, maybe_mkdir_p, save_json
from torch._dynamo import OptimizedModule
import nnunetv2
from nnunetv2.configuration import default_num_processes
from nnunetv2.inference.data_iterators import PreprocessAdapterFromNpy, preprocessing_iterator_fromfiles, \
preprocessing_iterator_fromnpy
from nnunetv2.inference.export_prediction import export_prediction_from_logits, \
convert_predicted_logits_to_segmentation_with_correct_shape
from nnunetv2.inference.sliding_window_prediction import compute_gaussian, \
compute_steps_for_sliding_window
from nnunetv2.utilities.file_path_utilities import check_workers_alive_and_busy
from nnunetv2.utilities.find_class_by_name import recursive_find_python_class
from nnunetv2.utilities.helpers import empty_cache, dummy_context
from nnunetv2.utilities.json_export import recursive_fix_for_json_export
from nnunetv2.utilities.label_handling.label_handling import determine_num_input_channels
from nnunetv2.utilities.plans_handling.plans_handler import PlansManager
from nnunetv2.utilities.utils import create_lists_from_splitted_dataset_folder
import sys, os
from nnunetv2.utilities.get_network_from_plans import get_network_from_plans_withSAM
class nnUNetPredictor(object):
def __init__(self,
tile_step_size: float = 0.5,
use_gaussian: bool = True,
use_mirroring: bool = True,
perform_everything_on_device: bool = True,
device: torch.device = torch.device('cuda'),
verbose: bool = False,
verbose_preprocessing: bool = False,
allow_tqdm: bool = True,
withSAM: bool = True,
sam_conf: dict = None,
config_path: str = None,
):
self.verbose = verbose
self.verbose_preprocessing = verbose_preprocessing
self.allow_tqdm = allow_tqdm
self.plans_manager, self.configuration_manager, self.list_of_parameters, self.network, self.dataset_json, \
self.trainer_name, self.allowed_mirroring_axes, self.label_manager = None, None, None, None, None, None, None, None
self.tile_step_size = tile_step_size
self.use_gaussian = use_gaussian
self.use_mirroring = use_mirroring
if device.type == 'cuda':
torch.backends.cudnn.benchmark = True
else:
print(f'perform_everything_on_device=True is only supported for cuda devices! Setting this to False')
perform_everything_on_device = False
self.device = device
self.perform_everything_on_device = perform_everything_on_device
self.ensemble_method = 'average'
self.withSAM = withSAM
self.sam_conf = sam_conf
self.config_path = config_path
def initialize_from_trained_model_folder(self, model_training_output_dir: str, fold: int,
checkpoint_name: str = 'checkpoint_final.pth'):
dataset_json = load_json(join(model_training_output_dir, 'dataset.json'))
plans = load_json(join(model_training_output_dir, 'plans.json'))
plans_manager = PlansManager(plans)
parameters, patch_sizes = [], []
checkpoint = torch.load(join(model_training_output_dir, f'fold_{fold}', checkpoint_name),
map_location=torch.device('cpu'), weights_only=False)
trainer_name = checkpoint['trainer_name']
configuration_name = checkpoint['init_args']['configuration']
inference_allowed_mirroring_axes = checkpoint['inference_allowed_mirroring_axes'] if \
'inference_allowed_mirroring_axes' in checkpoint.keys() else None
plan = load_json(join(model_training_output_dir, 'plans.json'))
plan_manager = PlansManager(plan)
patch_sizes.append(plan_manager.get_configuration(configuration_name).patch_size)
parameters.append(checkpoint['network_weights'])
configuration_manager = plans_manager.get_configuration(configuration_name)
num_input_channels = determine_num_input_channels(plans_manager, configuration_manager, dataset_json)
self.label_manager = plans_manager.get_label_manager(dataset_json)
network = get_network_from_plans_withSAM(
configuration_manager.network_arch_init_kwargs,
configuration_manager.network_arch_init_kwargs_req_import,
num_input_channels,
self.label_manager.num_segmentation_heads,
self.sam_conf,
allow_init=True,
deep_supervision=False,
)
self.plans_manager = plans_manager
self.configuration_manager = configuration_manager
self.list_of_parameters = parameters
self.list_of_patch_size = patch_sizes
self.network = network
self.dataset_json = dataset_json
self.trainer_name = trainer_name
self.allowed_mirroring_axes = inference_allowed_mirroring_axes
if ('nnUNet_compile' in os.environ.keys()) and (os.environ['nnUNet_compile'].lower() in ('true', '1', 't')) \
and not isinstance(self.network, OptimizedModule):
print('Using torch.compile')
self.network = torch.compile(self.network)
def _manage_input_and_output_lists(self, list_of_lists_or_source_folder: Union[str, List[List[str]]],
output_folder_or_list_of_truncated_output_files: Union[None, str, List[str]],
folder_with_segs_from_prev_stage: str = None,
overwrite: bool = True,
part_id: int = 0,
num_parts: int = 1,):
if isinstance(list_of_lists_or_source_folder, str):
list_of_lists_or_source_folder = create_lists_from_splitted_dataset_folder(list_of_lists_or_source_folder,
self.dataset_json['file_ending'])
print(f'There are {len(list_of_lists_or_source_folder)} cases in the source folder')
list_of_lists_or_source_folder = list_of_lists_or_source_folder[part_id::num_parts]
caseids = [os.path.basename(i[0])[:-(len(self.dataset_json['file_ending']) + 5)] for i in
list_of_lists_or_source_folder]
print(
f'I am process {part_id} out of {num_parts} (max process ID is {num_parts - 1}, we start counting with 0!)')
print(f'There are {len(caseids)} cases that I would like to predict')
if isinstance(output_folder_or_list_of_truncated_output_files, str):
output_filename_truncated = [join(output_folder_or_list_of_truncated_output_files, i) for i in caseids]
else:
output_filename_truncated = output_folder_or_list_of_truncated_output_files
seg_from_prev_stage_files = [join(folder_with_segs_from_prev_stage, i + self.dataset_json['file_ending']) if
folder_with_segs_from_prev_stage is not None else None for i in caseids]
# remove already predicted files form the lists
if not overwrite and output_filename_truncated is not None:
tmp = [isfile(i + self.dataset_json['file_ending']) for i in output_filename_truncated]
not_existing_indices = [i for i, j in enumerate(tmp) if not j]
output_filename_truncated = [output_filename_truncated[i] for i in not_existing_indices]
list_of_lists_or_source_folder = [list_of_lists_or_source_folder[i] for i in not_existing_indices]
seg_from_prev_stage_files = [seg_from_prev_stage_files[i] for i in not_existing_indices]
print(f'overwrite was set to {overwrite}, so I am only working on cases that haven\'t been predicted yet. '
f'That\'s {len(not_existing_indices)} cases.')
return list_of_lists_or_source_folder, output_filename_truncated, seg_from_prev_stage_files
def predict_from_files(self,
list_of_lists_or_source_folder: Union[str, List[List[str]]],
output_folder_or_list_of_truncated_output_files: Union[str, None, List[str]],
overwrite: bool = True,
num_processes_preprocessing: int = default_num_processes,
num_processes_segmentation_export: int = default_num_processes,
folder_with_segs_from_prev_stage: str = None,
num_parts: int = 1,
part_id: int = 0):
"""
This is nnU-Net's default function for making predictions. It works best for batch predictions
(predicting many images at once).
"""
if isinstance(output_folder_or_list_of_truncated_output_files, str):
output_folder = output_folder_or_list_of_truncated_output_files
elif isinstance(output_folder_or_list_of_truncated_output_files, list):
output_folder = os.path.dirname(output_folder_or_list_of_truncated_output_files[0])
else:
output_folder = None
# let's store the input arguments so that its clear what was used to generate the prediction
if output_folder is not None:
my_init_kwargs = {}
for k in inspect.signature(self.predict_from_files).parameters.keys():
my_init_kwargs[k] = locals()[k]
my_init_kwargs = deepcopy(
my_init_kwargs) # let's not unintentionally change anything in-place. Take this as a
recursive_fix_for_json_export(my_init_kwargs)
maybe_mkdir_p(output_folder)
save_json(my_init_kwargs, join(output_folder, 'predict_from_raw_data_args.json'))
# we need these two if we want to do things with the predictions like for example apply postprocessing
save_json(self.dataset_json, join(output_folder, 'dataset.json'), sort_keys=False)
save_json(self.plans_manager.plans, join(output_folder, 'plans.json'), sort_keys=False)
# check if we need a prediction from the previous stage
if self.configuration_manager.previous_stage_name is not None:
assert folder_with_segs_from_prev_stage is not None, \
f'The requested configuration is a cascaded network. It requires the segmentations of the previous ' \
f'stage ({self.configuration_manager.previous_stage_name}) as input. Please provide the folder where' \
f' they are located via folder_with_segs_from_prev_stage'
list_of_lists_or_source_folder, output_filename_truncated, seg_from_prev_stage_files = \
self._manage_input_and_output_lists(list_of_lists_or_source_folder,
output_folder_or_list_of_truncated_output_files,
folder_with_segs_from_prev_stage, overwrite, part_id, num_parts,)
if len(list_of_lists_or_source_folder) == 0:
return
data_iterator = self._internal_get_data_iterator_from_lists_of_filenames(list_of_lists_or_source_folder,
seg_from_prev_stage_files,
output_filename_truncated,
num_processes_preprocessing)
return self.predict_from_data_iterator(data_iterator, num_processes_segmentation_export)
def _internal_get_data_iterator_from_lists_of_filenames(self,
input_list_of_lists: List[List[str]],
seg_from_prev_stage_files: Union[List[str], None],
output_filenames_truncated: Union[List[str], None],
num_processes: int):
return preprocessing_iterator_fromfiles(input_list_of_lists, seg_from_prev_stage_files,
output_filenames_truncated, self.plans_manager, self.dataset_json,
self.configuration_manager, num_processes, self.device.type == 'cuda',
self.verbose_preprocessing)
def predict_from_data_iterator(self,
data_iterator,
num_processes_segmentation_export: int = default_num_processes):
"""
each element returned by data_iterator must be a dict with 'data', 'ofile' and 'data_properties' keys!
If 'ofile' is None, the result will be returned instead of written to a file
"""
with multiprocessing.get_context("spawn").Pool(num_processes_segmentation_export) as export_pool:
worker_list = [i for i in export_pool._pool]
r = []
for preprocessed in data_iterator:
data = preprocessed['data']
if isinstance(data, str):
delfile = data
data = torch.from_numpy(np.load(data))
os.remove(delfile)
ofile = preprocessed['ofile']
if ofile is not None:
print(f'\nPredicting {os.path.basename(ofile)}:')
else:
print(f'\nPredicting image of shape {data.shape}:')
print(f'perform_everything_on_device: {self.perform_everything_on_device}')
properties = preprocessed['data_properties']
# let's not get into a runaway situation where the GPU predicts so fast that the disk has to b swamped with
# npy files
proceed = not check_workers_alive_and_busy(export_pool, worker_list, r, allowed_num_queued=2)
while not proceed:
sleep(0.1)
proceed = not check_workers_alive_and_busy(export_pool, worker_list, r, allowed_num_queued=2)
nnUNet_logits, prediction = self.predict_logits_from_preprocessed_data(data, base_name=os.path.basename(ofile))
prediction = prediction.cpu()
nnUNet_logits = nnUNet_logits.cpu()
if ofile is not None:
# this needs to go into background processes
print('sending off prediction to background worker for resampling and export')
r.append(
export_pool.starmap_async(
export_prediction_from_logits,
((prediction, properties, self.configuration_manager, self.plans_manager,
self.dataset_json, ofile,
self.withSAM, nnUNet_logits),)
)
)
else:
print('sending off prediction to background worker for resampling')
r.append(
export_pool.starmap_async(
convert_predicted_logits_to_segmentation_with_correct_shape, (
(prediction, self.plans_manager,
self.configuration_manager, self.label_manager,
properties,
self.withSAM, nnUNet_logits),)
)
)
if ofile is not None:
print(f'done with {os.path.basename(ofile)}')
else:
print(f'\nDone with image of shape {data.shape}:')
ret = [i.get()[0] for i in r]
if isinstance(data_iterator, MultiThreadedAugmenter):
data_iterator._finish()
# clear lru cache
compute_gaussian.cache_clear()
# clear device cache
empty_cache(self.device)
return ret
def predict_logits_from_preprocessed_data(self, data: torch.Tensor, base_name: Optional[str]=None) -> torch.Tensor:
"""
IMPORTANT! IF YOU ARE RUNNING THE CASCADE, THE SEGMENTATION FROM THE PREVIOUS STAGE MUST ALREADY BE STACKED ON
TOP OF THE IMAGE AS ONE-HOT REPRESENTATION! SEE PreprocessAdapter ON HOW THIS SHOULD BE DONE!
RETURNED LOGITS HAVE THE SHAPE OF THE INPUT. THEY MUST BE CONVERTED BACK TO THE ORIGINAL IMAGE SIZE.
SEE convert_predicted_logits_to_segmentation_with_correct_shape
"""
n_threads = torch.get_num_threads()
torch.set_num_threads(default_num_processes if default_num_processes < n_threads else n_threads)
prediction = None
all_predictions = []
for (params, patch_size) in zip(self.list_of_parameters, self.list_of_patch_size):
# messing with state dict names...
if not isinstance(self.network, OptimizedModule):
with torch.inference_mode():
self.network.load_state_dict(params)
else:
self.network._orig_mod.load_state_dict(params)
# why not leave prediction on device if perform_everything_on_device? Because this may cause the
# second iteration to crash due to OOM. Grabbing that with try except cause way more bloated code than
# this actually saves computation time
if self.ensemble_method == 'average':
if prediction is None:
nnUNet_logits, prediction = self.predict_sliding_window_return_logits(data, patch_size)
nnUNet_logits = nnUNet_logits.to('cpu')
prediction = prediction.to('cpu')
else:
nnUNet_logits, prediction = self.predict_sliding_window_return_logits(data, patch_size)
nnUNet_logits += nnUNet_logits.to('cpu')
prediction += prediction.to('cpu')
elif self.ensemble_method == 'max':
nnUNet_logits, pred = self.predict_sliding_window_return_logits(data, patch_size)
all_predictions.append(pred)
if len(self.list_of_parameters) > 1:
if self.ensemble_method == 'average':
prediction /= len(self.list_of_parameters)
if self.verbose: print('Prediction done')
torch.set_num_threads(n_threads)
return nnUNet_logits, prediction
def _internal_get_sliding_window_slicers(self, image_size: Tuple[int, ...], patch_size):
slicers = []
if len(patch_size) < len(image_size):
assert len(patch_size) == len(
image_size) - 1, 'if tile_size has less entries than image_size, ' \
'len(tile_size) ' \
'must be one shorter than len(image_size) ' \
'(only dimension ' \
'discrepancy of 1 allowed).'
steps = compute_steps_for_sliding_window(image_size[1:], patch_size,
self.tile_step_size)
if self.verbose: print(f'n_steps {image_size[0] * len(steps[0]) * len(steps[1])}, image size is'
f' {image_size}, tile_size {self.configuration_manager.patch_size}, '
f'tile_step_size {self.tile_step_size}\nsteps:\n{steps}')
for d in range(image_size[0]):
for sx in steps[0]:
for sy in steps[1]:
slicers.append(
tuple([slice(None), d, *[slice(si, si + ti) for si, ti in
zip((sx, sy), patch_size)]]))
else:
steps = compute_steps_for_sliding_window(image_size, patch_size,
self.tile_step_size)
if self.verbose: print(
f'n_steps {np.prod([len(i) for i in steps])}, image size is {image_size}, tile_size {patch_size}, '
f'tile_step_size {self.tile_step_size}\nsteps:\n{steps}')
for sx in steps[0]:
for sy in steps[1]:
for sz in steps[2]:
slicers.append(
tuple([slice(None), *[slice(si, si + ti) for si, ti in
zip((sx, sy, sz), patch_size)]]))
return slicers
def _internal_maybe_mirror_and_predict(self, x: torch.Tensor) -> torch.Tensor:
mirror_axes = self.allowed_mirroring_axes if self.use_mirroring else None
with torch.no_grad():
if self.withSAM:
nnUNet_out, _, prediction, _ = self.network(x)
else:
prediction = self.network(x)
nnUNet_out = None
if mirror_axes is not None:
# check for invalid numbers in mirror_axes
# x should be 5d for 3d images and 4d for 2d. so the max value of mirror_axes cannot exceed len(x.shape) - 3
assert max(mirror_axes) <= x.ndim - 3, 'mirror_axes does not match the dimension of the input!'
mirror_axes = [m + 2 for m in mirror_axes]
axes_combinations = [
c for i in range(len(mirror_axes)) for c in itertools.combinations(mirror_axes, i + 1)
]
for axes in axes_combinations:
if self.withSAM:
_, _, flipped_prediction, _ = self.network(torch.flip(x, axes))
else:
flipped_prediction = self.network(torch.flip(x, axes))
prediction += torch.flip(flipped_prediction, axes)
prediction /= (len(axes_combinations) + 1)
return nnUNet_out, prediction
def _internal_predict_sliding_window_return_logits(self,
data: torch.Tensor,
slicers,
patch_size,
do_on_device: bool = True,
):
predicted_logits = n_predictions = prediction = gaussian = workon = None
results_device = self.device if do_on_device else torch.device('cpu')
try:
empty_cache(self.device)
# move data to device
if self.verbose:
print(f'move image to device {results_device}')
data = data.to(results_device)
# preallocate arrays
if self.verbose:
print(f'preallocating results arrays on device {results_device}')
if self.withSAM:
predicted_logits = torch.zeros((1, *data.shape[1:]),
dtype=torch.half, device=results_device)
nnUNet_logits = torch.zeros((self.label_manager.num_segmentation_heads, *data.shape[1:]),
dtype=torch.half, device=results_device)
else:
predicted_logits = torch.zeros((self.label_manager.num_segmentation_heads, *data.shape[1:]),
dtype=torch.half, device=results_device)
n_predictions = torch.zeros(data.shape[1:], dtype=torch.half, device=results_device)
if self.use_gaussian:
gaussian = compute_gaussian(tuple(patch_size), sigma_scale=1. / 8,
value_scaling_factor=10,
device=results_device)
else:
gaussian = 1
if not self.allow_tqdm and self.verbose:
print(f'running prediction: {len(slicers)} steps')
for i, sl in tqdm(enumerate(slicers), disable=not self.allow_tqdm):
workon = data[sl][None]
workon = workon.to(self.device)
nnUNet_out, prediction = self._internal_maybe_mirror_and_predict(workon)
prediction = prediction[0].to(results_device)
if self.use_gaussian:
prediction *= gaussian
predicted_logits[sl] += prediction.squeeze()
n_predictions[sl[1:]] += gaussian
if self.withSAM:
nnUNet_out = nnUNet_out[0].to(results_device)
if self.use_gaussian:
nnUNet_out *= gaussian
nnUNet_logits[sl] += nnUNet_out.squeeze()
predicted_logits /= n_predictions
if self.withSAM:
nnUNet_logits /= n_predictions
else:
nnUNet_logits = None
except Exception as e:
del predicted_logits, n_predictions, prediction, gaussian, workon
empty_cache(self.device)
empty_cache(results_device)
raise e
return nnUNet_logits, predicted_logits
@torch.inference_mode()
def predict_sliding_window_return_logits(self, input_image: torch.Tensor, patch_size) \
-> Union[np.ndarray, torch.Tensor]:
assert isinstance(input_image, torch.Tensor)
self.network = self.network.to(self.device)
self.network.eval()
empty_cache(self.device)
# Autocast can be annoying
# If the device_type is 'cpu' then it's slow as heck on some CPUs (no auto bfloat16 support detection)
# and needs to be disabled.
# If the device_type is 'mps' then it will complain that mps is not implemented, even if enabled=False
# is set. Whyyyyyyy. (this is why we don't make use of enabled=False)
# So autocast will only be active if we have a cuda device.
# with torch.autocast(self.device.type, enabled=True) if self.device.type == 'cuda' else dummy_context():
with torch.autocast(self.device.type, enabled=False) if self.device.type == 'cuda' else dummy_context():
assert input_image.ndim == 4, 'input_image must be a 4D np.ndarray or torch.Tensor (c, x, y, z)'
if self.verbose:
print(f'Input shape: {input_image.shape}')
print("step_size:", self.tile_step_size)
print("mirror_axes:", self.allowed_mirroring_axes if self.use_mirroring else None)
# if input_image is smaller than tile_size we need to pad it to tile_size.
data, slicer_revert_padding = pad_nd_image(input_image, patch_size,
'constant', {'value': 0}, True,
None)
slicers = self._internal_get_sliding_window_slicers(data.shape[1:], patch_size)
if self.perform_everything_on_device and self.device != 'cpu':
# we need to try except here because we can run OOM in which case we need to fall back to CPU as a results device
try:
nnUNet_logits, predicted_logits = self._internal_predict_sliding_window_return_logits(data, slicers, patch_size,
self.perform_everything_on_device)
except RuntimeError:
print(
'Prediction on device was unsuccessful, probably due to a lack of memory. Moving results arrays to CPU')
empty_cache(self.device)
nnUNet_logits, predicted_logits = self._internal_predict_sliding_window_return_logits(data, slicers, patch_size, False)
else:
nnUNet_logits, predicted_logits = self._internal_predict_sliding_window_return_logits(data, slicers, patch_size,
self.perform_everything_on_device)
empty_cache(self.device)
# revert padding
predicted_logits = predicted_logits[(slice(None), *slicer_revert_padding[1:])]
if self.withSAM:
nnUNet_logits = nnUNet_logits[(slice(None), *slicer_revert_padding[1:])]
return nnUNet_logits, predicted_logits
if __name__ == '__main__':
config_path = './HIRAM_config.yaml'
input_path = 'your_input_path'
output_path = 'your_output_path'
checkpoint_save_path = 'your_checkpoint_path'
fold = 0
sam_conf = {
"model_type": "HiRAM",
"model_name": "LoRA",
"Update": {
"image_encoder": False,
"prompt_encoder": False,
"mask_decoder": False
},
}
predictor = nnUNetPredictor(
tile_step_size=0.5,
use_gaussian=True,
use_mirroring=False,
perform_everything_on_device=True,
device=torch.device('cuda', 0),
verbose=False,
verbose_preprocessing=False,
allow_tqdm=True,
withSAM=True,
sam_conf=sam_conf,
config_path=config_path,
)
predictor.initialize_from_trained_model_folder(
checkpoint_save_path,
fold,
checkpoint_name="checkpoint_best.pth",
)
predictor.predict_from_files(input_path, output_path,
overwrite=True, num_processes_preprocessing=2, num_processes_segmentation_export=2,
folder_with_segs_from_prev_stage=None, num_parts=1, part_id=0)
print('------------ Finish ------------')