Ejemplo n.º 1
0
def cli_main(args):
    pl.seed_everything(args.seed)

    # ------------
    # data
    # ------------
    # this creates a k-space mask for transforming input data
    mask = create_mask_for_mask_type(args.mask_type, args.center_fractions,
                                     args.accelerations)
    # use random masks for train transform, fixed masks for val transform
    train_transform = UnetDataTransform(args.challenge,
                                        mask_func=mask,
                                        use_seed=False)
    val_transform = UnetDataTransform(args.challenge, mask_func=mask)
    test_transform = UnetDataTransform(args.challenge)
    # ptl data module - this handles data loaders
    data_module = FastMriDataModule(
        data_path=args.data_path,
        challenge=args.challenge,
        train_transform=train_transform,
        val_transform=val_transform,
        test_transform=test_transform,
        test_split=args.test_split,
        test_path=args.test_path,
        sample_rate=args.sample_rate,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        distributed_sampler=(args.accelerator in ("ddp", "ddp_cpu")),
        proportion=args.proportion,
    )

    # ------------
    # model
    # ------------
    model = UnetModule(
        in_chans=args.in_chans,
        out_chans=args.out_chans,
        chans=args.chans,
        num_pool_layers=args.num_pool_layers,
        drop_prob=args.drop_prob,
        lr=args.lr,
        lr_step_size=args.lr_step_size,
        lr_gamma=args.lr_gamma,
        weight_decay=args.weight_decay,
    )

    # ------------
    # trainer
    # ------------
    trainer = pl.Trainer.from_argparse_args(args)

    # ------------
    # run
    # ------------
    if args.mode == "train":
        trainer.fit(model, datamodule=data_module)
    elif args.mode == "test":
        trainer.test(model, datamodule=data_module)
    else:
        raise ValueError(f"unrecognized mode {args.mode}")
Ejemplo n.º 2
0
def test_unet_trainer(fastmri_mock_dataset, backend, tmp_path, monkeypatch):
    knee_path, _, metadata = fastmri_mock_dataset

    def retrieve_metadata_mock(a, fname):
        return metadata[str(fname)]

    monkeypatch.setattr(SliceDataset, "_retrieve_metadata",
                        retrieve_metadata_mock)

    params = build_unet_args(knee_path, tmp_path, backend)
    params.fast_dev_run = True
    params.backend = backend

    mask = create_mask_for_mask_type(params.mask_type, params.center_fractions,
                                     params.accelerations)
    train_transform = UnetDataTransform(params.challenge,
                                        mask_func=mask,
                                        use_seed=False)
    val_transform = UnetDataTransform(params.challenge, mask_func=mask)
    test_transform = UnetDataTransform(params.challenge)
    data_module = FastMriDataModule(
        data_path=params.data_path,
        challenge=params.challenge,
        train_transform=train_transform,
        val_transform=val_transform,
        test_transform=test_transform,
        test_split=params.test_split,
        sample_rate=params.sample_rate,
        batch_size=params.batch_size,
        num_workers=params.num_workers,
        distributed_sampler=(params.accelerator == "ddp"),
        use_dataset_cache_file=False,
    )

    model = UnetModule(
        in_chans=params.in_chans,
        out_chans=params.out_chans,
        chans=params.chans,
        num_pool_layers=params.num_pool_layers,
        drop_prob=params.drop_prob,
        lr=params.lr,
        lr_step_size=params.lr_step_size,
        lr_gamma=params.lr_gamma,
        weight_decay=params.weight_decay,
    )

    trainer = Trainer.from_argparse_args(params)

    trainer.fit(model, data_module)
Ejemplo n.º 3
0
def cli_main(args):
    pl.seed_everything(args.seed)

    # ------------
    # data
    # ------------
    # this creates a k-space mask for transforming input data
    mask = create_mask_for_mask_type(args.mask_type, args.center_fractions,
                                     args.accelerations)
    # use random masks for train transform, fixed masks for val transform
    train_transform = UnetDataTransform(args.challenge,
                                        mask_func=mask,
                                        use_seed=False)
    val_transform = UnetDataTransform(args.challenge, mask_func=mask)
    test_transform = UnetDataTransform(args.challenge)
    # ptl data module - this handles data loaders
    data_module = FastMriDataModule(
        data_path=args.data_path,
        challenge=args.challenge,
        train_transform=train_transform,
        val_transform=val_transform,
        test_transform=test_transform,
        test_split=args.test_split,
        test_path=args.test_path,
        sample_rate=args.sample_rate,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        distributed_sampler=(args.accelerator in ("ddp", "ddp_cpu")),
    )

    # ------------
    # model
    # ------------
    model = None
    if args.unet_module == "unet":
        model = UnetModule(
            in_chans=args.in_chans,
            out_chans=args.out_chans,
            chans=int(args.chans),
            num_pool_layers=args.num_pool_layers,
            drop_prob=args.drop_prob,
            lr=args.lr,
            lr_step_size=args.lr_step_size,
            lr_gamma=args.lr_gamma,
            weight_decay=args.weight_decay,
            optimizer=args.optmizer,
        )
    elif args.unet_module == "nestedunet":
        model = NestedUnetModule(
            in_chans=args.in_chans,
            out_chans=args.out_chans,
            chans=args.chans,
            num_pool_layers=args.num_pool_layers,
            drop_prob=args.drop_prob,
            lr=args.lr,
            lr_step_size=args.lr_step_size,
            lr_gamma=args.lr_gamma,
            weight_decay=args.weight_decay,
            optimizer=args.optmizer,
        )

    if args.device == "cuda" and not torch.cuda.is_available():
        raise ValueError(
            "The requested cuda device isn't available please set --device cpu"
        )

    pretrained_dict = torch.load(args.state_dict_file,
                                 map_location=args.device)
    model_dict = model.unet.state_dict()
    if args.unet_module == "unet":
        model_dict = {
            k: pretrained_dict["classy_state_dict"]["base_model"]["model"]
            ["trunk"]["_feature_blocks.unetblock." + k]
            for k, _ in model_dict.items()
        }
    elif args.unet_module == "nestedunet":
        model_dict = {
            k: pretrained_dict["classy_state_dict"]["base_model"]["model"]
            ["trunk"]["_feature_blocks.nublock." + k]
            for k, v in model_dict.items()
        }

    model.unet.load_state_dict(model_dict)

    # ------------
    # trainer
    # ------------
    trainer = pl.Trainer.from_argparse_args(args)

    # ------------
    # run
    # ------------
    output_filename = f"fine_tuned_{args.unet_module}.torch"
    output_model_filepath = f"{args.output_path}/{output_filename}"
    if args.mode == "train":
        trainer.fit(model, datamodule=data_module)
        print(f"Saving model: {output_model_filepath}")
        torch.save(model.state_dict(), output_model_filepath)
        print("DONE!")
    elif args.mode == "test":
        trainer.test(model, datamodule=data_module)
    else:
        raise ValueError(f"unrecognized mode {args.mode}")