Ejemplo n.º 1
0
    def setup_test():
        # reset the seed
        set_seed(0)
        # create dataset
        _train_set = MNIST(str(dataset_path),
                           train=True,
                           download=True,
                           transform=ToTensor())
        _val_set = MNIST(str(dataset_path),
                         train=False,
                         download=True,
                         transform=ToTensor())
        # make datasets smaller if requested in config
        if cfg.dataset_train.max_datapoints > -1:
            _train_set.data = _train_set.data[:cfg.dataset_train.
                                              max_datapoints]
        if cfg.dataset_val.max_datapoints > -1:
            _val_set.data = _val_set.data[:cfg.dataset_val.max_datapoints]
        # create dataloader
        _train_loader = create_loader(_train_set,
                                      cfg.dataset_train,
                                      batch_size=cfg.train.batch_size)
        _val_loader = create_loader(_val_set,
                                    cfg.dataset_val,
                                    batch_size=cfg.val.batch_size)

        # create model and trainer
        _model_mgr = MLPModelManager(cfg)
        _trainer = MLPMNISTTrainer(cfg,
                                   _model_mgr,
                                   exp_group,
                                   exp_name,
                                   run_name,
                                   len(_train_loader),
                                   reset=True)
        return _trainer, _model_mgr, _train_loader, _val_loader
Ejemplo n.º 2
0
def test_set_seed() -> None:
    """
    Set seed and create some random ints in torch, numpy, python. Check if
    the random functions are deterministic.
    """
    set_seed(420)
    rand_int1 = th.randint(42, (1, )).squeeze()
    assert rand_int1 == 29, rand_int1

    set_seed(69)
    rand_int2 = np.random.randint(1337, size=(1, ))
    assert rand_int2.squeeze() == 1078, rand_int2
    del rand_int2

    set_seed(300)
    rand_int3 = random.randint(0, 1001)
    assert rand_int3 == 612, rand_int3
    del rand_int3
Ejemplo n.º 3
0
def test_save_load():
    # load repository and experiment config
    exp_group, exp_name, run_name = "default", "mnist", "run1"
    config_file = setup_config_file_from_experiment_identifier(MNISTExperimentType, exp_group, exp_name,
                                                               config_dir=TrainerPathConst.DIR_CONFIG)
    config = load_yaml_config_file(config_file)
    dataset_path = "data"
    cfg = MLPMNISTExperimentConfig(config)
    cfg.dataset_train.num_workers = 0
    cfg.dataset_val.num_workers = 0
    set_seed(0, set_deterministic=True)

    # create dataset and dataloader
    train_set = MNIST(str(dataset_path), train=True, download=True, transform=ToTensor())
    val_set = MNIST(str(dataset_path), train=False, download=True, transform=ToTensor())
    train_loader = create_loader(train_set, cfg.dataset_train, batch_size=cfg.train.batch_size)
    val_loader = create_loader(val_set, cfg.dataset_val, batch_size=cfg.val.batch_size)

    # create model
    model_mgr = MLPModelManager(cfg)

    # create trainer
    trainer = MLPMNISTTrainer(cfg, model_mgr, exp_group, exp_name, run_name, len(train_loader), reset=True)

    # run training for some epochs
    cfg.train.num_epochs = 2
    trainer.train_model(train_loader, val_loader)

    # reload without cuda and train an epoch on the CPU
    del trainer
    del model_mgr
    cfg.train.num_epochs = 3
    cfg.use_multi_gpu = False
    cfg.use_cuda = False

    model_mgr = MLPModelManager(cfg)
    trainer = MLPMNISTTrainer(cfg, model_mgr, exp_group, exp_name, run_name, len(train_loader))
    trainer.train_model(train_loader, val_loader)

    # one more epoch with cuda only (no multi_gpu)
    del trainer
    del model_mgr
    cfg.train.num_epochs = 4
    cfg.use_multi_gpu = False
    cfg.use_cuda = True

    model_mgr = MLPModelManager(cfg)
    trainer = MLPMNISTTrainer(cfg, model_mgr, exp_group, exp_name, run_name, len(train_loader))
    trainer.train_model(train_loader, val_loader)
    old_metrics = deepcopy(trainer.metrics.storage_epoch)
    print(old_metrics)

    # test inference from loaded model
    del trainer
    del model_mgr
    cfg.train.num_epochs = 4
    cfg.use_multi_gpu = False
    cfg.use_cuda = True

    model_mgr = MLPModelManager(cfg)
    trainer = MLPMNISTTrainer(cfg, model_mgr, exp_group, exp_name, run_name, len(train_loader), inference_only=True)
    loss, acc, _, _ = trainer.validate_epoch(val_loader)
    print(loss, acc)
