make other meta-learning algorithms implemented in l2l.
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.

learnToLearn.py 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import os
  2. import torch
  3. import pickle
  4. from MeLU import MeLU
  5. from options import config
  6. from model_training import training
  7. from data_generation import generate
  8. from evidence_candidate import selection
  9. from model_test import test
  10. from embedding_module import EmbeddingModule
  11. import learn2learn as l2l
  12. from embeddings import item, user
  13. import random
  14. import numpy as np
  15. from learnToLearnTest import test
  16. from fast_adapt import fast_adapt
  17. import gc
  18. # DATA GENERATION
  19. print("DATA GENERATION PHASE")
  20. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  21. os.environ["CUDA_VISIBLE_DEVICES"] = "0"
  22. master_path= "/media/external_10TB/10TB/maheri/melu_data5"
  23. if not os.path.exists("{}/".format(master_path)):
  24. os.mkdir("{}/".format(master_path))
  25. # preparing dataset. It needs about 22GB of your hard disk space.
  26. generate(master_path)
  27. # TRAINING
  28. print("TRAINING PHASE")
  29. embedding_dim = config['embedding_dim']
  30. fc1_in_dim = config['embedding_dim'] * 8
  31. fc2_in_dim = config['first_fc_hidden_dim']
  32. fc2_out_dim = config['second_fc_hidden_dim']
  33. use_cuda = config['use_cuda']
  34. emb = EmbeddingModule(config).cuda()
  35. fc1 = torch.nn.Linear(fc1_in_dim, fc2_in_dim)
  36. fc2 = torch.nn.Linear(fc2_in_dim, fc2_out_dim)
  37. linear_out = torch.nn.Linear(fc2_out_dim, 1)
  38. head = torch.nn.Sequential(fc1,fc2,linear_out)
  39. # META LEARNING
  40. print("META LEARNING PHASE")
  41. # head = l2l.algorithms.MetaSGD(head, lr=config['local_lr'],first_order=True)
  42. transform = l2l.optim.ModuleTransform(torch.nn.Linear)
  43. head = l2l.algorithms.GBML(head , transform=transform , lr=config['local_lr'] , adapt_transform=True,first_order=True)
  44. # head.to(torch.device('cuda:0'))
  45. head.cuda()
  46. # Setup optimization
  47. print("SETUP OPTIMIZATION PHASE")
  48. all_parameters = list(emb.parameters()) + list(head.parameters())
  49. optimizer = torch.optim.Adam(all_parameters, lr=config['lr'])
  50. # loss = torch.nn.MSELoss(reduction='mean')
  51. # Load training dataset.
  52. print("LOAD DATASET PHASE")
  53. training_set_size = int(len(os.listdir("{}/warm_state".format(master_path))) / 4)
  54. supp_xs_s = []
  55. supp_ys_s = []
  56. query_xs_s = []
  57. query_ys_s = []
  58. for idx in range(training_set_size):
  59. supp_xs_s.append(pickle.load(open("{}/warm_state/supp_x_{}.pkl".format(master_path, idx), "rb")))
  60. supp_ys_s.append(pickle.load(open("{}/warm_state/supp_y_{}.pkl".format(master_path, idx), "rb")))
  61. query_xs_s.append(pickle.load(open("{}/warm_state/query_x_{}.pkl".format(master_path, idx), "rb")))
  62. query_ys_s.append(pickle.load(open("{}/warm_state/query_y_{}.pkl".format(master_path, idx), "rb")))
  63. total_dataset = list(zip(supp_xs_s, supp_ys_s, query_xs_s, query_ys_s))
  64. del(supp_xs_s, supp_ys_s, query_xs_s, query_ys_s)
  65. training_set_size = len(total_dataset)
  66. batch_size = config['batch_size']
  67. torch.cuda.empty_cache()
  68. random.shuffle(total_dataset)
  69. num_batch = int(training_set_size / batch_size)
  70. a, b, c, d = zip(*total_dataset)
  71. print("\n\n\n")
  72. for iteration in range(config['num_epoch']):
  73. for i in range(num_batch):
  74. optimizer.zero_grad()
  75. meta_train_error = 0.0
  76. meta_train_accuracy = 0.0
  77. meta_valid_error = 0.0
  78. meta_valid_accuracy = 0.0
  79. meta_test_error = 0.0
  80. meta_test_accuracy = 0.0
  81. print("EPOCH: ", iteration, " BATCH: ", i)
  82. supp_xs = list(a[batch_size * i:batch_size * (i + 1)])
  83. supp_ys = list(b[batch_size * i:batch_size * (i + 1)])
  84. query_xs = list(c[batch_size * i:batch_size * (i + 1)])
  85. query_ys = list(d[batch_size * i:batch_size * (i + 1)])
  86. batch_sz = len(supp_xs)
  87. for j in range(batch_size):
  88. supp_xs[j] = supp_xs[j].cuda()
  89. supp_ys[j] = supp_ys[j].cuda()
  90. query_xs[j] = query_xs[j].cuda()
  91. query_ys[j] = query_ys[j].cuda()
  92. for task in range(batch_sz):
  93. # print("EPOCH: ", iteration," BATCH: ",i, "TASK: ",task)
  94. # Compute meta-training loss
  95. learner = head.clone()
  96. temp_sxs = emb(supp_xs[task])
  97. temp_qxs = emb(query_xs[task])
  98. evaluation_error = fast_adapt(learner,
  99. temp_sxs,
  100. temp_qxs,
  101. supp_ys[task],
  102. query_ys[task],
  103. config['inner']
  104. )
  105. evaluation_error.backward()
  106. meta_train_error += evaluation_error.item()
  107. # Print some metrics
  108. print('Iteration', iteration)
  109. print('Meta Train Error', meta_train_error / batch_sz)
  110. # print('Meta Train Accuracy', meta_train_accuracy / batch_sz)
  111. # print('Meta Valid Error', meta_valid_error / batch_sz)
  112. # print('Meta Valid Accuracy', meta_valid_accuracy / batch_sz)
  113. # print('Meta Test Error', meta_test_error / batch_sz)
  114. # print('Meta Test Accuracy', meta_test_accuracy / batch_sz)
  115. # Average the accumulated gradients and optimize
  116. for p in all_parameters:
  117. p.grad.data.mul_(1.0 / batch_sz)
  118. optimizer.step()
  119. torch.cuda.empty_cache()
  120. del(supp_xs,supp_ys,query_xs,query_ys)
  121. gc.collect()
  122. print("===============================================\n")
  123. # save model
  124. final_model = torch.nn.Sequential(emb,head)
  125. torch.save(final_model.state_dict(), master_path + "/models_sgd.pkl")
  126. # testing
  127. print("start of test phase")
  128. for test_state in ['warm_state', 'user_cold_state', 'item_cold_state', 'user_and_item_cold_state']:
  129. test_dataset = None
  130. test_set_size = int(len(os.listdir("{}/{}".format(master_path, test_state))) / 4)
  131. supp_xs_s = []
  132. supp_ys_s = []
  133. query_xs_s = []
  134. query_ys_s = []
  135. for idx in range(test_set_size):
  136. supp_xs_s.append(pickle.load(open("{}/{}/supp_x_{}.pkl".format(master_path, test_state, idx), "rb")))
  137. supp_ys_s.append(pickle.load(open("{}/{}/supp_y_{}.pkl".format(master_path, test_state, idx), "rb")))
  138. query_xs_s.append(pickle.load(open("{}/{}/query_x_{}.pkl".format(master_path, test_state, idx), "rb")))
  139. query_ys_s.append(pickle.load(open("{}/{}/query_y_{}.pkl".format(master_path, test_state, idx), "rb")))
  140. test_dataset = list(zip(supp_xs_s, supp_ys_s, query_xs_s, query_ys_s))
  141. del (supp_xs_s, supp_ys_s, query_xs_s, query_ys_s)
  142. print("===================== " + test_state + " =====================")
  143. test(emb,head, test_dataset, batch_size=config['batch_size'], num_epoch=config['num_epoch'])
  144. print("===================================================\n\n\n")