示例#1
0
#
# mask = torch.tensor([0, 1, 0, 1, 1, 0], device='cuda')
# source = torch.tensor([1.0, 2.0, 3.0], device='cuda')
# mask = torch.tensor([0, 1, 0, 1, 1, 0], device='cuda', dtype=torch.uint8)
# y = myfunc(mask, source)

# example 2
class Model(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.layer = torch.nn.Linear(2, 1)

    def forward(self, x):
        return self.layer(x)

x = torch.tensor([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]])
y = torch.tensor([3.0, 5.0, 4.0, 6.0])

model = Model()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

with torchsnooper.snoop():
    for _ in range(100):
        optimizer.zero_grad()
        # pred = model(x)
        pred = model(x).squeeze()
        squared_diff = (y - pred) ** 2
        loss = squared_diff.mean()
        print(loss.item())
        loss.backward()
        optimizer.step()
示例#2
0
    '''
    '''
    #no-targeted L2 attack    
    adversary = L2MomentumIterativeAttack(
        learner.model, loss_fn=attack_cosine_distance(target=torch.ones(1).to(conf.device)), eps=10,
        nb_iter=40, eps_iter=0.2, decay_factor=1., clip_min=-1.0, clip_max=1.0,
        targeted=False)
    '''

    #image = Image.open("/hd1/anshengnan/InsightFace_Pytorch/data/test.jpg")
    loader, class_num = get_train_loader(conf)

    head = Arcface(embedding_size=conf.embedding_size,
                   classnum=class_num).to(conf.device)

    with ts.snoop():
        for imgs, labels in tqdm(iter(loader)):
            imgs = imgs.to(conf.device)
            labels = labels.to(conf.device)
            embeddings = learner.model(imgs)
            thetas = head(embeddings, labels)
            adv_targeted = adversary.perturb(imgs, labels)
            adv_embeddings = learner.model(adv_targeted)
            adv_thetas = head(adv_embeddings, labels)
            print(labels)
            thetas = list(thetas.squeeze(0))
            adv_thetas = list(adv_thetas.squeeze(0))
            print(thetas.index(max(thetas)))
            print(adv_thetas.index(max(adv_thetas)))
            break