extend Melu code to perform different meta algorithms and hyperparameters
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

clustering.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import torch.nn.init as init
  2. import os
  3. import torch
  4. import pickle
  5. from options import config
  6. import gc
  7. import torch.nn as nn
  8. from torch.nn import functional as F
  9. class ClustringModule(torch.nn.Module):
  10. def __init__(self, config_param):
  11. super(ClustringModule, self).__init__()
  12. self.h1_dim = config_param['cluster_h1_dim']
  13. self.h2_dim = config_param['cluster_h2_dim']
  14. self.final_dim = config_param['cluster_final_dim']
  15. self.dropout_rate = config_param['cluster_dropout_rate']
  16. layers = [nn.Linear(config_param['embedding_dim'] * 8 + 1, self.h1_dim),
  17. torch.nn.Dropout(self.dropout_rate),
  18. nn.ReLU(inplace=True),
  19. # nn.BatchNorm1d(self.h1_dim),
  20. nn.Linear(self.h1_dim, self.h2_dim),
  21. torch.nn.Dropout(self.dropout_rate),
  22. nn.ReLU(inplace=True),
  23. # nn.BatchNorm1d(self.h2_dim),
  24. nn.Linear(self.h2_dim, self.final_dim)]
  25. self.input_to_hidden = nn.Sequential(*layers)
  26. self.clusters_k = config_param['cluster_k']
  27. self.embed_size = self.final_dim
  28. self.array = nn.Parameter(init.xavier_uniform_(torch.FloatTensor(self.clusters_k, self.embed_size)))
  29. self.temperature = config_param['temperature']
  30. def aggregate(self, z_i):
  31. return torch.mean(z_i, dim=0)
  32. def forward(self, task_embed, y, training=True):
  33. y = y.view(-1, 1)
  34. input_pairs = torch.cat((task_embed, y), dim=1)
  35. task_embed = self.input_to_hidden(input_pairs)
  36. # todo : may be useless
  37. mean_task = self.aggregate(task_embed)
  38. res = torch.norm(mean_task - self.array, p=2, dim=1, keepdim=True)
  39. res = torch.pow((res / self.temperature) + 1, (self.temperature + 1) / -2)
  40. # 1*k
  41. C = torch.transpose(res / res.sum(), 0, 1)
  42. # 1*k, k*d, 1*d
  43. value = torch.mm(C, self.array)
  44. # simple add operation
  45. # new_task_embed = value + mean_task
  46. # new_task_embed = value
  47. new_task_embed = mean_task
  48. # print("injam1:", new_task_embed)
  49. # print("injam2:", self.array)
  50. list_dist = []
  51. # list_dist = torch.norm(new_task_embed - self.array, p=2, dim=1,keepdim=True)
  52. list_dist = torch.sum(torch.pow(new_task_embed - self.array,2),dim=1)
  53. stack_dist = list_dist
  54. # print("injam3:", stack_dist)
  55. ## Second, find the minimum squared distance for softmax normalization
  56. min_dist = min(list_dist)
  57. # print("injam4:", min_dist)
  58. ## Third, compute exponentials shifted with min_dist to avoid underflow (0/0) issues in softmaxes
  59. alpha = config['kmeans_alpha'] # Placeholder tensor for alpha
  60. list_exp = []
  61. for i in range(self.clusters_k):
  62. exp = torch.exp(-alpha * (stack_dist[i] - min_dist))
  63. list_exp.append(exp)
  64. stack_exp = torch.stack(list_exp)
  65. sum_exponentials = torch.sum(stack_exp)
  66. # print("injam5:", stack_exp, sum_exponentials)
  67. ## Fourth, compute softmaxes and the embedding/representative distances weighted by softmax
  68. list_softmax = []
  69. list_weighted_dist = []
  70. for j in range(self.clusters_k):
  71. softmax = stack_exp[j] / sum_exponentials
  72. weighted_dist = stack_dist[j] * softmax
  73. list_softmax.append(softmax)
  74. list_weighted_dist.append(weighted_dist)
  75. stack_weighted_dist = torch.stack(list_weighted_dist)
  76. kmeans_loss = torch.sum(stack_weighted_dist, dim=0)
  77. return C, new_task_embed, kmeans_loss
  78. class Trainer(torch.nn.Module):
  79. def __init__(self, config_param, head=None):
  80. super(Trainer, self).__init__()
  81. fc1_in_dim = config_param['embedding_dim'] * 8
  82. fc2_in_dim = config_param['first_fc_hidden_dim']
  83. fc2_out_dim = config_param['second_fc_hidden_dim']
  84. self.fc1 = torch.nn.Linear(fc1_in_dim, fc2_in_dim)
  85. self.fc2 = torch.nn.Linear(fc2_in_dim, fc2_out_dim)
  86. self.linear_out = torch.nn.Linear(fc2_out_dim, 1)
  87. # cluster module
  88. self.cluster_module = ClustringModule(config_param)
  89. # self.task_dim = fc1_in_dim
  90. self.task_dim = config_param['cluster_final_dim']
  91. # transform task to weights
  92. self.film_layer_1_beta = nn.Linear(self.task_dim, fc2_in_dim, bias=False)
  93. self.film_layer_1_gamma = nn.Linear(self.task_dim, fc2_in_dim, bias=False)
  94. self.film_layer_2_beta = nn.Linear(self.task_dim, fc2_out_dim, bias=False)
  95. self.film_layer_2_gamma = nn.Linear(self.task_dim, fc2_out_dim, bias=False)
  96. # self.film_layer_3_beta = nn.Linear(self.task_dim, self.h3_dim, bias=False)
  97. # self.film_layer_3_gamma = nn.Linear(self.task_dim, self.h3_dim, bias=False)
  98. # self.dropout_rate = 0
  99. self.dropout_rate = config_param['trainer_dropout_rate']
  100. self.dropout = nn.Dropout(self.dropout_rate)
  101. def aggregate(self, z_i):
  102. return torch.mean(z_i, dim=0)
  103. def forward(self, task_embed, y, training, adaptation_data=None, adaptation_labels=None):
  104. if training:
  105. C, clustered_task_embed, k_loss = self.cluster_module(task_embed, y)
  106. # hidden layers
  107. # todo : adding activation function or remove it
  108. hidden_1 = self.fc1(task_embed)
  109. beta_1 = torch.tanh(self.film_layer_1_beta(clustered_task_embed))
  110. gamma_1 = torch.tanh(self.film_layer_1_gamma(clustered_task_embed))
  111. hidden_1 = torch.mul(hidden_1, gamma_1) + beta_1
  112. hidden_1 = self.dropout(hidden_1)
  113. hidden_2 = F.relu(hidden_1)
  114. hidden_2 = self.fc2(hidden_2)
  115. beta_2 = torch.tanh(self.film_layer_2_beta(clustered_task_embed))
  116. gamma_2 = torch.tanh(self.film_layer_2_gamma(clustered_task_embed))
  117. hidden_2 = torch.mul(hidden_2, gamma_2) + beta_2
  118. hidden_2 = self.dropout(hidden_2)
  119. hidden_3 = F.relu(hidden_2)
  120. y_pred = self.linear_out(hidden_3)
  121. else:
  122. C, clustered_task_embed, k_loss = self.cluster_module(adaptation_data, adaptation_labels)
  123. beta_1 = torch.tanh(self.film_layer_1_beta(clustered_task_embed))
  124. gamma_1 = torch.tanh(self.film_layer_1_gamma(clustered_task_embed))
  125. beta_2 = torch.tanh(self.film_layer_2_beta(clustered_task_embed))
  126. gamma_2 = torch.tanh(self.film_layer_2_gamma(clustered_task_embed))
  127. hidden_1 = self.fc1(task_embed)
  128. hidden_1 = torch.mul(hidden_1, gamma_1) + beta_1
  129. hidden_1 = self.dropout(hidden_1)
  130. hidden_2 = F.relu(hidden_1)
  131. hidden_2 = self.fc2(hidden_2)
  132. hidden_2 = torch.mul(hidden_2, gamma_2) + beta_2
  133. hidden_2 = self.dropout(hidden_2)
  134. hidden_3 = F.relu(hidden_2)
  135. y_pred = self.linear_out(hidden_3)
  136. return y_pred, C, k_loss