Skip to content

train

xvr.cli.commands.train

train

train(
    volpath,
    maskpath,
    ckptpath,
    outpath,
    r1,
    r2,
    r3,
    tx,
    ty,
    tz,
    sdd,
    height,
    delx,
    renderer,
    orientation,
    reverse_x_axis,
    model_name,
    norm_layer,
    pretrained,
    parameterization,
    convention,
    unit_conversion_factor,
    p_augmentation,
    lr,
    weight_ncc,
    weight_geo,
    weight_dice,
    weight_mvc,
    batch_size,
    n_total_itrs,
    n_warmup_itrs,
    n_grad_accum_itrs,
    n_save_every_itrs,
    disable_scheduler,
    reuse_optimizer,
    warp,
    invert,
    patch_size,
    num_workers,
    pin_memory,
    sample_weights,
    name,
    id,
    project,
)

Train a pose regression model.

Source code in src/xvr/cli/commands/train.py
  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
@click.command(
    cls=CategorizedCommand,
    category_order=[
        "Required",
        "Data",
        "Sampling",
        "Renderer",
        "Model",
        "Optimizer",
        "Checkpoint",
        "Logging",
    ],
)
@categorized_option(
    "-v",
    "--volpath",
    required=True,
    type=click.Path(exists=True),
    help="A single CT or a directory with multiple volumes for pretraining",
    category="Required",
)
@categorized_option(
    "-m",
    "--maskpath",
    required=False,
    type=click.Path(exists=True),
    help="Optional labelmaps corresponding to the CTs passed in `volpath`",
    category="Data",
)
@categorized_option(
    "-c",
    "--ckptpath",
    required=False,
    type=click.Path(exists=True),
    help="Checkpoint of a pretrained pose regressor",
    category="Checkpoint",
)
@categorized_option(
    "-o",
    "--outpath",
    required=True,
    type=click.Path(),
    help="Directory in which to save model weights",
    category="Required",
)
@categorized_option(
    "--r1",
    required=True,
    type=(float, float),
    help="Range for primary angle (in degrees)",
    category="Sampling",
)
@categorized_option(
    "--r2",
    required=True,
    type=(float, float),
    help="Range for secondary angle (in degrees)",
    category="Sampling",
)
@categorized_option(
    "--r3",
    required=True,
    type=(float, float),
    help="Range for tertiary angle (in degrees)",
    category="Sampling",
)
@categorized_option(
    "--tx",
    required=True,
    type=(float, float),
    help="Range for x-offset (in millimeters)",
    category="Sampling",
)
@categorized_option(
    "--ty",
    required=True,
    type=(float, float),
    help="Range for y-offset (in millimeters)",
    category="Sampling",
)
@categorized_option(
    "--tz",
    required=True,
    type=(float, float),
    help="Range for z-offset (in millimeters)",
    category="Sampling",
)
@categorized_option(
    "--sdd",
    required=True,
    type=float,
    help="Source-to-detector distance (in millimeters)",
    category="Renderer",
)
@categorized_option(
    "--height",
    required=True,
    type=int,
    help="DRR height (in pixels)",
    category="Renderer",
)
@categorized_option(
    "--delx",
    required=True,
    type=float,
    help="DRR pixel size (in millimeters / pixel)",
    category="Renderer",
)
@categorized_option(
    "--renderer",
    default=args.renderer,
    type=click.Choice(["siddon", "trilinear"]),
    help="Rendering equation",
    category="Renderer",
)
@categorized_option(
    "--orientation",
    default=args.orientation,
    type=click.Choice(["AP", "PA"]),
    help="Orientation of CT volumes",
    category="Renderer",
)
@categorized_option(
    "--reverse_x_axis",
    default=args.reverse_x_axis,
    is_flag=True,
    help="Enable to obey radiologic convention (e.g., heart on right)",
    category="Renderer",
)
@categorized_option(
    "--model_name",
    default=args.model_name,
    type=str,
    help="Name of model to instantiate from the timm library",
    category="Model",
)
@categorized_option(
    "--norm_layer",
    default=args.norm_layer,
    type=str,
    help="Normalization layer",
    category="Model",
)
@categorized_option(
    "--pretrained",
    default=args.pretrained,
    is_flag=True,
    help="Load pretrained ImageNet-1k weights",
    category="Model",
)
@categorized_option(
    "--parameterization",
    default=args.parameterization,
    type=str,
    help="Parameterization of SO(3) for regression",
    category="Model",
)
@categorized_option(
    "--convention",
    default=args.convention,
    type=str,
    help="If `parameterization='euler_angles'`, specify order",
    category="Model",
)
@categorized_option(
    "--unit_conversion_factor",
    default=args.unit_conversion_factor,
    type=float,
    help="Scale factor for translation prediction (e.g., from m to mm)",
    category="Model",
)
@categorized_option(
    "--p_augmentation",
    default=args.p_augmentation,
    type=float,
    help="Base probability of image augmentations during training",
    category="Model",
)
@categorized_option(
    "--lr",
    default=args.lr,
    type=float,
    help="Maximum learning rate",
    category="Optimizer",
)
@categorized_option(
    "--weight_ncc",
    default=args.weight_ncc,
    type=float,
    help="Weight on mNCC loss term",
    category="Optimizer",
)
@categorized_option(
    "--weight_geo",
    default=args.weight_geo,
    type=float,
    help="Weight on geodesic loss term",
    category="Optimizer",
)
@categorized_option(
    "--weight_dice",
    default=args.weight_dice,
    type=float,
    help="Weight on Dice loss term",
    category="Optimizer",
)
@categorized_option(
    "--weight_mvc",
    default=args.weight_mvc,
    type=float,
    help="Weight on multiview consistency loss term",
    category="Optimizer",
)
@categorized_option(
    "--batch_size",
    default=args.batch_size,
    type=int,
    help="Number of DRRs per batch",
    category="Sampling",
)
@categorized_option(
    "--n_total_itrs",
    default=args.n_total_itrs,
    type=int,
    help="Number of iterations for training the model",
    category="Optimizer",
)
@categorized_option(
    "--n_warmup_itrs",
    default=args.n_warmup_itrs,
    type=int,
    help="Number of iterations for warming up the learning rate",
    category="Optimizer",
)
@categorized_option(
    "--n_grad_accum_itrs",
    default=args.n_grad_accum_itrs,
    type=int,
    help="Number of iterations for gradient accumulation",
    category="Optimizer",
)
@categorized_option(
    "--n_save_every_itrs",
    default=args.n_save_every_itrs,
    type=int,
    help="Number of iterations before saving a new model checkpoint",
    category="Optimizer",
)
@categorized_option(
    "--disable_scheduler",
    default=args.disable_scheduler,
    is_flag=True,
    help="Turn off cosine learning rate scheduler",
    category="Optimizer",
)
@categorized_option(
    "--reuse_optimizer",
    default=args.reuse_optimizer,
    is_flag=True,
    help="If ckptpath passed, initialize the previous optimizer's state",
    category="Checkpoint",
)
@categorized_option(
    "-w",
    "--warp",
    type=click.Path(exists=True),
    help="SimpleITK transform to warp input CT to the checkpoint's reference frame",
    category="Checkpoint",
)
@categorized_option(
    "--invert",
    default=args.invert,
    is_flag=True,
    help="Whether to invert the warp or not",
    category="Checkpoint",
)
@categorized_option(
    "--patch_size",
    default=None,
    type=str,
    help="Optional random crop size (e.g., 'h,w,d'); if None, return entire volume",
    category="Data",
)
@categorized_option(
    "--num_workers",
    default=args.num_workers,
    type=int,
    help="Number of subprocesses to use in the dataloader",
    category="Data",
)
@categorized_option(
    "--pin_memory",
    default=args.pin_memory,
    is_flag=True,
    help="Copy volumes from the dataloader into CUDA pinned memory before returning",
    category="Data",
)
@categorized_option(
    "--sample_weights",
    default=None,
    type=click.Path(exists=True),
    help="Probability for sampling each volume in `volpath`",
    category="Data",
)
@categorized_option(
    "--name",
    default=None,
    type=str,
    help="WandB run name",
    category="Logging",
)
@categorized_option(
    "--id",
    default=None,
    type=str,
    help="WandB run ID (useful when restarting from a checkpoint)",
    category="Logging",
)
@categorized_option(
    "--project",
    default=args.project,
    type=str,
    help="WandB project name",
    category="Logging",
)
def train(
    volpath,
    maskpath,
    ckptpath,
    outpath,
    r1,
    r2,
    r3,
    tx,
    ty,
    tz,
    sdd,
    height,
    delx,
    renderer,
    orientation,
    reverse_x_axis,
    model_name,
    norm_layer,
    pretrained,
    parameterization,
    convention,
    unit_conversion_factor,
    p_augmentation,
    lr,
    weight_ncc,
    weight_geo,
    weight_dice,
    weight_mvc,
    batch_size,
    n_total_itrs,
    n_warmup_itrs,
    n_grad_accum_itrs,
    n_save_every_itrs,
    disable_scheduler,
    reuse_optimizer,
    warp,
    invert,
    patch_size,
    num_workers,
    pin_memory,
    sample_weights,
    name,
    id,
    project,
):
    """Train a pose regression model."""
    import os
    from pathlib import Path

    import wandb

    from ...model import Trainer

    # Create the output directory for saving model weights
    Path(outpath).mkdir(parents=True, exist_ok=True)

    # If ckptpath is a directory, get the last saved model
    if ckptpath is not None:
        ckptpath = Path(ckptpath)
        if ckptpath.is_dir():
            ckptpath = max(ckptpath.glob("*.pth"), key=lambda p: p.name)
        ckptpath = str(ckptpath)

    # Parse patch_size
    if patch_size is not None:
        patch_size = tuple(int(x) for x in patch_size.split(","))

    # Parse 6-DoF pose parameters
    alphamin, alphamax = r1
    betamin, betamax = r2
    gammamin, gammamax = r3
    txmin, txmax = tx
    tymin, tymax = ty
    tzmin, tzmax = tz

    # Parse the sample weights
    weights = (
        [float(line) for line in Path(sample_weights).read_text().splitlines()]
        if sample_weights is not None
        else None
    )

    # Parse configuration parameters
    config = dict(
        volpath=volpath,
        maskpath=maskpath,
        ckptpath=ckptpath,
        outpath=outpath,
        alphamin=alphamin,
        alphamax=alphamax,
        betamin=betamin,
        betamax=betamax,
        gammamin=gammamin,
        gammamax=gammamax,
        txmin=txmin,
        txmax=txmax,
        tymin=tymin,
        tymax=tymax,
        tzmin=tzmin,
        tzmax=tzmax,
        sdd=sdd,
        height=height,
        delx=delx,
        renderer=renderer,
        orientation=orientation,
        reverse_x_axis=reverse_x_axis,
        parameterization=parameterization,
        convention=convention,
        model_name=model_name,
        pretrained=pretrained,
        norm_layer=norm_layer,
        unit_conversion_factor=unit_conversion_factor,
        p_augmentation=p_augmentation,
        lr=lr,
        weight_ncc=weight_ncc,
        weight_geo=weight_geo,
        weight_dice=weight_dice,
        weight_mvc=weight_mvc,
        batch_size=batch_size,
        n_total_itrs=n_total_itrs,
        n_warmup_itrs=n_warmup_itrs,
        n_grad_accum_itrs=n_grad_accum_itrs,
        n_save_every_itrs=n_save_every_itrs,
        disable_scheduler=disable_scheduler,
        reuse_optimizer=reuse_optimizer,
        patch_size=patch_size,
        num_workers=num_workers,
        pin_memory=pin_memory,
        weights=weights,
        warp=warp,
        invert=invert,
    )

    # Set up logging
    wandb.login(key=os.environ["WANDB_API_KEY"])
    run = wandb.init(
        project=project,
        name=name if name is not None else project,
        config=config,
        id=id,
        resume="must" if id is not None else None,
    )

    # Train the model
    trainer = Trainer(**config)
    trainer.train(run)