training_embedding.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import torch.nn as nn
  2. import torch
  3. from torch.optim import SGD, Adam
  4. import torch.nn.functional as F
  5. def string2bin(s):
  6. binary_representation = ''.join(format(ord(x), '08b') for x in s)
  7. return [int(x) for x in binary_representation]
  8. def bin2string(binary_string):
  9. return ''.join(chr(int(binary_string[i:i + 8], 2)) for i in range(0, len(binary_string), 8))
  10. class Embedding():
  11. def __init__(self, model, code: torch.Tensor, key_path: str = None, l=1, train=True):
  12. """
  13. 初始化白盒水印编码器
  14. :param model: 模型定义
  15. :param code: 密钥,转换为Tensor格式
  16. :param key_path: 投影矩阵权重文件保存路径
  17. :param l: 水印编码器loss权重
  18. :param train: 是否是训练环境,默认为True
  19. """
  20. super(Embedding, self).__init__()
  21. self.p = self.get_parameters(model)
  22. self.key_path = key_path if key_path is not None else './key.pt'
  23. # self.p = parameters
  24. # self.w = nn.Parameter(w, requires_grad=True)
  25. # the flatten mean parameters
  26. # w = torch.mean(self.p, dim=1).reshape(-1)
  27. w = self.flatten_parameters(self.p)
  28. self.l = l
  29. self.w_init = w.clone().detach()
  30. print('Size of embedding parameters:', w.shape)
  31. self.opt = Adam(self.p, lr=0.001)
  32. self.distribution_ignore = ['train_acc']
  33. self.code = torch.tensor(string2bin(
  34. code), dtype=torch.float).cuda() # the embedding code
  35. self.code_len = self.code.shape[0]
  36. print(f'Code:{self.code} code length:{self.code_len}')
  37. # 判断是否为训练环境,如果是测试环境,直接加载投影矩阵,训练环境随机生成X矩阵,并保存至key_path中
  38. if not train:
  39. self.load_matrix(key_path)
  40. else:
  41. self.X_random = torch.randn(
  42. (self.code_len, self.w_init.shape[0])).cuda()
  43. self.save_matrix()
  44. def save_matrix(self):
  45. torch.save(self.X_random, self.key_path)
  46. def load_matrix(self, path):
  47. self.X_random = torch.load(path).cuda()
  48. def get_parameters(self, model):
  49. # conv_list = []
  50. # for module in model.modules():
  51. # if isinstance(module, nn.Conv2d) and module.out_channels > 100:
  52. # conv_list.append(module)
  53. #
  54. # target = conv_list[10:12]
  55. target = model.get_encode_layers()
  56. print(f'Embedding target:{target}')
  57. # parameters = target.weight
  58. parameters = [x.weight for x in target]
  59. # [x.requires_grad_(True) for x in parameters]
  60. return parameters
  61. # add penalty value to loss
  62. def add_penalty(self, loss):
  63. # print(f'original loss:{loss} ')
  64. w = self.flatten_parameters(self.p)
  65. prob = self.get_prob(self.X_random, w)
  66. penalty = self.loss_fun(
  67. prob, self.code)
  68. loss += self.l * penalty
  69. # print(f'penalty loss:{loss} ')
  70. return loss
  71. def flatten_parameters(self, parameters):
  72. parameter = torch.cat([torch.mean(x, dim=3).reshape(-1)
  73. for x in parameters])
  74. return parameter
  75. def loss_fun(self, x, y):
  76. penalty = F.binary_cross_entropy(x, y)
  77. return penalty
  78. def decode(self, X, w):
  79. prob = self.get_prob(X, w)
  80. return torch.where(prob > 0.5, 1, 0)
  81. def get_prob(self, X, w):
  82. mm = torch.mm(self.X_random, w.reshape((w.shape[0], 1)))
  83. return F.sigmoid(mm).flatten()
  84. def test(self):
  85. w = self.flatten_parameters(self.p)
  86. decode = self.decode(self.X_random, w)
  87. print(decode.shape)
  88. code_string = ''.join([str(x) for x in decode.tolist()])
  89. code_string = bin2string(code_string)
  90. print('decoded code:', code_string)
  91. return code_string