Esempio n. 1
0
    def _load_model(self, model_path):
        # define model
        model_name = os.path.basename(model_path)
        h_input, w_input, model_type, _ = parse_model_name(model_name)
        self.kernel_size = get_kernel(
            h_input,
            w_input,
        )
        self.model = MODEL_MAPPING[model_type](
            conv6_kernel=self.kernel_size).to(self.device)

        # load model weight
        state_dict = torch.load(model_path, map_location=self.device)
        keys = iter(state_dict)
        first_layer_name = keys.__next__()
        if first_layer_name.find('module.') >= 0:
            from collections import OrderedDict
            new_state_dict = OrderedDict()
            for key, value in state_dict.items():
                name_key = key[7:]
                new_state_dict[name_key] = value
            self.model.load_state_dict(new_state_dict)
        else:
            self.model.load_state_dict(state_dict)
        return None
def update_config(args, conf):
    conf.devices = args.devices
    conf.val_size = args.val_size
    conf.patch_info = args.patch_info
    conf.checkpoint = args.checkpoint
    conf.epochs = args.epochs
    conf.batch_size = args.batch_size
    conf.model_type = args.model_type
    w_input, h_input = get_width_height(args.patch_info)
    conf.input_size = [h_input, w_input]
    conf.kernel_size = get_kernel(h_input, w_input)
    conf.device = "cuda:{}".format(
        conf.devices[0]) if torch.cuda.is_available() else "cpu"

    # resize fourier image size
    conf.ft_height = 2 * conf.kernel_size[0]
    conf.ft_width = 2 * conf.kernel_size[1]
    current_time = datetime.now().strftime('%b%d_%H-%M-%S')
    job_name = 'Anti_Spoofing_{}'.format(args.patch_info)
    log_path = '{}/{}/{} '.format(conf.log_path, job_name, current_time)
    snapshot_dir = '{}/{}'.format(conf.snapshot_dir_path, job_name)

    make_if_not_exist(snapshot_dir)
    make_if_not_exist(log_path)

    conf.model_path = snapshot_dir
    conf.log_path = log_path
    conf.job_name = job_name
    return conf
Esempio n. 3
0
def update_config(args, conf):
    conf.devices = args.devices
    conf.patch_info = args.patch_info
    w_input, h_input = get_width_height(args.patch_info)

    conf.kernel_size = get_kernel(h_input, w_input)
    conf.device = "cuda:{}".format(
        conf.devices[0]) if torch.cuda.is_available() else "cpu"

    # resize fourier image size
    # conf.ft_height = 2*conf.kernel_size[0]
    # conf.ft_width = 2*conf.kernel_size[1]

    # eval_snapshot_dir = '{}/{}'.format(conf.eval_snapshot_dir_path, eval_job_name)
    make_if_not_exist(conf.model_path)
    make_if_not_exist(conf.log_path)

    return conf
 def __init__(self, **kwargs):
     super(OnnxModel, self).__init__()
     kernel_size = get_kernel(80, 60)
     # self.model = MiniFASNetV2(conv6_kernel = kernel_size)
     self.model = RepVggFTNet(32, [48, 64, 128], [4, 10, 8],
                              num_out=2,
                              num_classes=3)
     try:
         # self.model.load("work_dirs/RepVGGNet/epoch_77.pth")
         clean_state_dict = OrderedDict()
         state_dict = torch.load("work_dirs/RepVGGNet/epoch_77.pth")
         for name, value in state_dict.items():
             if name.startswith("module."):
                 clean_state_dict[name.lstrip("module.")] = value
         self.model.load_state_dict(clean_state_dict)
         load(self.model)
     except:
         print(
             "There is no model loaded!! Initial parameters will be saved")