Ejemplo n.º 4
0
def main():
    # setup arguments
    parser = utils.ArgParser(description=__doc__)
    arguments.add_default_args(parser)
    arguments.add_trainer_args(parser)
    arguments.add_exp_identifier_args(parser)
    arguments.add_dataset_test_arg(parser)
    args = parser.parse_args()

    # load experiment config
    exp_group, exp_name, config_file = arguments.setup_experiment_identifier_from_args(
        args, EXP_TYPE)
    config = load_yaml_config_file(config_file)

    # update experiment config and dataset path given the script arguments
    config = arguments.update_config_from_args(config, args)
    dataset_path = arguments.update_path_from_args(args)

    # create configuration object
    cfg = MLPMNISTExperimentConfig(config)
    if args.print_config:
        print(cfg)

    # set seed
    if cfg.random_seed is not None:
        print(f"Set seed to {cfg.random_seed}")
        set_seed(
            cfg.random_seed,
            set_deterministic=False)  # set deterministic via config if needed

    # create datasets
    train_set = MNIST(str(dataset_path),
                      train=True,
                      download=True,
                      transform=ToTensor())
    val_set = MNIST(str(dataset_path),
                    train=False,
                    download=True,
                    transform=ToTensor())

    # make datasets smaller if requested in config
    if cfg.dataset_train.max_datapoints > -1:
        train_set.data = train_set.data[:cfg.dataset_train.max_datapoints]
    if cfg.dataset_val.max_datapoints > -1:
        val_set.data = val_set.data[:cfg.dataset_val.max_datapoints]

    # create dataloaders
    train_loader = create_loader(train_set,
                                 cfg.dataset_train,
                                 batch_size=cfg.train.batch_size)
    val_loader = create_loader(val_set,
                               cfg.dataset_val,
                               batch_size=cfg.val.batch_size)

    # create model
    model_mgr = MLPModelManager(cfg)

    if args.test_dataset:
        # run dataset test and exit
        run_mlpmnist_dataset_test(train_set, train_loader)
        return

    # always load best epoch during validation
    load_best = args.load_best or args.validate

    # create trainer
    trainer = MLPMNISTTrainer(cfg,
                              model_mgr,
                              exp_group,
                              exp_name,
                              args.run_name,
                              len(train_loader),
                              log_dir=args.log_dir,
                              log_level=args.log_level,
                              logger=None,
                              print_graph=args.print_graph,
                              reset=args.reset,
                              load_best=load_best,
                              load_epoch=args.load_epoch,
                              inference_only=args.validate)

    if args.validate:
        # run validation
        trainer.validate_epoch(val_loader)
    else:
        # run training
        trainer.train_model(train_loader, val_loader)
