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.

learnToLearn.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import os
  2. import torch
  3. import pickle
  4. from options import config
  5. from data_generation import generate
  6. from embedding_module import EmbeddingModule
  7. import learn2learn as l2l
  8. import random
  9. from learnToLearnTest import test
  10. from fast_adapt import fast_adapt
  11. import gc
  12. from learn2learn.optim.transforms import KroneckerTransform
  13. import argparse
  14. def parse_args():
  15. print("==============")
  16. parser = argparse.ArgumentParser([], description='Fast Context Adaptation via Meta-Learning (CAVIA),'
  17. 'Clasification experiments.')
  18. print("==============\n")
  19. parser.add_argument('--seed', type=int, default=53)
  20. parser.add_argument('--task', type=str, default='multi', help='problem setting: sine or celeba')
  21. parser.add_argument('--tasks_per_metaupdate', type=int, default=32,
  22. help='number of tasks in each batch per meta-update')
  23. parser.add_argument('--lr_inner', type=float, default=5e-6, help='inner-loop learning rate (per task)')
  24. parser.add_argument('--lr_meta', type=float, default=5e-5,
  25. help='outer-loop learning rate (used with Adam optimiser)')
  26. # parser.add_argument('--lr_meta_decay', type=float, default=0.9, help='decay factor for meta learning rate')
  27. parser.add_argument('--inner', type=int, default=5,
  28. help='number of gradient steps in inner loop (during training)')
  29. parser.add_argument('--inner_eval', type=int, default=5,
  30. help='number of gradient updates at test time (for evaluation)')
  31. parser.add_argument('--first_order', action='store_true', default=False,
  32. help='run first order approximation of CAVIA')
  33. parser.add_argument('--adapt_transform', action='store_true', default=False,
  34. help='run adaptation transform')
  35. parser.add_argument('--transformer', type=str, default="kronoker",
  36. help='transformer type')
  37. parser.add_argument('--meta_algo', type=str, default="gbml",
  38. help='MAML/MetaSGD/GBML')
  39. parser.add_argument('--gpu', type=int, default=0,
  40. help='number of gpu to run the code')
  41. parser.add_argument('--epochs', type=int, default=config['num_epoch'],
  42. help='number of gpu to run the code')
  43. # parser.add_argument('--data_root', type=str, default="./movielens/ml-1m", help='path to data root')
  44. # parser.add_argument('--num_workers', type=int, default=4, help='num of workers to use')
  45. # parser.add_argument('--test', action='store_true', default=False, help='num of workers to use')
  46. # parser.add_argument('--embedding_dim', type=int, default=32, help='num of workers to use')
  47. # parser.add_argument('--first_fc_hidden_dim', type=int, default=64, help='num of workers to use')
  48. # parser.add_argument('--second_fc_hidden_dim', type=int, default=64, help='num of workers to use')
  49. # parser.add_argument('--num_epoch', type=int, default=30, help='num of workers to use')
  50. # parser.add_argument('--num_genre', type=int, default=25, help='num of workers to use')
  51. # parser.add_argument('--num_director', type=int, default=2186, help='num of workers to use')
  52. # parser.add_argument('--num_actor', type=int, default=8030, help='num of workers to use')
  53. # parser.add_argument('--num_rate', type=int, default=6, help='num of workers to use')
  54. # parser.add_argument('--num_gender', type=int, default=2, help='num of workers to use')
  55. # parser.add_argument('--num_age', type=int, default=7, help='num of workers to use')
  56. # parser.add_argument('--num_occupation', type=int, default=21, help='num of workers to use')
  57. # parser.add_argument('--num_zipcode', type=int, default=3402, help='num of workers to use')
  58. # parser.add_argument('--rerun', action='store_true', default=False,
  59. # help='Re-run experiment (will override previously saved results)')
  60. args = parser.parse_args()
  61. # use the GPU if available
  62. # args.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  63. # print('Running on device: {}'.format(args.device))
  64. return args
  65. if __name__ == '__main__':
  66. args = parse_args()
  67. print(args)
  68. if config['use_cuda']:
  69. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  70. os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
  71. master_path= "/media/external_10TB/10TB/maheri/melu_data5"
  72. # DATA GENERATION
  73. print("DATA GENERATION PHASE")
  74. if not os.path.exists("{}/".format(master_path)):
  75. os.mkdir("{}/".format(master_path))
  76. # preparing dataset. It needs about 22GB of your hard disk space.
  77. generate(master_path)
  78. # TRAINING
  79. print("TRAINING PHASE")
  80. embedding_dim = config['embedding_dim']
  81. fc1_in_dim = config['embedding_dim'] * 8
  82. fc2_in_dim = config['first_fc_hidden_dim']
  83. fc2_out_dim = config['second_fc_hidden_dim']
  84. use_cuda = config['use_cuda']
  85. fc1 = torch.nn.Linear(fc1_in_dim, fc2_in_dim)
  86. fc2 = torch.nn.Linear(fc2_in_dim, fc2_out_dim)
  87. linear_out = torch.nn.Linear(fc2_out_dim, 1)
  88. head = torch.nn.Sequential(fc1,fc2,linear_out)
  89. if use_cuda:
  90. emb = EmbeddingModule(config).cuda()
  91. else:
  92. emb = EmbeddingModule(config)
  93. # META LEARNING
  94. print("META LEARNING PHASE")
  95. # define transformer
  96. transform = None
  97. if args.transformer == "kronoker":
  98. transform = KroneckerTransform(l2l.nn.KroneckerLinear)
  99. elif args.transformer == "linear":
  100. transform = l2l.optim.ModuleTransform(torch.nn.Linear)
  101. # define meta algorithm
  102. if args.meta_algo == "maml":
  103. head = l2l.algorithms.MAML(head, lr=args.lr_inner,first_order=args.first_order)
  104. elif args.meta_algo == 'metasgd':
  105. head = l2l.algorithms.MetaSGD(head, lr=args.lr_inner,first_order=args.first_order)
  106. elif args.meta_algo == 'gbml':
  107. head = l2l.algorithms.GBML(head, transform=transform, lr=args.lr_inner,adapt_transform=args.adapt_transform, first_order=args.first_order)
  108. if use_cuda:
  109. head.cuda()
  110. # Setup optimization
  111. print("SETUP OPTIMIZATION PHASE")
  112. all_parameters = list(emb.parameters()) + list(head.parameters())
  113. optimizer = torch.optim.Adam(all_parameters, lr=args.lr_meta)
  114. # loss = torch.nn.MSELoss(reduction='mean')
  115. # Load training dataset.
  116. print("LOAD DATASET PHASE")
  117. training_set_size = int(len(os.listdir("{}/warm_state".format(master_path))) / 4)
  118. supp_xs_s = []
  119. supp_ys_s = []
  120. query_xs_s = []
  121. query_ys_s = []
  122. for idx in range(training_set_size):
  123. supp_xs_s.append(pickle.load(open("{}/warm_state/supp_x_{}.pkl".format(master_path, idx), "rb")))
  124. supp_ys_s.append(pickle.load(open("{}/warm_state/supp_y_{}.pkl".format(master_path, idx), "rb")))
  125. query_xs_s.append(pickle.load(open("{}/warm_state/query_x_{}.pkl".format(master_path, idx), "rb")))
  126. query_ys_s.append(pickle.load(open("{}/warm_state/query_y_{}.pkl".format(master_path, idx), "rb")))
  127. total_dataset = list(zip(supp_xs_s, supp_ys_s, query_xs_s, query_ys_s))
  128. del(supp_xs_s, supp_ys_s, query_xs_s, query_ys_s)
  129. training_set_size = len(total_dataset)
  130. batch_size = config['batch_size']
  131. # torch.cuda.empty_cache()
  132. random.shuffle(total_dataset)
  133. num_batch = int(training_set_size / batch_size)
  134. a, b, c, d = zip(*total_dataset)
  135. print("\n\n\n")
  136. for iteration in range(args.epochs):
  137. for i in range(num_batch):
  138. optimizer.zero_grad()
  139. meta_train_error = 0.0
  140. meta_train_accuracy = 0.0
  141. meta_valid_error = 0.0
  142. meta_valid_accuracy = 0.0
  143. meta_test_error = 0.0
  144. meta_test_accuracy = 0.0
  145. print("EPOCH: ", iteration, " BATCH: ", i)
  146. supp_xs = list(a[batch_size * i:batch_size * (i + 1)])
  147. supp_ys = list(b[batch_size * i:batch_size * (i + 1)])
  148. query_xs = list(c[batch_size * i:batch_size * (i + 1)])
  149. query_ys = list(d[batch_size * i:batch_size * (i + 1)])
  150. batch_sz = len(supp_xs)
  151. # if use_cuda:
  152. # for j in range(batch_size):
  153. # supp_xs[j] = supp_xs[j].cuda()
  154. # supp_ys[j] = supp_ys[j].cuda()
  155. # query_xs[j] = query_xs[j].cuda()
  156. # query_ys[j] = query_ys[j].cuda()
  157. for task in range(batch_sz):
  158. # print("EPOCH: ", iteration," BATCH: ",i, "TASK: ",task)
  159. # Compute meta-training loss
  160. # if use_cuda:
  161. sxs = supp_xs[task].cuda()
  162. qxs = query_xs[task].cuda()
  163. sys = supp_ys[task].cuda()
  164. qys = query_ys[task].cuda()
  165. learner = head.clone()
  166. temp_sxs = emb(sxs)
  167. temp_qxs = emb(qxs)
  168. evaluation_error = fast_adapt(learner,
  169. temp_sxs,
  170. temp_qxs,
  171. sys,
  172. qys,
  173. args.inner)
  174. # config['inner'])
  175. evaluation_error.backward()
  176. meta_train_error += evaluation_error.item()
  177. del(sxs,qxs,sys,qys)
  178. supp_xs[task].cpu()
  179. query_xs[task].cpu()
  180. supp_ys[task].cpu()
  181. query_ys[task].cpu()
  182. # Print some metrics
  183. print('Iteration', iteration)
  184. print('Meta Train Error', meta_train_error / batch_sz)
  185. # print('Meta Train Accuracy', meta_train_accuracy / batch_sz)
  186. # print('Meta Valid Error', meta_valid_error / batch_sz)
  187. # print('Meta Valid Accuracy', meta_valid_accuracy / batch_sz)
  188. # print('Meta Test Error', meta_test_error / batch_sz)
  189. # print('Meta Test Accuracy', meta_test_accuracy / batch_sz)
  190. # Average the accumulated gradients and optimize
  191. for p in all_parameters:
  192. p.grad.data.mul_(1.0 / batch_sz)
  193. optimizer.step()
  194. # torch.cuda.empty_cache()
  195. del(supp_xs,supp_ys,query_xs,query_ys)
  196. gc.collect()
  197. print("===============================================\n")
  198. # save model
  199. final_model = torch.nn.Sequential(emb,head)
  200. torch.save(final_model.state_dict(), master_path + "/models_gbml.pkl")
  201. # testing
  202. print("start of test phase")
  203. for test_state in ['warm_state', 'user_cold_state', 'item_cold_state', 'user_and_item_cold_state']:
  204. test_dataset = None
  205. test_set_size = int(len(os.listdir("{}/{}".format(master_path, test_state))) / 4)
  206. supp_xs_s = []
  207. supp_ys_s = []
  208. query_xs_s = []
  209. query_ys_s = []
  210. for idx in range(test_set_size):
  211. supp_xs_s.append(pickle.load(open("{}/{}/supp_x_{}.pkl".format(master_path, test_state, idx), "rb")))
  212. supp_ys_s.append(pickle.load(open("{}/{}/supp_y_{}.pkl".format(master_path, test_state, idx), "rb")))
  213. query_xs_s.append(pickle.load(open("{}/{}/query_x_{}.pkl".format(master_path, test_state, idx), "rb")))
  214. query_ys_s.append(pickle.load(open("{}/{}/query_y_{}.pkl".format(master_path, test_state, idx), "rb")))
  215. test_dataset = list(zip(supp_xs_s, supp_ys_s, query_xs_s, query_ys_s))
  216. del (supp_xs_s, supp_ys_s, query_xs_s, query_ys_s)
  217. print("===================== " + test_state + " =====================")
  218. test(emb,head, test_dataset, batch_size=config['batch_size'], num_epoch=args.epochs,adaptation_step=args.inner_eval)
  219. print("===================================================\n\n\n")
  220. print(args)