training_embedding.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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.key_path = key_path if key_path is not None else './key.pt'
  22. self.p = self.get_parameters(model)
  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, './key.pt')
  46. def load_matrix(self, path):
  47. self.X_random = torch.load(path).cuda()
  48. def get_parameters(self, model):
  49. conv_list = []
  50. # print(model.modules())
  51. for module in model.modules():
  52. if isinstance(module, nn.Conv2d) and module.out_channels > 100:
  53. conv_list.append(module)
  54. # 增加模型深度不够深且conv_list长度不够问题的处理
  55. if len(conv_list) == 0:
  56. for module in model.modules():
  57. if isinstance(module, nn.Conv2d):
  58. conv_list.append(module)
  59. # print(conv_list)
  60. if len(conv_list) > 11:
  61. target = conv_list[10:12]
  62. elif len(conv_list) >= 2:
  63. target = conv_list[0:2]
  64. else:
  65. target = conv_list
  66. # target = conv_list[0:2]
  67. print(f'Embedding target:{target}')
  68. # parameters = target.weight
  69. parameters = [x.weight for x in target]
  70. # [x.requires_grad_(True) for x in parameters]
  71. return parameters
  72. # add penalty value to loss
  73. def add_penalty(self, loss):
  74. # print(f'original loss:{loss} ')
  75. w = self.flatten_parameters(self.p)
  76. prob = self.get_prob(self.X_random, w)
  77. penalty = self.loss_fun(
  78. prob, self.code)
  79. loss += self.l * penalty
  80. # print(f'penalty loss:{loss} ')
  81. return loss
  82. def flatten_parameters(self, parameters):
  83. parameter = torch.cat([torch.mean(x, dim=3).reshape(-1)
  84. for x in parameters])
  85. return parameter
  86. def loss_fun(self, x, y):
  87. penalty = F.binary_cross_entropy(x, y)
  88. return penalty
  89. def decode(self, X, w):
  90. prob = self.get_prob(X, w)
  91. return torch.where(prob > 0.5, 1, 0)
  92. def get_prob(self, X, w):
  93. mm = torch.mm(self.X_random, w.reshape((w.shape[0], 1)))
  94. return F.sigmoid(mm).flatten()
  95. def test(self):
  96. w = self.flatten_parameters(self.p)
  97. decode = self.decode(self.X_random, w)
  98. print(decode.shape)
  99. code_string = ''.join([str(x) for x in decode.tolist()])
  100. code_string = bin2string(code_string)
  101. print('decoded code:', code_string)
  102. return code_string