Ejemplo n.º 5
0
def main():
    # ---------- Setup script arguments. ----------
    parser = utils.ArgParser(description=__doc__)
    arguments.add_default_args(parser)  # logging level etc.
    arguments.add_exp_identifier_args(
        parser)  # arguments to identify the experiment to run
    arguments.add_trainer_args(parser,
                               dataset_path=False)  # general trainer arguments
    parser.add_argument("--preload",
                        action="store_true",
                        help="Preload everything.")  # feature preloading
    arguments_mart.add_mart_args(parser)  # some more paths for mart
    parser.add_argument("--load_model",
                        type=str,
                        default=None,
                        help="Load model from file.")
    parser.add_argument("--print_model",
                        action="store_true",
                        help=f"Print model")
    args = parser.parse_args()

    # load repository config yaml file to dict
    exp_group, exp_name, config_file = arguments.setup_experiment_identifier_from_args(
        args, EXP_TYPE)
    config = load_yaml_config_file(config_file)

    # update experiment config given the script arguments
    config = arguments.update_config_from_args(config, args)
    config = arguments_mart.update_mart_config_from_args(config, args)

    # read experiment config dict
    cfg = Config(config)
    if args.print_config:
        print(cfg)

    # set seed
    if cfg.random_seed is not None:
        print(f"Set seed to {cfg.random_seed}")
        set_seed(
            cfg.random_seed,
            set_deterministic=False)  # set deterministic via config if needed

    # create dataset
    train_set, val_set, train_loader, val_loader = create_mart_datasets_and_loaders(
        cfg, args.coot_feat_dir, args.annotations_dir, args.video_feature_dir)

    for i, run_number in enumerate(
            range(args.start_run, args.start_run + args.num_runs)):
        run_name = f"{args.run_name}{run_number}"

        # create model from config
        model = create_mart_model(cfg,
                                  len(train_set.word2idx),
                                  cache_dir=args.cache_dir)

        # print model for debug if requested
        if args.print_model and i == 0:
            print(model)

        # always load best epoch during validation
        load_best = args.load_best or args.validate

        # create trainer
        trainer = MartTrainer(cfg,
                              model,
                              exp_group,
                              exp_name,
                              run_name,
                              len(train_loader),
                              log_dir=args.log_dir,
                              log_level=args.log_level,
                              logger=None,
                              print_graph=args.print_graph,
                              reset=args.reset,
                              load_best=load_best,
                              load_epoch=args.load_epoch,
                              load_model=args.load_model,
                              inference_only=args.validate,
                              annotations_dir=args.annotations_dir)

        if args.validate:
            # run validation
            if not trainer.load and not args.ignore_untrained:
                raise ValueError(
                    "Validating an untrained model! No checkpoints were loaded. Add --ignore_untrained "
                    "to ignore this error.")
            trainer.validate_epoch(val_loader)
        else:
            # run training
            trainer.train_model(train_loader, val_loader)

        # done with this round
        trainer.close()
        del model
        del trainer
Ejemplo n.º 6
0
def main():
    # ---------- Setup script arguments. ----------
    parser = utils.ArgParser(description=__doc__)
    arguments.add_default_args(parser)  # logging level etc.
    arguments.add_exp_identifier_args(
        parser)  # arguments to identify the experiment to run
    arguments.add_trainer_args(parser)  # general trainer arguments
    arguments.add_dataset_test_arg(parser)  # flag for dataset testing
    arguments_coot.add_dataloader_args(parser)  # feature preloading
    parser.add_argument("--load_model",
                        type=str,
                        default=None,
                        help="Load model from file.")
    parser.add_argument("--save_embeddings",
                        action="store_true",
                        help="Save generated COOT embeddings.")
    args = parser.parse_args()

    if args.save_embeddings:
        assert args.validate, "Saving embeddings only works in validation with --validate"

    # load repository config yaml file to dict
    exp_group, exp_name, config_file = arguments.setup_experiment_identifier_from_args(
        args, EXP_TYPE)
    config = load_yaml_config_file(config_file)

    # update experiment config and dataset path given the script arguments
    path_data = arguments.update_path_from_args(args)
    config = arguments.update_config_from_args(config, args)
    config = arguments_coot.update_coot_config_from_args(config, args)

    # read experiment config dict
    cfg = Config(config, is_train=not args.validate and not args.test_dataset)
    if args.print_config:
        print(cfg)

    # set seed
    if cfg.random_seed is not None:
        print(f"Set seed to {cfg.random_seed}")
        set_seed(
            cfg.random_seed,
            set_deterministic=False)  # set deterministic via config if needed

    # create dataset and dataloader
    if (cfg.dataset_train.preload_vid_feat
            or cfg.dataset_train.preload_text_feat
            or cfg.dataset_val.preload_vid_feat
            or cfg.dataset_val.preload_text_feat):
        cmd = "ulimit -n 100000"
        print(f"Run system command to avoid TooManyFiles error:\n{cmd}")
        os.system(cmd)
    ################## CREATE DATASETS FROM PATH DATA ################
    train_set, val_set, train_loader, val_loader = create_retrieval_datasets_and_loaders(
        cfg, path_data)

    if args.test_dataset:
        # run dataset test and exit
        run_retrieval_dataset_test(train_set, train_loader)
        return
    print("---------- Setup done!")

    for run_number in range(1, args.num_runs + 1):
        run_name = f"{args.run_name}{run_number}"

        # create coot models
        model_mgr = ModelManager(cfg)

        # always load best epoch during validation
        load_best = args.load_best or args.validate

        # create trainer
        trainer = Trainer(cfg,
                          model_mgr,
                          exp_group,
                          exp_name,
                          run_name,
                          len(train_loader),
                          log_dir=args.log_dir,
                          log_level=args.log_level,
                          logger=None,
                          print_graph=args.print_graph,
                          reset=args.reset,
                          load_best=load_best,
                          load_epoch=args.load_epoch,
                          load_model=args.load_model,
                          inference_only=args.validate)

        if args.validate:
            # run validation
            trainer.validate_epoch(val_loader,
                                   val_clips=cfg.val.val_clips,
                                   save_embs=args.save_embeddings)
        else:
            # run training
            train_loss = trainer.train_model(train_loader, val_loader)

        # save train loss
        ipdb.set_trace()
        # done with this round
        trainer.close()
        del model_mgr
        del trainer
