sqlnet.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from torch.autograd import Variable
  5. import numpy as np
  6. from modules.word_embedding import WordEmbedding
  7. from modules.aggregator_predict import AggPredictor
  8. from modules.selection_predict import SelPredictor
  9. from modules.sqlnet_condition_predict import SQLNetCondPredictor
  10. from modules.select_number import SelNumPredictor
  11. from modules.where_relation import WhereRelationPredictor
  12. class SQLNet(nn.Module):
  13. def __init__(self, word_emb, N_word, N_h=100, N_depth=2,
  14. gpu=False, use_ca=True, trainable_emb=False):
  15. super(SQLNet, self).__init__()
  16. self.use_ca = use_ca
  17. self.trainable_emb = trainable_emb
  18. self.gpu = gpu
  19. self.N_h = N_h
  20. self.N_depth = N_depth
  21. self.max_col_num = 45
  22. self.max_tok_num = 200
  23. self.SQL_TOK = ['<UNK>', '<END>', 'WHERE', 'AND', 'OR', '==', '>', '<', '!=', '<BEG>']
  24. self.COND_OPS = ['>', '<', '==', '!=']
  25. # Word embedding
  26. self.embed_layer = WordEmbedding(word_emb, N_word, gpu, self.SQL_TOK, our_model=True, trainable=trainable_emb)
  27. # Predict the number of selected columns
  28. self.sel_num = SelNumPredictor(N_word, N_h, N_depth, use_ca=use_ca)
  29. #Predict which columns are selected
  30. self.sel_pred = SelPredictor(N_word, N_h, N_depth, self.max_tok_num, use_ca=use_ca)
  31. #Predict aggregation functions of corresponding selected columns
  32. self.agg_pred = AggPredictor(N_word, N_h, N_depth, use_ca=use_ca)
  33. #Predict number of conditions, condition columns, condition operations and condition values
  34. self.cond_pred = SQLNetCondPredictor(N_word, N_h, N_depth, self.max_col_num, self.max_tok_num, use_ca, gpu)
  35. # Predict condition relationship, like 'and', 'or'
  36. self.where_rela_pred = WhereRelationPredictor(N_word, N_h, N_depth, use_ca=use_ca)
  37. self.CE = nn.CrossEntropyLoss()
  38. self.softmax = nn.Softmax(dim=-1)
  39. self.log_softmax = nn.LogSoftmax()
  40. self.bce_logit = nn.BCEWithLogitsLoss()
  41. if gpu:
  42. self.cuda()
  43. def generate_gt_where_seq_test(self, q, gt_cond_seq):
  44. ret_seq = []
  45. for cur_q, ans in zip(q, gt_cond_seq):
  46. temp_q = u"".join(cur_q)
  47. cur_q = [u'<BEG>'] + cur_q + [u'<END>']
  48. record = []
  49. record_cond = []
  50. for cond in ans:
  51. if cond[2] not in temp_q:
  52. record.append((False, cond[2]))
  53. else:
  54. record.append((True, cond[2]))
  55. for idx, item in enumerate(record):
  56. temp_ret_seq = []
  57. if item[0]:
  58. temp_ret_seq.append(0)
  59. temp_ret_seq.extend(list(range(temp_q.index(item[1])+1,temp_q.index(item[1])+len(item[1])+1)))
  60. temp_ret_seq.append(len(cur_q)-1)
  61. else:
  62. temp_ret_seq.append([0,len(cur_q)-1])
  63. record_cond.append(temp_ret_seq)
  64. ret_seq.append(record_cond)
  65. return ret_seq
  66. def forward(self, q, col, col_num, gt_where = None, gt_cond=None, reinforce=False, gt_sel=None, gt_sel_num=None):
  67. B = len(q)
  68. sel_num_score = None
  69. agg_score = None
  70. sel_score = None
  71. cond_score = None
  72. #Predict aggregator
  73. if self.trainable_emb:
  74. x_emb_var, x_len = self.agg_embed_layer.gen_x_batch(q, col)
  75. col_inp_var, col_name_len, col_len = self.agg_embed_layer.gen_col_batch(col)
  76. max_x_len = max(x_len)
  77. agg_score = self.agg_pred(x_emb_var, x_len, col_inp_var,
  78. col_name_len, col_len, col_num, gt_sel=gt_sel)
  79. x_emb_var, x_len = self.sel_embed_layer.gen_x_batch(q, col)
  80. col_inp_var, col_name_len, col_len = self.sel_embed_layer.gen_col_batch(col)
  81. max_x_len = max(x_len)
  82. sel_score = self.sel_pred(x_emb_var, x_len, col_inp_var,
  83. col_name_len, col_len, col_num)
  84. x_emb_var, x_len = self.cond_embed_layer.gen_x_batch(q, col)
  85. col_inp_var, col_name_len, col_len = self.cond_embed_layer.gen_col_batch(col)
  86. max_x_len = max(x_len)
  87. cond_score = self.cond_pred(x_emb_var, x_len, col_inp_var, col_name_len, col_len, col_num, gt_where, gt_cond, reinforce=reinforce)
  88. where_rela_score = None
  89. else:
  90. x_emb_var, x_len = self.embed_layer.gen_x_batch(q, col)
  91. col_inp_var, col_name_len, col_len = self.embed_layer.gen_col_batch(col)
  92. sel_num_score = self.sel_num(x_emb_var, x_len, col_inp_var, col_name_len, col_len, col_num)
  93. # x_emb_var: embedding of each question
  94. # x_len: length of each question
  95. # col_inp_var: embedding of each header
  96. # col_name_len: length of each header
  97. # col_len: number of headers in each table, array type
  98. # col_num: number of headers in each table, list type
  99. if gt_sel_num:
  100. pr_sel_num = gt_sel_num
  101. else:
  102. pr_sel_num = np.argmax(sel_num_score.data.cpu().numpy(), axis=1)
  103. sel_score = self.sel_pred(x_emb_var, x_len, col_inp_var, col_name_len, col_len, col_num)
  104. if gt_sel:
  105. pr_sel = gt_sel
  106. else:
  107. num = np.argmax(sel_num_score.data.cpu().numpy(), axis=1)
  108. sel = sel_score.data.cpu().numpy()
  109. pr_sel = [list(np.argsort(-sel[b])[:num[b]]) for b in range(len(num))]
  110. agg_score = self.agg_pred(x_emb_var, x_len, col_inp_var, col_name_len, col_len, col_num, gt_sel=pr_sel, gt_sel_num=pr_sel_num)
  111. where_rela_score = self.where_rela_pred(x_emb_var, x_len, col_inp_var, col_name_len, col_len, col_num)
  112. cond_score = self.cond_pred(x_emb_var, x_len, col_inp_var, col_name_len, col_len, col_num, gt_where, gt_cond, reinforce=reinforce)
  113. return (sel_num_score, sel_score, agg_score, cond_score, where_rela_score)
  114. def loss(self, score, truth_num, gt_where):
  115. sel_num_score, sel_score, agg_score, cond_score, where_rela_score = score
  116. B = len(truth_num)
  117. loss = 0
  118. # Evaluate select number
  119. sel_num_truth = map(lambda x:x[0], truth_num)
  120. sel_num_truth = torch.from_numpy(np.array(sel_num_truth))
  121. if self.gpu:
  122. sel_num_truth = Variable(sel_num_truth.cuda())
  123. else:
  124. sel_num_truth = Variable(sel_num_truth)
  125. loss += self.CE(sel_num_score, sel_num_truth)
  126. # Evaluate select column
  127. T = len(sel_score[0])
  128. truth_prob = np.zeros((B,T), dtype=np.float32)
  129. for b in range(B):
  130. truth_prob[b][list(truth_num[b][1])] = 1
  131. data = torch.from_numpy(truth_prob)
  132. if self.gpu:
  133. sel_col_truth_var = Variable(data.cuda())
  134. else:
  135. sel_col_truth_var = Variable(data)
  136. sigm = nn.Sigmoid()
  137. sel_col_prob = sigm(sel_score)
  138. bce_loss = -torch.mean(
  139. 3*(sel_col_truth_var * torch.log(sel_col_prob+1e-10)) +
  140. (1-sel_col_truth_var) * torch.log(1-sel_col_prob+1e-10)
  141. )
  142. loss += bce_loss
  143. # Evaluate select aggregation
  144. for b in range(len(truth_num)):
  145. data = torch.from_numpy(np.array(truth_num[b][2]))
  146. if self.gpu:
  147. sel_agg_truth_var = Variable(data.cuda())
  148. else:
  149. sel_agg_truth_var = Variable(data)
  150. sel_agg_pred = agg_score[b, :len(truth_num[b][1])]
  151. loss += (self.CE(sel_agg_pred, sel_agg_truth_var)) / len(truth_num)
  152. cond_num_score, cond_col_score, cond_op_score, cond_str_score = cond_score
  153. # Evaluate the number of conditions
  154. cond_num_truth = map(lambda x:x[3], truth_num)
  155. data = torch.from_numpy(np.array(cond_num_truth))
  156. if self.gpu:
  157. try:
  158. cond_num_truth_var = Variable(data.cuda())
  159. except:
  160. print "cond_num_truth_var error"
  161. print data
  162. exit(0)
  163. else:
  164. cond_num_truth_var = Variable(data)
  165. loss += self.CE(cond_num_score, cond_num_truth_var)
  166. # Evaluate the columns of conditions
  167. T = len(cond_col_score[0])
  168. truth_prob = np.zeros((B, T), dtype=np.float32)
  169. for b in range(B):
  170. if len(truth_num[b][4]) > 0:
  171. truth_prob[b][list(truth_num[b][4])] = 1
  172. data = torch.from_numpy(truth_prob)
  173. if self.gpu:
  174. cond_col_truth_var = Variable(data.cuda())
  175. else:
  176. cond_col_truth_var = Variable(data)
  177. sigm = nn.Sigmoid()
  178. cond_col_prob = sigm(cond_col_score)
  179. bce_loss = -torch.mean(
  180. 3*(cond_col_truth_var * torch.log(cond_col_prob+1e-10)) +
  181. (1-cond_col_truth_var) * torch.log(1-cond_col_prob+1e-10) )
  182. loss += bce_loss
  183. # Evaluate the operator of conditions
  184. for b in range(len(truth_num)):
  185. if len(truth_num[b][5]) == 0:
  186. continue
  187. data = torch.from_numpy(np.array(truth_num[b][5]))
  188. if self.gpu:
  189. cond_op_truth_var = Variable(data.cuda())
  190. else:
  191. cond_op_truth_var = Variable(data)
  192. cond_op_pred = cond_op_score[b, :len(truth_num[b][5])]
  193. try:
  194. loss += (self.CE(cond_op_pred, cond_op_truth_var) / len(truth_num))
  195. except:
  196. print cond_op_pred
  197. print cond_op_truth_var
  198. exit(0)
  199. #Evaluate the strings of conditions
  200. for b in range(len(gt_where)):
  201. for idx in range(len(gt_where[b])):
  202. cond_str_truth = gt_where[b][idx]
  203. if len(cond_str_truth) == 1:
  204. continue
  205. data = torch.from_numpy(np.array(cond_str_truth[1:]))
  206. if self.gpu:
  207. cond_str_truth_var = Variable(data.cuda())
  208. else:
  209. cond_str_truth_var = Variable(data)
  210. str_end = len(cond_str_truth)-1
  211. cond_str_pred = cond_str_score[b, idx, :str_end]
  212. loss += (self.CE(cond_str_pred, cond_str_truth_var) \
  213. / (len(gt_where) * len(gt_where[b])))
  214. # Evaluate condition relationship, and / or
  215. where_rela_truth = map(lambda x:x[6], truth_num)
  216. data = torch.from_numpy(np.array(where_rela_truth))
  217. if self.gpu:
  218. try:
  219. where_rela_truth = Variable(data.cuda())
  220. except:
  221. print "where_rela_truth error"
  222. print data
  223. exit(0)
  224. else:
  225. where_rela_truth = Variable(data)
  226. loss += self.CE(where_rela_score, where_rela_truth)
  227. return loss
  228. def check_acc(self, vis_info, pred_queries, gt_queries):
  229. def gen_cond_str(conds, header):
  230. if len(conds) == 0:
  231. return 'None'
  232. cond_str = []
  233. for cond in conds:
  234. cond_str.append(header[cond[0]] + ' ' +
  235. self.COND_OPS[cond[1]] + ' ' + unicode(cond[2]).lower())
  236. return 'WHERE ' + ' AND '.join(cond_str)
  237. tot_err = sel_num_err = agg_err = sel_err = 0.0
  238. cond_num_err = cond_col_err = cond_op_err = cond_val_err = cond_rela_err = 0.0
  239. for b, (pred_qry, gt_qry) in enumerate(zip(pred_queries, gt_queries)):
  240. good = True
  241. sel_pred, agg_pred, where_rela_pred = pred_qry['sel'], pred_qry['agg'], pred_qry['cond_conn_op']
  242. sel_gt, agg_gt, where_rela_gt = gt_qry['sel'], gt_qry['agg'], gt_qry['cond_conn_op']
  243. if where_rela_gt != where_rela_pred:
  244. good = False
  245. cond_rela_err += 1
  246. if len(sel_pred) != len(sel_gt):
  247. good = False
  248. sel_num_err += 1
  249. pred_sel_dict = {k:v for k,v in zip(list(sel_pred), list(agg_pred))}
  250. gt_sel_dict = {k:v for k,v in zip(sel_gt, agg_gt)}
  251. if set(sel_pred) != set(sel_gt):
  252. good = False
  253. sel_err += 1
  254. agg_pred = [pred_sel_dict[x] for x in sorted(pred_sel_dict.keys())]
  255. agg_gt = [gt_sel_dict[x] for x in sorted(gt_sel_dict.keys())]
  256. if agg_pred != agg_gt:
  257. good = False
  258. agg_err += 1
  259. cond_pred = pred_qry['conds']
  260. cond_gt = gt_qry['conds']
  261. if len(cond_pred) != len(cond_gt):
  262. good = False
  263. cond_num_err += 1
  264. else:
  265. cond_op_pred, cond_op_gt = {}, {}
  266. cond_val_pred, cond_val_gt = {}, {}
  267. for p, g in zip(cond_pred, cond_gt):
  268. cond_op_pred[p[0]] = p[1]
  269. cond_val_pred[p[0]] = p[2]
  270. cond_op_gt[g[0]] = g[1]
  271. cond_val_gt[g[0]] = g[2]
  272. if set(cond_op_pred.keys()) != set(cond_op_gt.keys()):
  273. cond_col_err += 1
  274. good=False
  275. where_op_pred = [cond_op_pred[x] for x in sorted(cond_op_pred.keys())]
  276. where_op_gt = [cond_op_gt[x] for x in sorted(cond_op_gt.keys())]
  277. if where_op_pred != where_op_gt:
  278. cond_op_err += 1
  279. good=False
  280. where_val_pred = [cond_val_pred[x] for x in sorted(cond_val_pred.keys())]
  281. where_val_gt = [cond_val_gt[x] for x in sorted(cond_val_gt.keys())]
  282. if where_val_pred != where_val_gt:
  283. cond_val_err += 1
  284. good=False
  285. if not good:
  286. tot_err += 1
  287. return np.array((sel_num_err, sel_err, agg_err, cond_num_err, cond_col_err, cond_op_err, cond_val_err , cond_rela_err)), tot_err
  288. def gen_query(self, score, q, col, raw_q, reinforce=False, verbose=False):
  289. """
  290. :param score:
  291. :param q: token-questions
  292. :param col: token-headers
  293. :param raw_q: original question sequence
  294. :return:
  295. """
  296. def merge_tokens(tok_list, raw_tok_str):
  297. tok_str = raw_tok_str# .lower()
  298. alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789$('
  299. special = {'-LRB-':'(',
  300. '-RRB-':')',
  301. '-LSB-':'[',
  302. '-RSB-':']',
  303. '``':'"',
  304. '\'\'':'"',
  305. '--':u'\u2013'}
  306. ret = ''
  307. double_quote_appear = 0
  308. for raw_tok in tok_list:
  309. if not raw_tok:
  310. continue
  311. tok = special.get(raw_tok, raw_tok)
  312. if tok == '"':
  313. double_quote_appear = 1 - double_quote_appear
  314. if len(ret) == 0:
  315. pass
  316. elif len(ret) > 0 and ret + ' ' + tok in tok_str:
  317. ret = ret + ' '
  318. elif len(ret) > 0 and ret + tok in tok_str:
  319. pass
  320. elif tok == '"':
  321. if double_quote_appear:
  322. ret = ret + ' '
  323. # elif tok[0] not in alphabet:
  324. # pass
  325. elif (ret[-1] not in ['(', '/', u'\u2013', '#', '$', '&']) \
  326. and (ret[-1] != '"' or not double_quote_appear):
  327. ret = ret + ' '
  328. ret = ret + tok
  329. return ret.strip()
  330. sel_num_score, sel_score, agg_score, cond_score, where_rela_score = score
  331. # [64,4,6], [64,14], ..., [64,4]
  332. sel_num_score = sel_num_score.data.cpu().numpy()
  333. sel_score = sel_score.data.cpu().numpy()
  334. agg_score = agg_score.data.cpu().numpy()
  335. where_rela_score = where_rela_score.data.cpu().numpy()
  336. ret_queries = []
  337. B = len(agg_score)
  338. cond_num_score,cond_col_score,cond_op_score,cond_str_score =\
  339. [x.data.cpu().numpy() for x in cond_score]
  340. for b in range(B):
  341. cur_query = {}
  342. cur_query['sel'] = []
  343. cur_query['agg'] = []
  344. sel_num = np.argmax(sel_num_score[b])
  345. max_col_idxes = np.argsort(-sel_score[b])[:sel_num]
  346. # find the most-probable columns' indexes
  347. max_agg_idxes = np.argsort(-agg_score[b])[:sel_num]
  348. cur_query['sel'].extend([int(i) for i in max_col_idxes])
  349. cur_query['agg'].extend([i[0] for i in max_agg_idxes])
  350. cur_query['cond_conn_op'] = np.argmax(where_rela_score[b])
  351. cur_query['conds'] = []
  352. cond_num = np.argmax(cond_num_score[b])
  353. all_toks = ['<BEG>'] + q[b] + ['<END>']
  354. max_idxes = np.argsort(-cond_col_score[b])[:cond_num]
  355. for idx in range(cond_num):
  356. cur_cond = []
  357. cur_cond.append(max_idxes[idx]) # where-col
  358. cur_cond.append(np.argmax(cond_op_score[b][idx])) # where-op
  359. cur_cond_str_toks = []
  360. for str_score in cond_str_score[b][idx]:
  361. str_tok = np.argmax(str_score[:len(all_toks)])
  362. str_val = all_toks[str_tok]
  363. if str_val == '<END>':
  364. break
  365. cur_cond_str_toks.append(str_val)
  366. cur_cond.append(merge_tokens(cur_cond_str_toks, raw_q[b]))
  367. cur_query['conds'].append(cur_cond)
  368. ret_queries.append(cur_query)
  369. return ret_queries