Esempio n. 5
0
def update_config(args, conf):
    conf.devices = args.devices
    conf.patch_info = args.patch_info
    w_input, h_input = get_width_height(args.patch_info)
    conf.input_size = [h_input, w_input]
    conf.kernel_size = get_kernel(w_input, h_input)
    conf.device = "cuda:{}".format(
        conf.devices[0]) if torch.cuda.is_available() else "cpu"

    current_time = datetime.now().strftime('%b%d_%H-%M-%S')
    job_name = 'Anti_Spoofing_{}'.format(args.patch_info)
    log_path = '{}/{}/{} '.format(conf.log_path, job_name, current_time)
    snapshot_dir = '{}/{}'.format(conf.snapshot_dir_path, job_name)

    make_if_not_exist(snapshot_dir)
    make_if_not_exist(log_path)

    conf.model_path = snapshot_dir
    conf.log_path = log_path
    conf.job_name = job_name
    return conf
 def _load_model(self, model_path):
     # define model
     model_name = os.path.basename(model_path)
     h_input, w_input, model_type, _ = 80, 80, None, 1
     self.kernel_size = get_kernel(h_input, w_input,)
     # self.model = MODEL_MAPPING["MiniFASNetV2"](conv6_kernel=self.kernel_size).to(self.device)
     self.model = RepVggFTNet(32, [48, 64, 128], [4, 10, 8], num_out=2, num_classes=3).to(self.device)
     # load model weight
     state_dict = torch.load(model_path, map_location=self.device)
     keys = iter(state_dict)
     first_layer_name = keys.__next__()
     if first_layer_name.find('module.') >= 0:
         from collections import OrderedDict
         new_state_dict = OrderedDict()
         for key, value in state_dict.items():
             # if str(key)[0:12]=="module.model":
                 name_key = key[7:]
                 new_state_dict[name_key] = value
         self.model.load_state_dict(new_state_dict)
     else:
         self.model.load_state_dict(state_dict)
     return None
    def __init__(self):
        super(AntiSpoofPredict, self).__init__()
        self.num_class = 2
        self.model_path = "/home/ubuntu/Silent-Face-Anti-Spoofing-master/saved_logs/snapshot/Anti_Spoofing_1_80-80/2021-01-11-13-19_Anti_Spoofing_1_80-80_model_iter-39500.pth"
        model_name = os.path.basename(self.model_path)
        h_input, w_input, model_type, _ = parse_model_name(model_name)
        self.kernel_size = get_kernel(
            h_input,
            w_input,
        )
        self.model = MODEL_MAPPING["MiniFASNetV2SE"](
            conv6_kernel=self.kernel_size, num_classes=self.num_class)
        checkpoint = torch.load(self.model_path, map_location="cuda:3")
        pretrain(self.model, checkpoint)

        self.new_width = self.new_height = 224
        self.transform = torchvision.transforms.Compose([
            torchvision.transforms.Resize((self.new_width, self.new_height)),
            torchvision.transforms.ToTensor(),
        ])
        device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")
        self.model.to(device)
        self.model.eval()
    def _load_model(self, model_path):
        # define model
        model_name = os.path.basename(model_path)
        h_input, w_input, model_type, _ = parse_model_name(model_name)
        self.kernel_size = get_kernel(
            h_input,
            w_input,
        )

        if model_type not in MODEL_MAPPING:
            params = {
                'embedding_size': 128,
                'conv6_kernel': (5, 5),
                'num_classes': 2,
                'img_channel': 3,
                'training': False
            }
            self.model = MultiFTNet(**params).to(self.device)
        else:
            self.model = MODEL_MAPPING[model_type](
                conv6_kernel=self.kernel_size).to(self.device)

        # load model weight
        state_dict = torch.load(model_path, map_location=self.device)
        keys = iter(state_dict)
        first_layer_name = keys.__next__()
        if first_layer_name.find('module.') >= 0:
            from collections import OrderedDict
            new_state_dict = OrderedDict()
            for key, value in state_dict.items():
                name_key = key[7:]
                new_state_dict[name_key] = value
            self.model.load_state_dict(new_state_dict)
        else:
            self.model.load_state_dict(state_dict)
        return None
Esempio n. 9
0
from lr_finder import LRFinder
from src.model_lib.MultiFTNet import MultiFTNet
from src.model_lib.MiniFASNet import MiniFASNetV1, MiniFASNetV2,MiniFASNetV1SE,MiniFASNetV2SE
from src.utility import get_kernel
from torch.nn import CrossEntropyLoss, MSELoss
from torch import optim
from src.data_io.dataset_loader import get_train_loader,get_eval_loader
from src.default_config import get_default_config, update_config
from train import parse_args
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
kernel_size = get_kernel(80, 60)
model = MultiFTNet(conv6_kernel = kernel_size)
cls_criterion = CrossEntropyLoss()
FT_criterion = MSELoss()
from torch import optim
# optimizer = optim.SGD(model.parameters(),
#                                    lr=0.1,
#                                    weight_decay=5e-4,
#                                    momentum=0.9)
optimizer = optim.AdamW(model.parameters())
lr_finder = LRFinder(model, optimizer, cls_criterion,FT_criterion)
conf = get_default_config()
args = parse_args()
conf = update_config(args, conf)
trainloader = get_train_loader(conf)
val_loader = get_eval_loader(conf)
lr_finder.range_test(trainloader, end_lr=1, num_iter=100, step_mode="linear")
lr_finder.plot(log_lr=False)
lr_finder.reset()