Ejemplo n.º 7
0
def main():
    # setup arguments
    parser = utils.ArgParser(description=__doc__)
    arguments.add_default_args(parser)
    arguments.add_exp_identifier_args(parser)
    arguments.add_trainer_args(parser)
    arguments.add_dataset_test_arg(parser)
    args = parser.parse_args()

    # load repository config yaml file to dict
    exp_group, exp_name, config_file = arguments.setup_experiment_identifier_from_args(
        args, EXP_TYPE)
    config = load_yaml_config_file(config_file)

    # update experiment config and dataset path given the script arguments
    config = arguments.update_config_from_args(config, args)
    dataset_path = arguments.update_path_from_args(args)

    # read experiment config dict
    cfg = MLPMNISTExperimentConfig(config)
    if args.print_config:
        print(cfg)

    # set seed
    verb = "Set seed"
    if cfg.random_seed is None:
        cfg.random_seed = np.random.randint(0, 2**15, dtype=np.int32)
        verb = "Randomly generated seed"
    print(f"{verb} {cfg.random_seed} deterministic {cfg.cudnn_deterministic} "
          f"benchmark {cfg.cudnn_benchmark}")
    set_seed(cfg.random_seed,
             cudnn_deterministic=cfg.cudnn_deterministic,
             cudnn_benchmark=cfg.cudnn_benchmark)

    # create datasets
    train_set = MNIST(str(dataset_path),
                      train=True,
                      download=True,
                      transform=ToTensor())
    val_set = MNIST(str(dataset_path),
                    train=False,
                    download=True,
                    transform=ToTensor())

    # make datasets smaller if requested in config
    if cfg.dataset_train.max_datapoints > -1:
        train_set.data = train_set.data[:cfg.dataset_train.max_datapoints]
    if cfg.dataset_val.max_datapoints > -1:
        val_set.data = val_set.data[:cfg.dataset_val.max_datapoints]

    # create dataloaders
    train_loader = create_loader(train_set,
                                 cfg.dataset_train,
                                 batch_size=cfg.train.batch_size)
    val_loader = create_loader(val_set,
                               cfg.dataset_val,
                               batch_size=cfg.val.batch_size)

    if args.test_dataset:
        # run dataset test and exit
        run_mlpmnist_dataset_test(train_set, train_loader)
        return
    print("---------- Setup done!")

    for run_number in range(1, args.num_runs + 1):
        run_name = f"{args.run_name}{run_number}"

        # create model
        model_mgr = MLPModelManager(cfg)

        # always load best epoch during validation
        load_best = args.load_best or args.validate

        # create trainer
        trainer = MLPMNISTTrainer(cfg,
                                  model_mgr,
                                  exp_group,
                                  exp_name,
                                  run_name,
                                  len(train_loader),
                                  log_dir=args.log_dir,
                                  log_level=args.log_level,
                                  logger=None,
                                  print_graph=args.print_graph,
                                  reset=args.reset,
                                  load_best=load_best,
                                  load_epoch=args.load_epoch,
                                  inference_only=args.validate)

        if args.validate:
            # run validation
            trainer.validate_epoch(val_loader)
        else:
            # run training
            trainer.train_model(train_loader, val_loader)

        # done with this round
        trainer.close()
        del model_mgr
        del trainer