id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
165,017
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def frange_cycle_linear(n_iter, start=0.01, stop=1.0, n_cycle=4, ratio=0.5): L = np.ones(n_iter) * stop period = n_iter/n_cycle step = (stop-start)/(period*ratio) # linear schedule for c in range(n_cycle): v, i = start, 0 while v <= stop and (int(i+c*period) < n_iter): L[int(i+c*period)] = v v += step i += 1 return L
null
165,018
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def num_params(model): return sum([np.prod(p.size()) for p in model.parameters() if p.requires_grad])
null
165,019
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * The provided code snippet includes necessary dependencies for implementing the `switch_schedule` function. Write a Python function `def switch_schedule(schedule, mult, switch)` to solve the following problem: Apply LR multiplier before iteration "switch" Here is the function: def switch_schedule(schedule, mult, switch): """ Apply LR multiplier before iteration "switch" """ def f(e): s = schedule(e) if e < switch: return s * mult return s return f
Apply LR multiplier before iteration "switch"
165,020
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def linear_schedule(args): def f(e): if e <= args.warmup: return e / args.warmup return max((e - args.iterations) / (args.warmup - args.iterations), 0) return f
null
165,021
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def get_mask(x_len): mask = torch.arange(max(x_len), device=x_len.device)[None, :] < x_len[:, None] # [bs, max_len] return mask.bool()
null
165,022
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def get_reverse_mask(x_len): mask = torch.arange(max(x_len)-1, -1, -1, device=x_len.device)[None, :] < x_len[:, None] # [bs, max_len] return mask.bool()
null
165,023
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def compare_tokens(x, y, eos_id): if eos_id in x: x = x[:x.index(eos_id)] if eos_id in y: y = y[:y.index(eos_id)] return x == y
null
165,024
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def seed_everything(seed=42): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False os.environ['PYTHONHASHSEED'] = str(seed) torch.cuda.manual_seed_all(seed)
null
165,025
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def pad_tensor(tensor, length, pad_token=0): return torch.cat([tensor, tensor.new(tensor.size(0), length - tensor.size()[1]).fill_(pad_token)], dim=1) The provided code snippet includes necessary dependencies for implementing the `communicate_tensor` function. Write a Python function `def communicate_tensor(tensor_list, pad_token=0)` to solve the following problem: collect tensors from all processes Here is the function: def communicate_tensor(tensor_list, pad_token=0): ''' collect tensors from all processes ''' if len(tensor_list) == 0: return None device = tensor_list[0].device max_len = torch.tensor(max([i.shape[1] for i in tensor_list]), dtype=torch.int64, device=device) if dist.is_initialized(): # Obtain the max_len of the second dim of each tensor dist.all_reduce(max_len, op=dist.ReduceOp.MAX) # Pad tensors to the max_len tensor = torch.cat([pad_tensor(i, max_len, pad_token) for i in tensor_list], dim=0) tensor_bs = torch.tensor(tensor.shape[0], dtype=torch.int64, device=device) max_tensor_bs = torch.tensor(tensor.shape[0], dtype=torch.int64, device=device) if dist.is_initialized(): dist.all_reduce(max_tensor_bs, op=dist.ReduceOp.MAX) # Obtain the max_tensor_bs of each tensor if max_tensor_bs != tensor_bs: tensor = torch.cat([tensor, tensor.new(max_tensor_bs-tensor_bs, tensor.shape[1]).fill_(pad_token)], dim=0) # Gather padded tensors and the bs of each tensor tensor_list = [torch.ones_like(tensor).fill_(pad_token) for _ in range(dist.get_world_size())] tensor_bs_list = [torch.ones_like(tensor_bs).fill_(pad_token) for _ in range(dist.get_world_size())] dist.all_gather(tensor_list=tensor_list, tensor=tensor.contiguous()) dist.all_gather(tensor_list=tensor_bs_list, tensor=tensor_bs) # Cut the padded batch for i in range(dist.get_world_size()): tensor_list[i] = tensor_list[i][:tensor_bs_list[i]] tensor = torch.cat(tensor_list, dim=0) return tensor
collect tensors from all processes
165,026
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def cut_eos(seq, eos_id): if eos_id not in seq: return seq return seq[:seq.index(eos_id)]
null
165,027
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def cal_metrics_from_pred_files(res_file): with open(res_file, 'r', encoding='utf-8') as f: res = [json.loads(i) for i in f.readlines()] y_true = [i['ans_gold'] for i in res] y_pred = [i['ans_pred'] for i in res] return { "accuracy": accuracy_score(y_true, y_pred), }
null
165,028
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * The provided code snippet includes necessary dependencies for implementing the `slot_f1_score` function. Write a Python function `def slot_f1_score(pred_slots, true_slots)` to solve the following problem: pred_slots, true_slots are like [['from_location:10-11', 'leaving_date:12-13']] Here is the function: def slot_f1_score(pred_slots, true_slots): ''' pred_slots, true_slots are like [['from_location:10-11', 'leaving_date:12-13']] ''' slot_types = set([slot.split(":")[0] for row in true_slots for slot in row]) slot_type_f1_scores = [] for slot_type in slot_types: predictions_for_slot = [[p for p in prediction if slot_type in p] for prediction in pred_slots] # [['from_location'],[],[],['from_location']] labels_for_slot = [[l for l in label if slot_type in l] for label in true_slots] proposal_made = [len(p) > 0 for p in predictions_for_slot] has_label = [len(l) > 0 for l in labels_for_slot] prediction_correct = [prediction == label for prediction, label in zip(predictions_for_slot, labels_for_slot)] true_positives = sum([ int(proposed and correct) for proposed, correct in zip(proposal_made, prediction_correct)]) num_predicted = sum([int(proposed) for proposed in proposal_made]) num_to_recall = sum([int(hl) for hl in has_label]) precision = true_positives / (1e-5 + num_predicted) recall = true_positives / (1e-5 + num_to_recall) f1_score = 2 * precision * recall / (1e-5 + precision + recall) slot_type_f1_scores.append(f1_score) return np.mean(slot_type_f1_scores)
pred_slots, true_slots are like [['from_location:10-11', 'leaving_date:12-13']]
165,029
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def textid_decode(text, eos, tokz, contain_eos=False): if eos in text: if contain_eos: idx = text.index(eos) text = text[:idx] else: text = text[:text.index(eos)] text_id = text len_text = len(text) text = tokz.decode(text).strip() return text, len_text, text_id
null
165,030
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def pad_seq(seq, pad, max_len, pad_left=False): if pad_left: return [pad] * (max_len - len(seq)) + seq else: return seq + [pad] * (max_len - len(seq)) def padding_convert(text_list, eos): tt_list = [] for text in text_list: if eos in text: eos_indexs = [i for i, x in enumerate(text) if x==eos] # print('eos index', eos_indexs,flush=True) if len(eos_indexs)>1: text = text[:eos_indexs[1]] tt_list.append(text) tt_lens = [len(i) for i in tt_list] tt_lens = torch.tensor(tt_lens, dtype=torch.long).to('cuda') tt_pad = torch.tensor([pad_seq(i, eos, max(tt_lens), pad_left=True) for i in tt_list], dtype=torch.long).to('cuda') return tt_pad, tt_lens
null
165,031
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def strip_list(seq, eos_id): l, r = 0, len(seq)-1 for i in range(len(seq)): if seq[i] != eos_id: break l = i for i in range(len(seq)-1, -1, -1): if seq[i] != eos_id: break r = i return seq[l+1:r]
null
165,032
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def aug_unlabeled_data(batch, tokz, args, task_name): # * Augment sentence with EDA. input_sen, context_sen, all_sen, ans_sen = [],[],[],[] task_prefix = task_name + ':' raw_sen, ques_sen = [],[] for i in batch: text = i['raw_text'] ans_text = i['ans_sen'] question = i['question'] aug_text_list = eda(text, num_aug=args.num_aug) # aug_text_list = eda(text, num_aug=1) for aug_text in aug_text_list: input_text = task_prefix + aug_text + '<QUES>' + question input_sen.append(input_text) context_sen.append(input_text+'<ANS>') # all_sen.append(aug_text+'<ANS>'+ans_text) all_sen.append(aug_text+'<QUES>') # train LM only on the inputs ans_sen.append(ans_text) raw_sen.append(aug_text) ques_sen.append(question) input_encoding = tokz(input_sen, padding='longest', max_length=args.max_input_len, truncation=True, return_tensors='pt') all_encoding = tokz(all_sen, padding='longest', max_length=args.max_input_len, truncation=True, return_tensors='pt') context_encoding = tokz(context_sen, padding='longest', max_length=args.max_input_len, truncation=True, return_tensors='pt') ans_encoding = tokz(ans_sen, padding='longest', max_length=args.max_ans_len, truncation=True, return_tensors='pt') raw_text_encoding = tokz(raw_sen, padding='longest', max_length=args.max_input_len, truncation=True, return_tensors='pt') question_encoding = tokz(ques_sen, padding='longest', max_length=args.max_input_len, truncation=True, return_tensors='pt') res = {} res["input_id"], res['input_mask'] = input_encoding.input_ids, input_encoding.attention_mask res["all_id"], res['all_mask'] = all_encoding.input_ids, all_encoding.attention_mask res["context_id"], res['context_mask'] = context_encoding.input_ids, context_encoding.attention_mask res["ans_id"], res['ans_mask'] = ans_encoding.input_ids, ans_encoding.attention_mask res["raw_id"], res['raw_mask'] = raw_text_encoding.input_ids, raw_text_encoding.attention_mask res["ques_id"], res['ques_mask'] = question_encoding.input_ids, question_encoding.attention_mask res['batch_text'] = batch return res
null
165,033
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def sigmoid_rampup(current, rampup_length): """Exponential rampup from https://arxiv.org/abs/1610.02242""" if rampup_length == 0: return 1.0 else: current = np.clip(current, 0.0, rampup_length) phase = 1.0 - current / rampup_length return float(np.exp(-5.0 * phase * phase)) def get_current_consistency_weight(args, epoch): # Consistency ramp-up from https://arxiv.org/abs/1610.02242 return args.consistency * sigmoid_rampup(epoch, args.consistency_rampup)
null
165,034
from unifymodel.dataset import PadBatchSeq, pad_seq, get_unlabel_data import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy from transformers import GPT2Config, GPT2Model, GPT2LMHeadModel, GPT2Tokenizer import torch.nn.functional as F from tools.eda import * def kl_divergence(mean1, logvar1, mean2, logvar2): # print(mean1.size(),logvar1.size(),mean2.size(),logvar2.size(),flush=True) exponential = logvar1 - logvar2 - \ torch.pow(mean1 - mean2, 2) / logvar2.exp() - \ torch.exp(logvar1 - logvar2) + 1 result = -0.5 * torch.sum(exponential, tuple(range(1, len(exponential.shape)))) return result.mean()
null
165,035
from unifymodel.utils import * from unifymodel.generate import * from unifymodel.model import SSLLModel from unifymodel.dataset import PadBatchSeq, TASK2INFO, LBDataset, get_datasets, get_unlabel_data, get_unlabel_dict, MixedDataset from unifymodel.dataset import * from unifymodel.memory import * from transformers import T5Config, T5Tokenizer, T5Model,T5ForConditionalGeneration, T5AdapterModel from torch.utils.data import DataLoader import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, threading, shutil import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.nn import DataParallel import torch.distributed as dist import torch.multiprocessing as mp import numpy as np import transformers from transformers import get_linear_schedule_with_warmup, Conv1D, AdamW from torch.utils.tensorboard import SummaryWriter import importlib import copy from collections import Counter from rouge import Rouge from metrics import * from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_MASKED_LM_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, BatchEncoding, AutoModelForMaskedLM, FlaxT5ForConditionalGeneration, HfArgumentParser, PreTrainedTokenizerBase, T5Config, is_tensorboard_available, set_seed, T5ForConditionalGeneration, Trainer, TrainingArguments, is_torch_tpu_available, ) from transformers.models.t5.modeling_flax_t5 import shift_tokens_right from pretrain import * def compute_solver_loss(model, loss_fn, total, args=None, kl_loss=None): input_tokens, input_mask, target_tokens, target_mask = total model = model.cuda() model.train() outputs = model(input_ids=input_tokens, attention_mask=input_mask, labels=target_tokens) loss = outputs[0] return loss
null
165,036
from unifymodel.utils import * from unifymodel.generate import * from unifymodel.model import SSLLModel from unifymodel.dataset import PadBatchSeq, TASK2INFO, LBDataset, get_datasets, get_unlabel_data, get_unlabel_dict, MixedDataset from unifymodel.dataset import * from unifymodel.memory import * from transformers import T5Config, T5Tokenizer, T5Model,T5ForConditionalGeneration, T5AdapterModel from torch.utils.data import DataLoader import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, threading, shutil import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.nn import DataParallel import torch.distributed as dist import torch.multiprocessing as mp import numpy as np import transformers from transformers import get_linear_schedule_with_warmup, Conv1D, AdamW from torch.utils.tensorboard import SummaryWriter import importlib import copy from collections import Counter from rouge import Rouge from metrics import * from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_MASKED_LM_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, BatchEncoding, AutoModelForMaskedLM, FlaxT5ForConditionalGeneration, HfArgumentParser, PreTrainedTokenizerBase, T5Config, is_tensorboard_available, set_seed, T5ForConditionalGeneration, Trainer, TrainingArguments, is_torch_tpu_available, ) from transformers.models.t5.modeling_flax_t5 import shift_tokens_right from pretrain import * def compute_lm_loss(model, loss_fn, total, args=None, kl_loss=None): input_tokens, decoder_input_ids, labels = total model = model.cuda().train() decoder_input_ids = None outputs = model(input_ids=input_tokens, decoder_input_ids=decoder_input_ids, labels=labels) loss = outputs[0] return loss
null
165,037
from unifymodel.utils import * from unifymodel.generate import * from unifymodel.model import SSLLModel from unifymodel.dataset import PadBatchSeq, TASK2INFO, LBDataset, get_datasets, get_unlabel_data, get_unlabel_dict, MixedDataset from unifymodel.dataset import * from unifymodel.memory import * from transformers import T5Config, T5Tokenizer, T5Model,T5ForConditionalGeneration, T5AdapterModel from torch.utils.data import DataLoader import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, threading, shutil import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.nn import DataParallel import torch.distributed as dist import torch.multiprocessing as mp import numpy as np import transformers from transformers import get_linear_schedule_with_warmup, Conv1D, AdamW from torch.utils.tensorboard import SummaryWriter import importlib import copy from collections import Counter from rouge import Rouge from metrics import * from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_MASKED_LM_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, BatchEncoding, AutoModelForMaskedLM, FlaxT5ForConditionalGeneration, HfArgumentParser, PreTrainedTokenizerBase, T5Config, is_tensorboard_available, set_seed, T5ForConditionalGeneration, Trainer, TrainingArguments, is_torch_tpu_available, ) from transformers.models.t5.modeling_flax_t5 import shift_tokens_right from pretrain import * def compute_feedback_loss(model, ema_model, loss_fn, total, args=None, kl_loss=None): input_tokens, input_mask, target_tokens, target_mask = total model, ema_model = model.cuda(), ema_model.cuda() model.train() ema_model.train() # outputs = model(input_ids=input_tokens, attention_mask=input_mask, labels=target_tokens) # logits = outputs.logits.contiguous() # logits = logits.view(-1, logits.size(-1)) ema_outputs = ema_model(input_ids=input_tokens, attention_mask=input_mask, labels=target_tokens) # ema_logits = ema_outputs.logits.contiguous().detach() # ema_logits = ema_logits.view(-1, ema_logits.size(-1)) # target_mask = (target_mask>0) # feedback_loss = kl_loss(ema_logits, logits, label_mask=target_mask) # Student model give feedback to teacher model. feedback_loss = ema_outputs.loss print('feedback_loss',feedback_loss.item(), flush=True) return feedback_loss
null
165,038
from unifymodel.utils import * from unifymodel.generate import * from unifymodel.model import SSLLModel from unifymodel.dataset import PadBatchSeq, TASK2INFO, LBDataset, get_datasets, get_unlabel_data, get_unlabel_dict, MixedDataset from unifymodel.dataset import * from unifymodel.memory import * from transformers import T5Config, T5Tokenizer, T5Model,T5ForConditionalGeneration, T5AdapterModel from torch.utils.data import DataLoader import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, threading, shutil import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.nn import DataParallel import torch.distributed as dist import torch.multiprocessing as mp import numpy as np import transformers from transformers import get_linear_schedule_with_warmup, Conv1D, AdamW from torch.utils.tensorboard import SummaryWriter import importlib import copy from collections import Counter from rouge import Rouge from metrics import * from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_MASKED_LM_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, BatchEncoding, AutoModelForMaskedLM, FlaxT5ForConditionalGeneration, HfArgumentParser, PreTrainedTokenizerBase, T5Config, is_tensorboard_available, set_seed, T5ForConditionalGeneration, Trainer, TrainingArguments, is_torch_tpu_available, ) from transformers.models.t5.modeling_flax_t5 import shift_tokens_right from pretrain import * def compute_consistency_loss(model, ema_model, loss_fn, total, args=None, kl_loss=None, tokz=None, epoch=0, task_name=None): input_tokens, input_mask, target_tokens, target_mask = total model, ema_model = model.cuda(), ema_model.cuda() model.train() ema_model.train() btz = input_tokens.size()[0] # print(f'length of tokz {len(tokz)}', flush=True) assert task_name is not None max_ans_len = max_ans_length_dict[task_name] # * Teacher prediction ema_seqs, ema_scores = get_answer(tokz, ema_model, input_tokens, input_mask, max_ans_len, args=args, is_eval=False) # print('ema_seqs shape',ema_seqs.shape,'input shape',input_tokens.shape,flush=True) # ema_seqs [192, 20], target [192, 4], input [192, 119] # print(f'length of tokz {len(tokz)}', flush=True) ema_target_tokens = ema_seqs[:,1:] # print(f'ema tgt token 0 {ema_target_tokens[0]}',flush=True) ema_target_tokens[ema_target_tokens==tokz.pad_token_id] = -100 # print(f'ema tgt token 1 {ema_target_tokens[0]}',flush=True) ema_target_tokens = ema_target_tokens.contiguous() ema_target_mask = torch.ones_like(ema_target_tokens) ema_target_mask[ema_target_tokens==-100] = 0 ema_target_mask = (ema_target_mask > 0) if args.add_confidence_selection: _, ppl = compute_ppl(ema_seqs[:,1:], ema_scores, tokz) ppl = torch.stack(torch.split(ppl, args.pl_sample_num)) # [16, 5] all_ppl = [] for i in range(btz): example_ppl = ppl[i,:] # scores shape torch.Size([5, 10, 50258]) seq shape torch.Size([5, 10]) min_idx = torch.argmin(example_ppl) all_ppl.append(example_ppl[min_idx]) ppl_batch = torch.tensor(all_ppl) # print(f'ppl {ppl_batch}', flush=True) # * Select high confidence outputs. greater_thresh = torch.le(ppl_batch, args.pseudo_tau).to('cuda') # print(f'confidence mask {greater_thresh.shape}',flush=True) # [48] num_aug * batch_size # print(f'ema tgt tokens {ema_target_tokens.shape}',flush=True) ema_target_tokens = (ema_target_tokens.T * greater_thresh).T ema_target_tokens[ema_target_tokens==tokz.pad_token_id] = -100 # * Student prediction outputs = model(input_ids=input_tokens, attention_mask=input_mask, labels=ema_target_tokens) logits = outputs.logits.contiguous() logits = logits.view(-1, logits.size(-1)) consist_loss = outputs.loss consistency_weight = get_current_consistency_weight(args, epoch) if args.rdrop: outputs2 = model(input_ids=input_tokens, attention_mask=input_mask, labels=ema_target_tokens) logits2 = outputs2.logits.contiguous() logits2 = logits2.view(-1, logits2.size(-1)) rdrop_loss = 0.5 * kl_loss(logits, logits2, label_mask=ema_target_mask) + 0.5 * kl_loss(logits2, logits, label_mask=ema_target_mask) else: rdrop_loss = 0.0 consistency_loss = consistency_weight * (consist_loss + rdrop_loss) print('consistency_kl_loss:',consistency_loss.item(),flush=True) # print(f'rdrop_loss: {rdrop_loss.item()}', flush=True) return consistency_loss
null
165,039
from unifymodel.utils import * from unifymodel.generate import * from unifymodel.model import SSLLModel from unifymodel.dataset import PadBatchSeq, TASK2INFO, LBDataset, get_datasets, get_unlabel_data, get_unlabel_dict, MixedDataset from unifymodel.dataset import * from unifymodel.memory import * from transformers import T5Config, T5Tokenizer, T5Model,T5ForConditionalGeneration, T5AdapterModel from torch.utils.data import DataLoader import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, threading, shutil import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.nn import DataParallel import torch.distributed as dist import torch.multiprocessing as mp import numpy as np import transformers from transformers import get_linear_schedule_with_warmup, Conv1D, AdamW from torch.utils.tensorboard import SummaryWriter import importlib import copy from collections import Counter from rouge import Rouge from metrics import * from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_MASKED_LM_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, BatchEncoding, AutoModelForMaskedLM, FlaxT5ForConditionalGeneration, HfArgumentParser, PreTrainedTokenizerBase, T5Config, is_tensorboard_available, set_seed, T5ForConditionalGeneration, Trainer, TrainingArguments, is_torch_tpu_available, ) from transformers.models.t5.modeling_flax_t5 import shift_tokens_right from pretrain import * def get_model_inputs(data, global_step=10, tokz=None, model_type='cls', task=None, data_type='label'): if model_type=='cls': input_tokens = data['context_id'] input_mask = data['context_mask'].contiguous() if global_step < 3: print('-'*10, 'Solver Inputs and targets', '-'*10, flush=True) print('input:', tokz.decode(input_tokens[0]), flush=True) print('input id:', input_tokens[0], flush=True) print('attention_mask:', input_mask[0], flush=True) if data_type == 'label': target_tokens = data['ans_id'] target_mask = data['ans_mask'].contiguous() if global_step < 3: print('target:',tokz.decode(target_tokens[0]),flush=True) print('target id:', target_tokens[0],flush=True) print('\n',flush=True) target_tokens[target_tokens==tokz.pad_token_id] = -100 target_tokens = target_tokens.contiguous() input_total = (input_tokens.cuda(), input_mask.cuda(), target_tokens.cuda(), target_mask.cuda()) else: input_total = (input_tokens.cuda(), input_mask.cuda(), None, None) return input_total elif model_type=='lm': batch_size = data['input_id'].shape[0] assert task is not None task_prefix_id = tokz.encode(task+':')[0] # print(task_prefix_id, flush=True) input_tokens = torch.full((batch_size,1), task_prefix_id) decoder_input_ids = data['all_id'][:,:-1].contiguous() # labels = data['all_id'][:,1:].clone().detach() labels = data['all_id'][:,:].clone().detach() if global_step < 3: print('-'*10,'LM Inputs and targets','-'*10, flush=True) print('input:',tokz.decode(input_tokens[0]),flush=True) print('input id:',input_tokens[0],flush=True) print('target:',tokz.decode(labels[0]),flush=True) print('target id:', labels[0],flush=True) print('\n',flush=True) labels[labels==tokz.pad_token_id] = -100 input_total = (input_tokens.cuda(), decoder_input_ids.cuda(), labels.cuda()) return input_total elif model_type=='pretrain': input_ids = data['input_ids'].cuda() labels = data['labels'].cuda() if global_step <= 3: print('pretrain_input: ',tokz.decode(input_ids[0],flush=True)) print('pretrain_label: ',tokz.decode(labels[0],flush=True)) labels[labels==tokz.pad_token_id] = -100 labels = labels.contiguous() decoder_input_ids = data['decoder_input_ids'].cuda() return input_ids, labels, decoder_input_ids
null
165,040
from unifymodel.utils import * from unifymodel.generate import * from unifymodel.model import SSLLModel from unifymodel.dataset import PadBatchSeq, TASK2INFO, LBDataset, get_datasets, get_unlabel_data, get_unlabel_dict, MixedDataset from unifymodel.dataset import * from unifymodel.memory import * from transformers import T5Config, T5Tokenizer, T5Model,T5ForConditionalGeneration, T5AdapterModel from torch.utils.data import DataLoader import torch.distributed as dist import os, time, gc, json, pickle, argparse, math, threading, shutil import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torch.nn import DataParallel import torch.distributed as dist import torch.multiprocessing as mp import numpy as np import transformers from transformers import get_linear_schedule_with_warmup, Conv1D, AdamW from torch.utils.tensorboard import SummaryWriter import importlib import copy from collections import Counter from rouge import Rouge from metrics import * from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_MASKED_LM_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, BatchEncoding, AutoModelForMaskedLM, FlaxT5ForConditionalGeneration, HfArgumentParser, PreTrainedTokenizerBase, T5Config, is_tensorboard_available, set_seed, T5ForConditionalGeneration, Trainer, TrainingArguments, is_torch_tpu_available, ) from transformers.models.t5.modeling_flax_t5 import shift_tokens_right from pretrain import * def update_ema_variables(model, ema_model, alpha, global_step): # Use the true average until the exponential average is more correct # alpha = ema_decay alpha = min(1 - 1 / (global_step + 1), alpha) for ema_param, param in zip(ema_model.parameters(), model.parameters()): ema_param.data = ema_param.data.cuda() param.data = param.data.cuda() ema_param.data.mul_(alpha).add_(param.data, alpha=1 - alpha) # ema_param.data.mul_(alpha).add_(1 - alpha, param.data)
null
165,041
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * from pretrain import * from torch.utils.data import DataLoader args = parse_args() if args.data_type == 'intent': TASK2INFO = { "banking": { "dataset_class": LBDataset, "dataset_folder": "banking", "task_type": "CLS", }, "clinc": { "dataset_class": LBDataset, "dataset_folder": "clinc", "task_type": "CLS", }, "hwu": { "dataset_class": LBDataset, "dataset_folder": "hwu", "task_type": "CLS", }, "atis": { "dataset_class": LBDataset, "dataset_folder": "atis", "task_type": "CLS", }, "tod": { "dataset_class": LBDataset, "dataset_folder": "FB_TOD_SF", "task_type": "CLS", }, "snips": { "dataset_class": LBDataset, "dataset_folder": "snips", "task_type": "CLS", }, "top_split1": { "dataset_class": LBDataset, "dataset_folder": "top_split1", "task_type": "CLS", }, "top_split2": { "dataset_class": LBDataset, "dataset_folder": "top_split2", "task_type": "CLS", }, "top_split3": { "dataset_class": LBDataset, "dataset_folder": "top_split3", "task_type": "CLS", } } elif args.data_type =='slot': TASK2INFO = { "dstc8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "dstc8", "task_type": "SlotTagging", }, "restaurant8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "restaurant8", "task_type": "SlotTagging", }, "atis": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "atis", "task_type": "SlotTagging", }, "mit_movie_eng": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_eng", "task_type": "SlotTagging", }, "mit_movie_trivia": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_trivia", "task_type": "SlotTagging", }, "mit_restaurant": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_restaurant", "task_type": "SlotTagging", }, "snips": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "snips", "task_type": "SlotTagging", } } elif args.data_type =='decanlp' or args.data_type == 'tc' or args.data_type == 'mix': TASK2INFO = { "ag": { "dataset_class": LBDataset, "dataset_folder": "ag", "task_type": "tc", }, 'dbpedia':{ 'dataset_class':LBDataset, 'dataset_folder':'dbpedia', 'task_type':'tc', }, 'yelp':{ 'dataset_class':LBDataset, 'dataset_folder':'yelp', 'task_type':'tc', }, 'yahoo':{ 'dataset_class':LBDataset, 'dataset_folder':'yahoo', 'task_type':'tc', }, 'snips':{ 'dataset_class':LBDataset, 'dataset_folder':'snips', 'task_type':'tc', }, 'amazon':{ 'dataset_class':LBDataset, 'dataset_folder':'amazon', 'task_type':'tc', }, 'woz.en':{ 'dataset_class':LBDataset, 'dataset_folder':'woz.en', 'task_type':'decanlp', }, 'squad':{ 'dataset_class':LBDataset, 'dataset_folder':'squad', 'task_type':'decanlp', }, 'sst':{ 'dataset_class':LBDataset, 'dataset_folder':'sst', 'task_type':'decanlp', }, 'srl':{ 'dataset_class':LBDataset, 'dataset_folder':'srl', 'task_type':'decanlp', }, 'wikisql':{ 'dataset_class':LBDataset, 'dataset_folder':'wikisql', 'task_type':'decanlp', } } def get_unlabel_data(path, task): info = TASK2INFO[task] # data_path = os.path.join(path, info['dataset_folder'],'unlabel_train.json') if args.unlabel_ratio == -1: num_unlabel = 2000 else: num_unlabel = args.num_label*args.unlabel_ratio data_path = os.path.join(path, info['dataset_folder'],str(num_unlabel)+'_unlabel_train.json') return data_path
null
165,042
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * from pretrain import * from torch.utils.data import DataLoader class LBDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, max_input_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path self.max_ans_len = args.max_ans_len self.special_token_ids = special_token_ids self.task_name = task_name self.max_input_len = max_input_length_dict[self.task_name] with open(data_path, "r", encoding='utf-8') as f: ori_data = [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) if task_name in ['wikisql','woz.en'] and 'test' in self.data_path: with open(os.path.join(args.data_dir, task_name, 'answers.json'),'r') as f: self.answers = json.load(f) print(f'Number of answers is {len(self.answers)}') if task_name in ['wikisql', 'squad'] and 'test' in self.data_path: self.targets = [] for i in ori_data: self.targets.append(i['output']) def get_answer(self, target): # get answer text from intent # replace - and _ to make the text seems more natural if type(target) == list: target = target[0] if self.task_name == 'wikisql': ans = target else: ans = target.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): if self.task_name in ['wikisql','woz.en','squad','srl']: text = example['input'] question = example['question'] text_wo_question = example['text_wo_question'] else: text = example['input'].replace('-',' ').replace('_',' ').replace('\\',' ') question = example['question'].replace('-',' ').replace('_',' ').replace('\\',' ') text_wo_question = example['text_wo_question'].replace('-',' ').replace('_',' ').replace('\\',' ') ans = self.get_answer(example['output']) if self.task_name in ['woz.en','squad','wikisql'] and 'test' in self.data_path: ans_list = example['output'] return [(text, ans, question, text_wo_question, example['id'], ans_list)] return [(text, ans, question, text_wo_question)] def per_tokenization(self, task_name, d): # print(d,flush=True) # input_text, ans_text = d if self.task_name in ['woz.en','squad','wikisql'] and 'test' in self.data_path: input_text, ans_text, question, text_wo_question, idx, ans_list = d else: input_text, ans_text, question, text_wo_question = d raw_text = text_wo_question input_sen = task_name+':' + raw_text + '<QUES>' + question context_sen = input_sen + '<ANS>' # for evaluation ans_sen = ans_text # all_sen = context_sen + ans_sen all_sen = raw_text + '<QUES>' res_dict = { 'all_sen': all_sen, 'input_sen': input_sen, 'context_sen': context_sen, 'ans_sen': ans_sen, 'question': question, 'raw_text': raw_text } if self.task_name in ['woz.en','squad','wikisql'] and 'test' in self.data_path: res_dict['id'] = idx res_dict['ans_list'] = ans_list return res_dict def data_tokenization(self, task_name, data): # print('data',data[:10],flush=True) data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] def sort_by_index(self): self.data.sort(key=lambda x: x['id']) def get_indices(self): return [d['id'] for d in self.data] def get_unlabel_dict(path, task, tokz, args): info = TASK2INFO[task] special_token_ids = {'ans_token':tokz.convert_tokens_to_ids('ANS:')} if args.data_type == 'intent': return LBDataset(task, tokz, path, args.max_input_len, special_token_ids=special_token_ids) else: return None
null
165,043
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * from pretrain import * from torch.utils.data import DataLoader def write_mix_train_file(label_train_dataset, unlabel_train_dataset, out_file, oridir): datatype_list=['label_train','unlabel_train'] with open(out_file,'w') as fw: for datatype in datatype_list: datapath = os.path.join(oridir,datatype+'.json') with open(datapath,'r') as f: data = [json.loads(i) for i in f.readlines()] for row in data: # print(json.dumps(row['input'].strip('"'), ensure_ascii=False),file=fw) print(row['input'.strip('"')], file=fw)
null
165,044
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * from pretrain import * from torch.utils.data import DataLoader def create_dataloader_for_pretrain(mix_train_file, tokz, model, args): data_files = {} data_files['train'] = mix_train_file extension = mix_train_file.split(".")[-1] if extension == 'txt': extension = 'text' datasets = load_dataset(extension, data_files=data_files) train_dataset = datasets['train'] max_seq_length=128 def tokenize_function(examples): return tokz(examples[text_column_name], return_attention_mask=False) column_names = train_dataset.column_names text_column_name = "text" if "text" in column_names else column_names[0] tokenized_datasets = train_dataset.map( tokenize_function, batched=True, remove_columns=column_names, load_from_cache_file=True, ) # T5-like span masked language modeling will fuse consecutively masked tokens to a single sentinel token. # To ensure that the input length is `max_seq_length`, we need to increase the maximum length # according to `mlm_probability` and `mean_noise_span_length`. We can also define the label length accordingly. expanded_inputs_length, targets_length = compute_input_and_target_lengths( inputs_length=max_seq_length, noise_density=0.15, mean_noise_span_length=3.0, ) data_collator = DataCollatorForT5MLM( tokenizer=tokz, noise_density=0.15, mean_noise_span_length=3.0, input_length=max_seq_length, target_length=targets_length, pad_token_id=model.config.pad_token_id, decoder_start_token_id=model.config.decoder_start_token_id, ) # Main data processing function that will concatenate all texts from our dataset and generate chunks of expanded_inputs_length. def group_texts(examples): # Concatenate all texts. concatenated_examples = { k: list(chain(*examples[k])) for k in examples.keys()} total_length = len(concatenated_examples[list(examples.keys())[0]]) # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can # customize this part to your needs. if total_length >= expanded_inputs_length: total_length = ( total_length // expanded_inputs_length) * expanded_inputs_length # Split by chunks of max_len. result = { k: [t[i: i + expanded_inputs_length] for i in range(0, total_length, expanded_inputs_length)] for k, t in concatenated_examples.items() } return result # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value # might be slower to preprocess. # # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map train_dataset = tokenized_datasets.map( group_texts, batched=True, load_from_cache_file=True, ) train_sampler = torch.utils.data.RandomSampler(train_dataset) mix_dataloader = DataLoader(train_dataset, batch_size=16, sampler=train_sampler, num_workers=args.num_workers, pin_memory=True, collate_fn=data_collator) return mix_dataloader
null
165,045
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * from pretrain import * from torch.utils.data import DataLoader max_input_length_dict = { 'woz.en': 128, 'sst': 128, 'srl': 128, 'wikisql': 300, 'squad':512, 'ag':128, 'yelp':256, 'yahoo':128, 'dbpedia':128, 'amazon':200 } args = parse_args() class LBDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, max_input_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path self.max_ans_len = args.max_ans_len self.special_token_ids = special_token_ids self.task_name = task_name self.max_input_len = max_input_length_dict[self.task_name] with open(data_path, "r", encoding='utf-8') as f: ori_data = [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) if task_name in ['wikisql','woz.en'] and 'test' in self.data_path: with open(os.path.join(args.data_dir, task_name, 'answers.json'),'r') as f: self.answers = json.load(f) print(f'Number of answers is {len(self.answers)}') if task_name in ['wikisql', 'squad'] and 'test' in self.data_path: self.targets = [] for i in ori_data: self.targets.append(i['output']) def get_answer(self, target): # get answer text from intent # replace - and _ to make the text seems more natural if type(target) == list: target = target[0] if self.task_name == 'wikisql': ans = target else: ans = target.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): if self.task_name in ['wikisql','woz.en','squad','srl']: text = example['input'] question = example['question'] text_wo_question = example['text_wo_question'] else: text = example['input'].replace('-',' ').replace('_',' ').replace('\\',' ') question = example['question'].replace('-',' ').replace('_',' ').replace('\\',' ') text_wo_question = example['text_wo_question'].replace('-',' ').replace('_',' ').replace('\\',' ') ans = self.get_answer(example['output']) if self.task_name in ['woz.en','squad','wikisql'] and 'test' in self.data_path: ans_list = example['output'] return [(text, ans, question, text_wo_question, example['id'], ans_list)] return [(text, ans, question, text_wo_question)] def per_tokenization(self, task_name, d): # print(d,flush=True) # input_text, ans_text = d if self.task_name in ['woz.en','squad','wikisql'] and 'test' in self.data_path: input_text, ans_text, question, text_wo_question, idx, ans_list = d else: input_text, ans_text, question, text_wo_question = d raw_text = text_wo_question input_sen = task_name+':' + raw_text + '<QUES>' + question context_sen = input_sen + '<ANS>' # for evaluation ans_sen = ans_text # all_sen = context_sen + ans_sen all_sen = raw_text + '<QUES>' res_dict = { 'all_sen': all_sen, 'input_sen': input_sen, 'context_sen': context_sen, 'ans_sen': ans_sen, 'question': question, 'raw_text': raw_text } if self.task_name in ['woz.en','squad','wikisql'] and 'test' in self.data_path: res_dict['id'] = idx res_dict['ans_list'] = ans_list return res_dict def data_tokenization(self, task_name, data): # print('data',data[:10],flush=True) data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] def sort_by_index(self): self.data.sort(key=lambda x: x['id']) def get_indices(self): return [d['id'] for d in self.data] class ULBDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, max_input_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path self.max_ans_len = args.max_ans_len self.special_token_ids = special_token_ids self.task_name = task_name self.max_input_len = max_input_length_dict[self.task_name] with open(data_path, "r", encoding='utf-8') as f: # data = [json.loads(i) for i in f.readlines()] # data = [self.parse_example(i) for i in data] # [utter, label] ori_data = [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) if task_name in ['wikisql','woz.en'] and 'test' in self.data_path: with open(os.path.join(args.data_dir, task_name, 'answers.json'),'r') as f: self.answers = json.load(f) def get_answer(self, target): # get answer text from intent if type(target) == list: target = target[0] if self.task_name == 'wikisql': ans = target else: ans = target.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): if self.task_name in ['wikisql','woz.en','squad','srl']: text = example['input'] question = example['question'] text_wo_question = example['text_wo_question'] else: text = example['input'].replace('-',' ').replace('_',' ').replace('\\',' ') question = example['question'].replace('-',' ').replace('_',' ').replace('\\',' ') text_wo_question = example['text_wo_question'].replace('-',' ').replace('_',' ').replace('\\',' ') ans = self.get_answer(example['output']) return [(text, ans, question, text_wo_question)] def per_tokenization(self, task_name, d): input_text, ans_text, question, text_wo_question = d raw_text = text_wo_question input_sen = task_name+':' + raw_text + '<QUES>' + question context_sen = input_sen + '<ANS>' # for evaluation ans_sen = ans_text # all_sen = context_sen + ans_sen all_sen = raw_text + '<QUES>' return { 'all_sen': all_sen, 'input_sen': input_sen, 'context_sen': context_sen, 'ans_sen': ans_sen, 'question': question, 'raw_text': raw_text } def data_tokenization(self, task_name, data): data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] if args.data_type == 'intent': TASK2INFO = { "banking": { "dataset_class": LBDataset, "dataset_folder": "banking", "task_type": "CLS", }, "clinc": { "dataset_class": LBDataset, "dataset_folder": "clinc", "task_type": "CLS", }, "hwu": { "dataset_class": LBDataset, "dataset_folder": "hwu", "task_type": "CLS", }, "atis": { "dataset_class": LBDataset, "dataset_folder": "atis", "task_type": "CLS", }, "tod": { "dataset_class": LBDataset, "dataset_folder": "FB_TOD_SF", "task_type": "CLS", }, "snips": { "dataset_class": LBDataset, "dataset_folder": "snips", "task_type": "CLS", }, "top_split1": { "dataset_class": LBDataset, "dataset_folder": "top_split1", "task_type": "CLS", }, "top_split2": { "dataset_class": LBDataset, "dataset_folder": "top_split2", "task_type": "CLS", }, "top_split3": { "dataset_class": LBDataset, "dataset_folder": "top_split3", "task_type": "CLS", } } elif args.data_type =='slot': TASK2INFO = { "dstc8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "dstc8", "task_type": "SlotTagging", }, "restaurant8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "restaurant8", "task_type": "SlotTagging", }, "atis": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "atis", "task_type": "SlotTagging", }, "mit_movie_eng": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_eng", "task_type": "SlotTagging", }, "mit_movie_trivia": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_trivia", "task_type": "SlotTagging", }, "mit_restaurant": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_restaurant", "task_type": "SlotTagging", }, "snips": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "snips", "task_type": "SlotTagging", } } elif args.data_type =='decanlp' or args.data_type == 'tc' or args.data_type == 'mix': TASK2INFO = { "ag": { "dataset_class": LBDataset, "dataset_folder": "ag", "task_type": "tc", }, 'dbpedia':{ 'dataset_class':LBDataset, 'dataset_folder':'dbpedia', 'task_type':'tc', }, 'yelp':{ 'dataset_class':LBDataset, 'dataset_folder':'yelp', 'task_type':'tc', }, 'yahoo':{ 'dataset_class':LBDataset, 'dataset_folder':'yahoo', 'task_type':'tc', }, 'snips':{ 'dataset_class':LBDataset, 'dataset_folder':'snips', 'task_type':'tc', }, 'amazon':{ 'dataset_class':LBDataset, 'dataset_folder':'amazon', 'task_type':'tc', }, 'woz.en':{ 'dataset_class':LBDataset, 'dataset_folder':'woz.en', 'task_type':'decanlp', }, 'squad':{ 'dataset_class':LBDataset, 'dataset_folder':'squad', 'task_type':'decanlp', }, 'sst':{ 'dataset_class':LBDataset, 'dataset_folder':'sst', 'task_type':'decanlp', }, 'srl':{ 'dataset_class':LBDataset, 'dataset_folder':'srl', 'task_type':'decanlp', }, 'wikisql':{ 'dataset_class':LBDataset, 'dataset_folder':'wikisql', 'task_type':'decanlp', } } def get_datasets(path, tasks, tokz, max_input_len=100, special_token_ids=None): res = {} for task in tasks: res[task] = {} info = TASK2INFO[task] if args.unlabel_ratio == -1: num_unlabel = 2000 else: num_unlabel = args.num_label * args.unlabel_ratio max_input_len = max_input_length_dict[task] # ! Remember to restore this. res[task]['label_train'] = LBDataset( task, tokz, os.path.join(path, info['dataset_folder'], 'label_train.json'), max_input_len=max_input_len, special_token_ids=special_token_ids) if args.use_unlabel: res[task]['unlabel_train'] = ULBDataset( task, tokz, os.path.join(path, info['dataset_folder'], str(num_unlabel)+'_unlabel_train.json'), max_input_len=max_input_len, special_token_ids=special_token_ids) res[task]['val'] = TASK2INFO[task]['dataset_class'](task, tokz, os.path.join(path, info['dataset_folder'], 'test.json'), max_input_len=max_input_len, special_token_ids=special_token_ids) res[task]['test'] = TASK2INFO[task]['dataset_class'](task, tokz, os.path.join(path, info['dataset_folder'], 'test.json'), max_input_len=max_input_len, special_token_ids=special_token_ids) return res
null
165,046
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def padding_convert(text_list, eos): tt_list = [] for text in text_list: if eos in text: eos_indexs = [i for i, x in enumerate(text) if x == eos] # print('eos index', eos_indexs,flush=True) if len(eos_indexs) > 1: text = text[:eos_indexs[1]] tt_list.append(text) tt_lens = [len(i) for i in tt_list] tt_lens = torch.tensor(tt_lens, dtype=torch.long).to('cuda') tt_pad = torch.tensor([pad_seq(i, eos, max(tt_lens), pad_left=True) for i in tt_list], dtype=torch.long).to('cuda') return tt_pad, tt_lens
null
165,047
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F t5tokz = T5Tokenizer.from_pretrained('t5-base') def gen_pseudo_data(model, task, tokz, max_output_len=90, batch_size=4, target_count=100, output_file=None, args=None, question=None): device = 'cuda' task_prefix = task+':' task_prefix_id = tokz.encode(task_prefix)[0] # task_prefix_id = tokz.encode('Task:')[0] input_tokens = torch.full((batch_size,1), task_prefix_id).cuda() adapter_name = task.replace('.','_') model.set_active_adapters(adapter_name) model = model.cuda() pseudo_list = [] utter_set = set() eos_token = tokz.eos_token_id pad_token = tokz.pad_token_id # bad_words = tokz.additional_special_tokens # bad_words_ids = [[badid] for badid in tokz.additional_special_tokens_ids] bad_words = t5tokz.additional_special_tokens bad_words_ids = tokz(bad_words, add_special_tokens=False).input_ids if output_file is None: raise ValueError("Pseudo output file is not specified.") if output_file is not None: if not os.path.isdir(os.path.dirname(output_file)): os.makedirs(os.path.dirname(output_file), exist_ok=True) # * Generate pseudo samples. input_set = set() while len(pseudo_list) < target_count: once_target_count = min(32, target_count) with torch.no_grad(): model.eval() outputs = model.generate(input_ids=input_tokens, do_sample=True, eos_token_id=eos_token, pad_token_id=pad_token, output_scores=True, return_dict_in_generate=True, early_stopping=True, max_length=min(max_output_len, 256), num_return_sequences=once_target_count, bad_words_ids=bad_words_ids) output_seq = outputs.sequences output_list = output_seq.tolist() # print('output_list len',len(output_list), flush=True) # print('batch size',batch_size, flush=True) for i in range(batch_size): # print("Test what's the first token:",output_list[i],flush=True) if len(output_list[i])<=1: continue output_id = output_list[i][1:] # print(output_id, flush=True) if eos_token in output_id: output_id = output_id[:output_id.index(eos_token)] output = tokz.decode(output_id, skip_special_tokens=True) #! Not contain '<QUES>' token # print(output, flush=True) if len(output)>=2: input_sen = output.strip() context_sen = task_prefix + input_sen + '<QUES>' + question + '<ANS>' input_ids = torch.tensor([tokz.encode(context_sen)]).cuda() ans_id = model.generate(input_ids=input_ids, do_sample=False, eos_token_id=eos_token, pad_token_id=pad_token, bad_words_ids=bad_words_ids) output_sen = tokz.decode(ans_id[0], skip_special_tokens=True) else: input_sen, output_sen = None, None if input_sen and output_sen: print('INPUT::',input_sen, '===> OUTPUT::', output_sen, flush=True) if input_sen not in input_set: input_set.add(input_sen) # avoid duplicate inputs. pseudo_list.append([input_sen, output_sen, question]) pseudo_list = pseudo_list[:target_count] with open(output_file, 'w', encoding='utf8') as f: for input, output, _ in pseudo_list: print(json.dumps({'input': input, 'output': output}, ensure_ascii=False), file=f) model.train() return pseudo_list
null
165,048
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def get_all_priors(model, tokz, args): def pseudo_prompt(task): return f"In the \"{task}\" task, which intent category best describes: \"" all_prior_info = {} for task in args.tasks: prompt_id = [tokz.bos_token_id]+tokz.encode(pseudo_prompt(task))+[tokz.eos_token_id] prompt_id = torch.LongTensor(prompt_id).to('cuda') prior_out = model.encoder(input_ids=prompt_id) prior_emb, _ = model.avg_attn(prior_out[0]) prior_mean, prior_logvar = model.prior_mean(prior_emb), model.prior_logvar(prior_emb) all_prior_info[task]=(prior_mean, prior_logvar) return all_prior_info
null
165,049
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def get_nearest_task(model, tokz, sample, all_prior_info, args): def pseudo_prompt(task): return f"In the \"{task}\" task, which intent category best describes: \"" all_posteriors={} batch_size = len(sample['utter_id']) for task in args.tasks: prompt_id = [tokz.bos_token_id]+tokz.encode(pseudo_prompt(task)) bt_prompt_id = torch.LongTensor([prompt_id for _ in range(batch_size)]).to('cuda') bt_px_id = torch.cat((bt_prompt_id,sample['utter_id'].to('cuda')),dim=1) bt_px_id = bt_px_id.to('cuda') if len(bt_px_id)!=batch_size: raise ValueError('Tensor concatenate is wrong.') # px_id = tokz.encode(prompt_id+sample['utter_id'].tolist()) # prompt_id = torch.LongTensor(prompt_id).to('cuda') # px_id = torch.LongTensor(px_id).to('cuda') post_out = model.encoder(input_ids=bt_px_id) post_emb, _ = model.avg_attn(post_out[0]) post_mean, post_logvar = model.post_mean(post_emb), model.post_logvar(post_emb) all_posteriors[task]=(post_mean, post_logvar) min_kl = 1e10 res_task = args.tasks[0] all_kl_dist = [] for task in all_prior_info.keys(): prior_mean, prior_logvar = all_prior_info[task] post_mean, post_logvar = all_posteriors[task] kl_dist = kl_divergence(post_mean, post_logvar, prior_mean, prior_logvar) all_kl_dist.append(kl_dist) if kl_dist < min_kl: min_kl = kl_dist res_task = task # print(all_kl_dist,flush=True) return res_task
null
165,050
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def get_pred_context(tokz, pred_task_name, gt_task_name, sample): new_list = [] for ss in sample['context_id'].tolist(): # print('1',len(ss),flush=True) context = tokz.decode(ss) # print('1',context,flush=True) # new_context = text.replace(f'In the "{gt_task_name}" task, which intent category best describes: "', pred_task_name).strip() new_context = re.sub(gt_task_name,pred_task_name,context) # print('2',new_context,flush=True) new_context_id = tokz.encode(new_context) # print('2',len(new_context_id),flush=True) new_list.append(new_context_id) # if len(new_context_id)!=len(new_list[0]): # raise ValueError('Lengths are not match in this batch.') context_lens = [len(i) for i in new_list] context_mask = torch.ByteTensor([[1] * context_lens[i] + [0] * (max(context_lens)-context_lens[i]) for i in range(len(context_lens))]) new_res = torch.tensor([pad_seq(i, tokz.eos_token_id, max(context_lens), pad_left=True) for i in new_list], dtype=torch.long).to('cuda') new_lens = torch.tensor(context_lens,dtype=torch.long).to('cuda') # new_res = torch.LongTensor(new_list).to('cuda',non_blocking=True) return new_res, new_lens
null
165,051
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def get_answer(tokz, model, example, example_mask, max_ans_len, args=None, is_eval=False): temperature = args.temperature model.eval() device = 'cuda' eos_token = tokz.eos_token_id pad_token = tokz.pad_token_id bad_words = t5tokz.additional_special_tokens bad_words_ids = tokz(bad_words, add_special_tokens=False).input_ids # bad_words_ids = [[badid] for badid in tokz.additional_special_tokens_ids] # * Get sequence outputs. # print('Begin generating answers.',flush=True) outputs = model.generate(input_ids=example, attention_mask=example_mask, do_sample=False, eos_token_id=eos_token, pad_token_id=pad_token, output_scores=True, return_dict_in_generate=True, early_stopping=True, max_length=max_ans_len, bad_words_ids=bad_words_ids) # print(outputs,flush=True) output_seq = outputs.sequences output_scores = outputs.scores if not is_eval: output_scores = torch.stack(list(output_scores), dim=0) output_scores = output_scores.permute(1, 0, 2) # [80,10,50258] # print(f'output_scores {output_scores.shape}',flush=True) # print(f'output_seq {output_seq.shape}',flush=True) # print('output_seq',output_seq.shape, 'output_scores',len(output_scores), output_scores[0].shape, flush=True) # generate one: example [16, 29], out_seq [16, 39], out_score[0] [16, 50258], out_score [max_length=input_ids.shape[-1], batch_size, vocab_size] tuple # generate many: out_seq [16, 5, 29], out_scores [16, 5, 10, 50258] # return output_seq[:,example.shape[1]:], output_scores return output_seq, output_scores def get_pseudo_labels_for_all(tokz, model, dataloader, task, sampling=False, args=None): out_dir = os.path.join(args.output_dir, f'{task}_unlabel_pseudo.json') out_dir_data = [] data_path = get_unlabel_data(args.data_dir, task) with open(data_path, 'r', encoding='utf-8') as f: all_data = [json.loads(i) for i in f.readlines()] with torch.no_grad(): model.eval() pred_ans_all = [] input_all = [] for i, data in enumerate(dataloader): sample = data['context_id'].to('cuda') sample_lens = data['context_lens'].to('cuda') pred_ans = get_answer(tokz, model, sample, sample_lens, max_ans_len=args.max_ans_len, args=args) pred_ans_all.append(pred_ans) pred_ans_all = communicate_tensor(pred_ans_all, pad_token=tokz.eos_token_id).tolist() for i in range(len(pred_ans_all)): res = {} res['userInput'] = {} res['userInput']['text'] = all_data[i]['userInput']['text'] res['intent'] = tokz.decode(cut_eos(pred_ans_all[i], tokz.eos_token_id)) out_dir_data.append(res) with open(out_dir, 'w', encoding='utf-8') as f: for res in out_dir_data: print(json.dumps(res), file=f) model.train() return None
null
165,052
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def get_answer(tokz, model, example, example_mask, max_ans_len, args=None, is_eval=False): temperature = args.temperature model.eval() device = 'cuda' eos_token = tokz.eos_token_id pad_token = tokz.pad_token_id bad_words = t5tokz.additional_special_tokens bad_words_ids = tokz(bad_words, add_special_tokens=False).input_ids # bad_words_ids = [[badid] for badid in tokz.additional_special_tokens_ids] # * Get sequence outputs. # print('Begin generating answers.',flush=True) outputs = model.generate(input_ids=example, attention_mask=example_mask, do_sample=False, eos_token_id=eos_token, pad_token_id=pad_token, output_scores=True, return_dict_in_generate=True, early_stopping=True, max_length=max_ans_len, bad_words_ids=bad_words_ids) # print(outputs,flush=True) output_seq = outputs.sequences output_scores = outputs.scores if not is_eval: output_scores = torch.stack(list(output_scores), dim=0) output_scores = output_scores.permute(1, 0, 2) # [80,10,50258] # print(f'output_scores {output_scores.shape}',flush=True) # print(f'output_seq {output_seq.shape}',flush=True) # print('output_seq',output_seq.shape, 'output_scores',len(output_scores), output_scores[0].shape, flush=True) # generate one: example [16, 29], out_seq [16, 39], out_score[0] [16, 50258], out_score [max_length=input_ids.shape[-1], batch_size, vocab_size] tuple # generate many: out_seq [16, 5, 29], out_scores [16, 5, 10, 50258] # return output_seq[:,example.shape[1]:], output_scores return output_seq, output_scores def textid_decode(text, eos, tokz, contain_eos=False): if eos in text: if contain_eos: idx = text.index(eos) text = text[:idx] else: text = text[:text.index(eos)] text_id = text len_text = len(text) text = tokz.decode(text).strip() return text, len_text, text_id def compute_ppl(out_seqs, out_scores, tokz): # * Get answer lens. ans_lens = [] max_seq_len = out_seqs.size(-1) out_seqs_list = out_seqs.tolist() all_ans_id = [] for i in out_seqs_list: _, seq_len, seq_id = textid_decode(i, tokz.eos_token_id, tokz, contain_eos=True) ans_lens.append(seq_len) # Contain one EOS token. all_ans_id.append(seq_id) btz = out_seqs.size(0) ans_scores = out_scores # may get -inf # print(f'answer scores max {torch.max(ans_scores)} min {torch.min(ans_scores)}') # for j in range(btz): # score_per_sample = [] # for l in range(max_seq_len): # score_per_sample.append(out_scores[l][j].tolist()) # ans_scores.append(score_per_sample) # ans_scores = torch.tensor(ans_scores) # ans_scores = out_scores.permute(1, 0, 2) log_softmax = nn.LogSoftmax(dim=-1) # for vocab_size log_soft = log_softmax(ans_scores) select_log_soft = [] log_soft_flatten = log_soft.view(-1, ans_scores.shape[-1]).to('cuda') # log_soft_flatten = log_soft.view(-1, len(tokz)).to('cuda') out_seq_flatten = out_seqs.contiguous().view(-1).to('cuda') select_log_soft = log_soft_flatten[torch.arange(log_soft_flatten.shape[0]),out_seq_flatten] select_log_soft = select_log_soft.view(btz, max_seq_len) # ans_scores:[16, 10, 50258] log_soft [16, 10, 50258] select_log_soft [16, 10] ans_score_mask = [[1]* ans_lens[i]+[0]*(max_seq_len-ans_lens[i]) for i in range(btz)] ans_score_mask = torch.tensor(ans_score_mask).to('cuda') neg_loglh = torch.sum(-select_log_soft * ans_score_mask, dim=1) / torch.sum(ans_score_mask, dim=1) ppl_batch = torch.exp(neg_loglh).to('cuda') return all_ans_id, ppl_batch def get_pseudo_labels_per_batch(tokz, model, data, sampling=False, args=None): with torch.no_grad(): model.eval() context = data['context_id'].to('cuda') context_lens = data['context_lens'].to('cuda') out_seqs, out_scores = get_answer(tokz, model, context, context_lens, max_ans_len=args.max_ans_len, args=args) # print('out_seqs',out_seqs,'out_scores',out_scores,flush=True) # Get all lens. eos_token = tokz.eos_token_id ans_lens = [] max_seq_len = out_seqs.size(-1) btz = out_seqs.size(0) out_seqs_list = out_seqs.tolist() # print(out_seqs_list,flush=True) all_ans_id = [] for i in out_seqs_list: # print(i,flush=True) _, seq_len, seq_id = textid_decode(i, eos_token, tokz, contain_eos=True) ans_lens.append(seq_len) # Contain one EOS token. all_ans_id.append(seq_id) # print('ans len', ans_lens, flush=True) # print('max_seq_len',max_seq_len, 'max(all_lens)',max(ans_lens), flush=True) # ans_scores = [[out_scores[context_lens[i]:all_lens[i]]] for i in range(btz)] # * Compute PPL. ppl_batch = compute_ppl(out_seqs, out_scores, tokz) # * Prepare batch for training. spe_token_id = tokz.convert_tokens_to_ids('ANS:') batch_list = [] for i in range(btz): info = {} input_id = data['input_id'][i][:data['input_lens'][i]] input_id = input_id.tolist() info['input_id'] = input_id info['ans_id'] = all_ans_id[i] + [tokz.eos_token_id] info['context_id'] = input_id + [spe_token_id] info['all_id'] = info['context_id'] + all_ans_id[i] + [tokz.eos_token_id] batch_list.append(info) # Print some pseudo samples. if i==0: print('-'*10, 'Unlabeled sample with pseudo labels:', flush=True) print('input:', tokz.decode(info['input_id']), flush=True) print('all:',tokz.decode(info['all_id']), flush=True) print('-'*20,flush=True) # print(batch_list[0],flush=True) padbatch = PadBatchSeq() batch = padbatch(batch_list) print('ppl',ppl_batch.tolist(),flush=True) return ppl_batch, batch
null
165,053
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def textid_decode(text, eos, tokz, contain_eos=False): if eos in text: if contain_eos: idx = text.index(eos) text = text[:idx] else: text = text[:text.index(eos)] text_id = text len_text = len(text) text = tokz.decode(text).strip() return text, len_text, text_id def old_compute_ppl(out_seqs, out_scores, tokz): # * Get answer lens. ans_lens = [] max_seq_len = out_seqs.size(-1) out_seqs_list = out_seqs.tolist() all_ans_id = [] for i in out_seqs_list: _, seq_len, seq_id = textid_decode(i, tokz.eos_token_id, tokz, contain_eos=True) ans_lens.append(seq_len) # Contain one EOS token. all_ans_id.append(seq_id) btz = out_seqs.size(0) ans_scores = out_scores # for j in range(btz): # score_per_sample = [] # for l in range(max_seq_len): # score_per_sample.append(out_scores[l][j].tolist()) # ans_scores.append(score_per_sample) # ans_scores = torch.tensor(ans_scores) # ans_scores = out_scores.permute(1, 0, 2) log_softmax = nn.LogSoftmax(dim=-1) # for vocab_size log_soft = log_softmax(ans_scores) select_log_soft = [] log_soft_flatten = log_soft.view(-1, len(tokz)).to('cuda') out_seq_flatten = out_seqs.contiguous().view(-1).to('cuda') select_log_soft = log_soft_flatten[torch.arange(log_soft_flatten.shape[0]),out_seq_flatten] select_log_soft = select_log_soft.view(btz, max_seq_len) # ans_scores:[16, 10, 50258] log_soft [16, 10, 50258] select_log_soft [16, 10] ans_score_mask = [[1]* ans_lens[i]+[0]*(max_seq_len-ans_lens[i]) for i in range(btz)] ans_score_mask = torch.tensor(ans_score_mask).to('cuda') neg_loglh = torch.sum(-select_log_soft * ans_score_mask, dim=1) / torch.sum(ans_score_mask, dim=1) ppl_batch = torch.exp(neg_loglh).to('cuda') return all_ans_id, ppl_batch
null
165,054
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def map_to_same_length(seq_list, tokz): max_seq_len = 10 eos_token = tokz.eos_token_id new_seq_list = [] for i in range(len(seq_list)): if len(seq_list[i]) < max_seq_len: new_seq_list.append(seq_list[i]+[eos_token] * (max_seq_len-len(seq_list[i]))) return new_seq_list
null
165,055
from transformers import T5Tokenizer, T5Config import logging import random import torch import numpy as np from torch.utils.data import DataLoader import json from tqdm import tqdm from sklearn.metrics import accuracy_score, f1_score import torch.distributed as dist import os import time import gc import json import pickle import argparse import math import re import torch.nn as nn import torch.utils.data as data import torch.distributed as dist import torch.multiprocessing as mp import copy import torch.nn.functional as F def get_answer(tokz, model, example, example_mask, max_ans_len, args=None, is_eval=False): temperature = args.temperature model.eval() device = 'cuda' eos_token = tokz.eos_token_id pad_token = tokz.pad_token_id bad_words = t5tokz.additional_special_tokens bad_words_ids = tokz(bad_words, add_special_tokens=False).input_ids # bad_words_ids = [[badid] for badid in tokz.additional_special_tokens_ids] # * Get sequence outputs. # print('Begin generating answers.',flush=True) outputs = model.generate(input_ids=example, attention_mask=example_mask, do_sample=False, eos_token_id=eos_token, pad_token_id=pad_token, output_scores=True, return_dict_in_generate=True, early_stopping=True, max_length=max_ans_len, bad_words_ids=bad_words_ids) # print(outputs,flush=True) output_seq = outputs.sequences output_scores = outputs.scores if not is_eval: output_scores = torch.stack(list(output_scores), dim=0) output_scores = output_scores.permute(1, 0, 2) # [80,10,50258] # print(f'output_scores {output_scores.shape}',flush=True) # print(f'output_seq {output_seq.shape}',flush=True) # print('output_seq',output_seq.shape, 'output_scores',len(output_scores), output_scores[0].shape, flush=True) # generate one: example [16, 29], out_seq [16, 39], out_score[0] [16, 50258], out_score [max_length=input_ids.shape[-1], batch_size, vocab_size] tuple # generate many: out_seq [16, 5, 29], out_scores [16, 5, 10, 50258] # return output_seq[:,example.shape[1]:], output_scores return output_seq, output_scores def compute_ppl(out_seqs, out_scores, tokz): # * Get answer lens. ans_lens = [] max_seq_len = out_seqs.size(-1) out_seqs_list = out_seqs.tolist() all_ans_id = [] for i in out_seqs_list: _, seq_len, seq_id = textid_decode(i, tokz.eos_token_id, tokz, contain_eos=True) ans_lens.append(seq_len) # Contain one EOS token. all_ans_id.append(seq_id) btz = out_seqs.size(0) ans_scores = out_scores # may get -inf # print(f'answer scores max {torch.max(ans_scores)} min {torch.min(ans_scores)}') # for j in range(btz): # score_per_sample = [] # for l in range(max_seq_len): # score_per_sample.append(out_scores[l][j].tolist()) # ans_scores.append(score_per_sample) # ans_scores = torch.tensor(ans_scores) # ans_scores = out_scores.permute(1, 0, 2) log_softmax = nn.LogSoftmax(dim=-1) # for vocab_size log_soft = log_softmax(ans_scores) select_log_soft = [] log_soft_flatten = log_soft.view(-1, ans_scores.shape[-1]).to('cuda') # log_soft_flatten = log_soft.view(-1, len(tokz)).to('cuda') out_seq_flatten = out_seqs.contiguous().view(-1).to('cuda') select_log_soft = log_soft_flatten[torch.arange(log_soft_flatten.shape[0]),out_seq_flatten] select_log_soft = select_log_soft.view(btz, max_seq_len) # ans_scores:[16, 10, 50258] log_soft [16, 10, 50258] select_log_soft [16, 10] ans_score_mask = [[1]* ans_lens[i]+[0]*(max_seq_len-ans_lens[i]) for i in range(btz)] ans_score_mask = torch.tensor(ans_score_mask).to('cuda') neg_loglh = torch.sum(-select_log_soft * ans_score_mask, dim=1) / torch.sum(ans_score_mask, dim=1) ppl_batch = torch.exp(neg_loglh).to('cuda') return all_ans_id, ppl_batch def get_pseudo_labels_per_batch_with_sampling(tokz, model, data, args=None): eos_token = tokz.eos_token_id with torch.no_grad(): model.eval() context = data['context_id'].to('cuda') context_lens = data['context_lens'].to('cuda') out_seqs, out_scores = get_answer(tokz, model, context, context_lens, max_ans_len=args.max_ans_len, args=args) # generate many: out_seq [80, 29], out_scores [80, 10, 50258] btz = args.train_batch_size all_seqs = [] all_scores = [] # Save batch_size number. all_ans_id = [] all_ppl = [] all_res = [] ans_id, ppl = compute_ppl(out_seqs, out_scores, tokz) # output_seq = output_seq.split(args.pl_sample_num) # output_seq = torch.stack(output_seq) # output_scores = output_scores.split(args.pl_sample_num) # output_scores = torch.stack(output_scores) # out_seq [16, 5, 29], out_scores [16, 5, 10, 50258] ppl = torch.stack(torch.split(ppl, args.pl_sample_num)) # [16, 5] print('ppl shape after split', ppl.shape, flush=True) for i in range(btz): example_ppl = ppl[i,:] # scores shape torch.Size([5, 10, 50258]) seq shape torch.Size([5, 10]) min_idx = torch.argmin(example_ppl) all_ans_id.append(ans_id[min_idx+i*args.pl_sample_num]) all_ppl.append(example_ppl[min_idx]) all_ppl = torch.tensor(all_ppl) # * Prepare batch for training. spe_token_id = tokz.convert_tokens_to_ids('ANS:') batch_list = [] for i in range(btz): info = {} input_id = data['input_id'][i][:data['input_lens'][i]] input_id = input_id.tolist() info['input_id'] = input_id info['ans_id'] = all_ans_id[i] + [tokz.eos_token_id] info['context_id'] = input_id + [spe_token_id] info['all_id'] = info['context_id'] + all_ans_id[i] + [tokz.eos_token_id] batch_list.append(info) # Print some pseudo samples. if i==0: print('-'*10, 'Unlabeled sample with pseudo labels:', flush=True) print('input:', tokz.decode(info['input_id']), flush=True) print('all:',tokz.decode(info['all_id']), flush=True) print('-'*20,flush=True) # print(batch_list[0],flush=True) padbatch = PadBatchSeq() batch = padbatch(batch_list) print('ppl', all_ppl.tolist(),flush=True)
null
165,056
import torch import numpy as np from eda import * import torch.nn as nn from unifymodel.dataset import * def get_neighbors(querys, task_name=None, K=1, memory=None, args=None, questions=None): def create_batch_from_memory(samples, tokz, args, task_name): def create_batch_to_augment_memory(old_task, old_memory, curr_memory, tokz=None, args=None): querys = torch.tensor(old_memory['keys']) questions = old_memory['questions'] neighbors = get_neighbors(querys, task_name=None, K=args.back_kneighbors, memory=curr_memory, args=args, questions=questions) aug_unlabel_batch = create_batch_from_memory(neighbors, tokz, args=args, task_name=old_task) return aug_unlabel_batch
null
165,057
import torch import numpy as np from eda import * import torch.nn as nn from unifymodel.dataset import * def get_sentence_embedding(model, batch, args=None): model.set_active_adapters(None) batch_size = batch['raw_id'].size()[0] input_tokens = batch['raw_id'].cuda() attn_masks = batch['raw_mask'].cuda() outputs = model.transformer.encoder(input_ids=input_tokens, attention_mask=attn_masks, return_dict=True) pooled_emb = outputs.last_hidden_state sen_emb = torch.mean(pooled_emb, dim=1) # (batch_size, 768) # print('sentence emb shape', sen_emb.shape, flush=True) # if args.diff_question: all_questions = [] all_values = [] all_keys = [] for i in range(batch_size): sample_ques = batch['batch_text'][i]['question'] sample_value = batch['batch_text'][i]['raw_text'] all_questions.append(sample_ques) all_values.append(sample_value) # all_keys.append(sen_emb[i].tolist()) all_keys.append(sen_emb[i,:]) # return sen_emb, all_values, all_questions return all_keys, all_values, all_questions def construct_memory(task_name, model, batch, memory=None, args=None): sen_embs, all_values, all_questions = get_sentence_embedding(model, batch, args=args) if memory is None: memory = {} if task_name not in memory: memory[task_name] = {} memory[task_name]['keys'] = [] memory[task_name]['values'] = [] memory[task_name]['questions'] = [] batch_size = len(batch['batch_text']) for i in range(batch_size): key = sen_embs[i].tolist() # value = batch['raw_id'][i] # value = batch['batch_text'][i]['raw_text'] # * Store the raw sentence as the value into the memory. memory[task_name]['keys'].append(key) memory[task_name]['values'].append(value) memory[task_name]['questions'].append(all_questions[i]) return memory
null
165,058
import torch import numpy as np from eda import * import torch.nn as nn from unifymodel.dataset import * def get_old_center_dict(old_memory, prev_tasks, args=None): center_dict = {} for prev_task in prev_tasks: old_keys = old_memory[prev_task]['keys'] # list of list old_keys_tensor = torch.tensor(old_keys).cuda() old_center = torch.mean(old_keys_tensor,dim=0) center_dict[prev_task] = old_center return center_dict
null
165,059
import torch import numpy as np from eda import * import torch.nn as nn from unifymodel.dataset import * def cosine_similarity(v1, m2): # print(v1.shape, m2.shape) if len(m2.shape) == 1 and len(v1.shape) == 1: cos = nn.CosineSimilarity(dim=0) elif len(m2.shape)>1: v1 = v1.unsqueeze(0) cos = nn.CosineSimilarity(dim=1) else: print(f'v1 shape {v1.shape}, m2 shape {m2.shape}',flush=True) score = cos(v1, m2) return score def adapter_selection(prev_tasks, curr_center, old_center_dict, args=None): distance_list = [] for prev_task in prev_tasks: dist = cosine_similarity(curr_center, old_center_dict[prev_task]) distance_list.append(dist) print(f'Distances among centers {distance_list}',flush=True) max_dist = max(distance_list) max_idx = distance_list.index(max_dist) adapter_name = prev_tasks[max_idx] return adapter_name
null
165,060
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * def pad_seq(seq, pad, max_len, pad_left=False): if pad_left: return [pad] * (max_len - len(seq)) + seq else: return seq + [pad] * (max_len - len(seq))
null
165,061
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * def get_unlabel_data(path, task): info = TASK2INFO[task] data_path = os.path.join(path, info['dataset_folder'],'unlabel_train.json') return data_path
null
165,062
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * class LBIDDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, ctx_max_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path self.max_ans_len = 10 self.special_token_ids = special_token_ids with open(data_path, "r", encoding='utf-8') as f: ori_data = [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) def get_answer(self, target): # get answer text from intent # replace - and _ to make the text seems more natural ans = target.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): text = example['input'].replace('-',' ').replace('_',' ').replace('\\',' ') ans = self.get_answer(example['output']) num_aug = 0 # Number of augmented sentences per sample. if not args.meantc or num_aug == 0: return [(text, ans)] else: aug_text_list = eda(text, num_aug=num_aug) res = [(aug_text, ans) for aug_text in aug_text_list] res.append((text, ans)) return res def per_tokenization(self, task_name, d): # print(d,flush=True) input_text, ans_text = d if args.use_task_pmt: # prefix_id = self.tokz.encode(task_name+':') input_sen = task_name+':' + input_text else: # prefix_id = self.tokz.encode('TASK:') input_sen = 'TASK:' + input_text context_sen = input_sen + '<ANS>' all_sen = input_text + '<ANS>' + ans_text ans_sen = ans_text # ans_id = self.tokz.encode(ans_text) # self.max_ans_len = max(self.max_ans_len, len(ans_id) + 1) # return { # 'all_id': self.tokz.encode(all_sen), # 'input_id': self.tokz.encode(input_sen), # 'context_id': self.tokz.encode(context_sen), # 'ans_id': ans_id # } return { 'all_sen': all_sen, 'input_sen': input_sen, 'context_sen': context_sen, 'ans_sen': ans_sen, } def data_tokenization(self, task_name, data): # print('data',data[:10],flush=True) data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] def get_unlabel_dict(path, task, tokz, args): info = TASK2INFO[task] special_token_ids = {'ans_token':tokz.convert_tokens_to_ids('ANS:')} if args.data_type == 'intent': return LBIDDataset(task, tokz, path, args.ctx_max_len, special_token_ids=special_token_ids) else: return None
null
165,063
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * args = parse_args() class LBIDDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, ctx_max_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path self.max_ans_len = 10 self.special_token_ids = special_token_ids with open(data_path, "r", encoding='utf-8') as f: ori_data = [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) def get_answer(self, target): # get answer text from intent # replace - and _ to make the text seems more natural ans = target.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): text = example['input'].replace('-',' ').replace('_',' ').replace('\\',' ') ans = self.get_answer(example['output']) num_aug = 0 # Number of augmented sentences per sample. if not args.meantc or num_aug == 0: return [(text, ans)] else: aug_text_list = eda(text, num_aug=num_aug) res = [(aug_text, ans) for aug_text in aug_text_list] res.append((text, ans)) return res def per_tokenization(self, task_name, d): # print(d,flush=True) input_text, ans_text = d if args.use_task_pmt: # prefix_id = self.tokz.encode(task_name+':') input_sen = task_name+':' + input_text else: # prefix_id = self.tokz.encode('TASK:') input_sen = 'TASK:' + input_text context_sen = input_sen + '<ANS>' all_sen = input_text + '<ANS>' + ans_text ans_sen = ans_text # ans_id = self.tokz.encode(ans_text) # self.max_ans_len = max(self.max_ans_len, len(ans_id) + 1) # return { # 'all_id': self.tokz.encode(all_sen), # 'input_id': self.tokz.encode(input_sen), # 'context_id': self.tokz.encode(context_sen), # 'ans_id': ans_id # } return { 'all_sen': all_sen, 'input_sen': input_sen, 'context_sen': context_sen, 'ans_sen': ans_sen, } def data_tokenization(self, task_name, data): # print('data',data[:10],flush=True) data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] class ULBIDDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, ctx_max_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path self.max_ans_len = 0 self.special_token_ids = special_token_ids with open(data_path, "r", encoding='utf-8') as f: data = [json.loads(i) for i in f.readlines()] data = [self.parse_example(i) for i in data] # [utter, label] self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) def get_answer(self, target): # get answer text from intent # replace - and _ to make the text seems more natural ans = target.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): text = example['input'].replace('-',' ').replace('_',' ').replace('\\',' ') ans = self.get_answer(example['output']) return text, ans def per_tokenization(self, task_name, d): input_text, ans_text = d if args.use_task_pmt: # prefix_id = self.tokz.encode(task_name+':') input_sen = task_name+':' + input_text else: # prefix_id = self.tokz.encode('TASK:') input_sen = 'TASK:' + input_text context_sen = input_sen + '<ANS>' # all_sen = context_sen + ans_text all_sen = input_text + '<ANS>' + ans_text ans_sen = ans_text # ans_id = self.tokz.encode(ans_text) # self.max_ans_len = max(self.max_ans_len, len(ans_id) + 1) # return { # 'all_id': self.tokz.encode(all_sen), # 'input_id': self.tokz.encode(input_sen), # 'context_id': self.tokz.encode(context_sen), # 'ans_id': ans_id # } return { 'all_sen': all_sen, 'input_sen': input_sen, 'context_sen': context_sen, 'ans_sen': ans_sen, } def data_tokenization(self, task_name, data): data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] if args.data_type == 'intent': TASK2INFO = { "banking": { "dataset_class": LBIDDataset, "dataset_folder": "banking", "task_type": "CLS", }, "clinc": { "dataset_class": LBIDDataset, "dataset_folder": "clinc", "task_type": "CLS", }, "hwu": { "dataset_class": LBIDDataset, "dataset_folder": "hwu", "task_type": "CLS", }, "atis": { "dataset_class": LBIDDataset, "dataset_folder": "atis", "task_type": "CLS", }, "tod": { "dataset_class": LBIDDataset, "dataset_folder": "FB_TOD_SF", "task_type": "CLS", }, "snips": { "dataset_class": LBIDDataset, "dataset_folder": "snips", "task_type": "CLS", }, "top_split1": { "dataset_class": LBIDDataset, "dataset_folder": "top_split1", "task_type": "CLS", }, "top_split2": { "dataset_class": LBIDDataset, "dataset_folder": "top_split2", "task_type": "CLS", }, "top_split3": { "dataset_class": LBIDDataset, "dataset_folder": "top_split3", "task_type": "CLS", } } elif args.data_type =='slot': TASK2INFO = { "dstc8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "dstc8", "task_type": "SlotTagging", }, "restaurant8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "restaurant8", "task_type": "SlotTagging", }, "atis": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "atis", "task_type": "SlotTagging", }, "mit_movie_eng": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_eng", "task_type": "SlotTagging", }, "mit_movie_trivia": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_trivia", "task_type": "SlotTagging", }, "mit_restaurant": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_restaurant", "task_type": "SlotTagging", }, "snips": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "snips", "task_type": "SlotTagging", } } elif args.data_type =='tc': TASK2INFO = { "ag": { "dataset_class": LBIDDataset, "dataset_folder": "ag", "task_type": "tc", }, 'dbpedia':{ 'dataset_class':LBIDDataset, 'dataset_folder':'dbpedia', 'task_type':'tc', }, 'yelp':{ 'dataset_class':LBIDDataset, 'dataset_folder':'yelp', 'task_type':'tc', }, 'yahoo':{ 'dataset_class':LBIDDataset, 'dataset_folder':'yahoo', 'task_type':'tc', }, 'snips':{ 'dataset_class':LBIDDataset, 'dataset_folder':'snips', 'task_type':'tc', }, } class AugDataset(LBIDDataset): def __init__(self, task_name, tokz, label_data_path, unlabel_data_path, ctx_max_len=100, special_token_ids=None): self.tokz = tokz self.max_ans_len = 0 self.special_token_ids = special_token_ids with open(label_data_path, "r", encoding='utf-8') as f: ori_data = [json.loads(i) for i in f.readlines()] with open(unlabel_data_path, "r", encoding='utf-8') as f: ori_data += [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) def parse_example(self, example): text = example['userInput']['text'] aug_text_list = eda(text, num_aug=args.num_aug) ans = self.get_answer(example['intent']) res = [(aug_text, ans) for aug_text in aug_text_list] res.append((text, ans)) return res def get_datasets(path, tasks, tokz, ctx_max_len=100, special_token_ids=None): res = {} for task in tasks: res[task] = {} info = TASK2INFO[task] if args.data_type == "intent" or args.data_type == "tc": res[task]['label_train'] = LBIDDataset( task, tokz, os.path.join(path, info['dataset_folder'], 'label_train.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) if args.use_unlabel: res[task]['unlabel_train'] = ULBIDDataset( task, tokz, os.path.join(path, info['dataset_folder'], 'unlabel_train.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) if args.meantc: filename = 'unlabel_' + str(args.num_unlabel) + '_train.json' res[task]['aug_train'] = AugDataset(task, tokz, os.path.join(path, info['dataset_folder'], 'label_train.json'), os.path.join(path, info['dataset_folder'], filename), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) res[task]['val'] = TASK2INFO[task]['dataset_class'](task, tokz, os.path.join(path, info['dataset_folder'], 'test.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) res[task]['test'] = TASK2INFO[task]['dataset_class'](task, tokz, os.path.join(path, info['dataset_folder'], 'test.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) return res
null
165,064
import os import argparse import torch def parse_args(): parser = argparse.ArgumentParser() # * New arguments for semi-supervised continual learning. parser.add_argument('--newmm_size', default=0.2, type=float, help='Different memory size for storing new task unlabeled data.') parser.add_argument('--random_initialization',default=False, type=bool) parser.add_argument('--evaluate_zero_shot',default=False, type=bool) parser.add_argument('--forward_augment',default=False, type=bool, help='Whether apply forward augmentation from old constructed memory.') parser.add_argument('--backward_augment', type=bool, default=False, help='Whether use the current task unlabeled data to augment the old tasks.') parser.add_argument('--select_adapter',default=False, type=bool, help='Whether select the previous adapter for the new task initialization.') parser.add_argument('--similarity_tau',default=0.6, type=float, help='Similarity threshold of cosine for KNN.') parser.add_argument('--back_kneighbors',default=5, type=int, help='Retrieve K nearest neighbors from the current unlabeled memory.') parser.add_argument('--diff_question', type=bool, default=False, help='If true, the dataset has different questions for each sample.') parser.add_argument('--debug_use_unlabel', default=False, type=bool, help='Always use unlabeled data for debugging.') parser.add_argument('--add_confidence_selection', type=bool, default=False, help='Whether add confidence selection for pseudo label.') parser.add_argument('--kneighbors', default=5, type=int, help='Retrieve K nearest neighbors from the memory.') parser.add_argument('--construct_memory',default=False, help='Construct memory for generated pseudo data from old tasks.') parser.add_argument('--aug_neighbors_from_memory', default=False, help='Whether augment retrieved neighbors inputs from memory.') parser.add_argument('--lm_lambda',type=float, default=0.5, help='The coefficient of language modeling loss.') parser.add_argument('--accum_grad_iter', type=bool, default=1, help='Accumulation steps for gradients.') parser.add_argument('--add_label_lm_loss', type=bool, default=False, help='Whether compute lm loss on the labeled inputs.') parser.add_argument('--add_unlabel_lm_loss', type=bool, default=False, help='Whether compute lm loss on the unlabeled inputs.') parser.add_argument('--pretrain_epoch',type=int, default=20, help='Pretrain first for e.g.20 epochs before finetuning.') parser.add_argument('--pretrain_first', type=bool, default=False, help='Whether to perform pretraining before each task finetuning.') parser.add_argument('--test_all', type=bool, default=False, help='Whether evaluate all test data after training the last epoch.') parser.add_argument('--add_pretrain_with_ft', type=bool, default=False, help='Whether add pretraining MLM loss during finetuning.') parser.add_argument('--rdrop', default=False, type=bool, help='Whether use R-drop as the consistency regularization, where dropout is used as model augmentation.') parser.add_argument('--stu_feedback', default=False,type=bool, help='Whether consisder feedback from student to teacher on labeled datasets.') parser.add_argument('--feedback_threshold', default=1e-1, type=float, help='Threshold of student feedback to determine whether to use teacher to teach the student.') parser.add_argument('--dropout_rate',default=0.3, type=float, help='Modify dropout rate for model augmentation with dropout.') parser.add_argument('--freeze_plm', default=False, type=bool, help='Whether to freeze the pretrained LM and only finetuning the added adapters.') parser.add_argument('--max_input_len',default=512, type=int, help='Max number of input tokens.') parser.add_argument('--max_ans_len', default=100, type=int, help='Max number of answer tokens.') parser.add_argument('--use_task_pmt',default=False, type=bool, help='Whether use task specific token as the prefix.') parser.add_argument('--use_ema', default=False, type=bool, help='Use EMA for fixmatch.') parser.add_argument('--fixmatch', default=False, type=bool, help='Use fixmatch to solve semi-supervised learning.') parser.add_argument('--num_label', default=500, type=int, help='Number of labeled data we use.') parser.add_argument('--unlabel_ratio', default=500, type=int, help='Ratio of unlabeled data over labeled data we use.') parser.add_argument('--logit_distance_cost', default=-1, type=float, help='let the student model have two outputs and use an MSE loss between the logits with the given weight (default: only have one output)') parser.add_argument('--test_overfit', default=False, type=bool, help='Test whether the model can overfit on labeled train dataset.') parser.add_argument('--num_aug', type=int, default=3, help='Number of augmented sentences per sample with EDA.') parser.add_argument('--ema_decay', default=0.999, type=float, metavar='ALPHA', help='ema variable decay rate (default: 0.999)') parser.add_argument('--consistency_rampup', type=int, default=30, metavar='EPOCHS', help='length of the consistency loss ramp-up') parser.add_argument('--consistency', type=float, default=100.0, metavar='WEIGHT', help='use consistency loss with given weight (default: None)') parser.add_argument('--meantc', type=bool, default=False, help='Whether to use mean teacher to deal with SSL.') parser.add_argument('--only_update_prompts', type=bool, default=False, help='Only update the prompt tokens params.') parser.add_argument('--pl_sample_num', type=int, default=1, help='Number of sampling for pseudo labeling.') parser.add_argument('--pl_sampling', type=bool, default=False, help='Perform pseudo labeling with sampling for unlabeled data. That means, sample several times for each example, and choose the one with the lowest ppl.') parser.add_argument('--unlabel_amount', type=str, default='1', help='How much unlabeled data used per labeled batch.') parser.add_argument('--ungamma', type=float, default=0.2, help='Weight added to the unlabeled loss.') parser.add_argument('--KD_term', type=float, default=1, help="Control how many teacher model signal is passed to student.") parser.add_argument('--KD_temperature', type=float, default=2.0, help="Temperature used to calculate KD loss.") parser.add_argument('--consist_regularize', type=bool, default=False, help='Whether to use consistency regularization for SSL.') parser.add_argument('--stu_epochs', type=int, default=1, help='Number of epochs for training student model.') parser.add_argument('--noisy_stu', type=bool, default=False, help='Whether to use noisy student self-training framework for SSL, generate pseudo labels for all unlabeled data once.') parser.add_argument('--online_noisy_stu', type=bool, default=False, help='Noisy student self-training framework with PL and CR. Perform pseudo labeling online.') parser.add_argument('--naive_pseudo_labeling', type=bool, default=False, help='Whether to use pseudo-labeling for semi-supervised learning.') parser.add_argument('--only_pseudo_selection', type=bool, default=False, help='Whether to select pseudo labels with high confidence.') parser.add_argument('--pretrain_ul_input', type=bool, default=False, help='Only pretrain the inputs of unlabeled data.') parser.add_argument('--use_unlabel', type=bool, default=False, help='Whether to use unlabeled data during training.') parser.add_argument('--use_infix', type=bool, default=False, help='Whether to use infix prompts.') parser.add_argument('--use_prefix', type=bool, default=False, help='Whether to use prefix prompts.') parser.add_argument('--preseqlen', type=int, default=5, help='Number of prepended prefix tokens.') parser.add_argument('--train_dir',type=str, help='Divide part of labeled data to unlabeled.') parser.add_argument('--data_outdir',type=str, help='Directory of divided labeled and unlabeled data.') parser.add_argument('--pseudo_tau', type=float, default=0.6, help='Threshold to choose pseudo labels with high confidence.') parser.add_argument('--input_aug', type=bool, default=False, help='Whether to use EDA on inputs.') parser.add_argument('--model_aug', type=bool, default=False, help='Whether to use dropout on the model as the data augmentation.') parser.add_argument('--warmup_epoch', type=int, default=10, help='Not use unlabeled data before training certain epochs.') # * Old arguments. parser.add_argument('--data_type',type=str,default='intent') parser.add_argument('--use_memory', default=False, type=bool, help="Whether store the learned latent variables z and other info into the memory.") parser.add_argument('--experiment', type=str) parser.add_argument('--tasks',nargs='+', default=['banking']) parser.add_argument("--data_dir", default="./PLL_DATA/", type=str, help="The path to train/dev/test data files.") # Default parameters are set based on single GPU training parser.add_argument("--output_dir", default="./output/dstc", type=str,help="The output directory where the model checkpoints and predictions will be written.") parser.add_argument("--tb_log_dir", default="./tb_logs/dstc", type=str,help="The tensorboard output directory.") parser.add_argument("--res_dir",default="./res", type=str,help="The path to save scores of experiments.") parser.add_argument("--gene_batch_size", default=16, type=int) # For generation. parser.add_argument('--top_k', type=int, default=100) parser.add_argument('--top_p', type=float, default=0.95) parser.add_argument('--do_train',type=bool, default=True) parser.add_argument('--gen_replay',type=bool, default=False, help='Whether use generative replay to avoid forgetting.') parser.add_argument('--model_path', type=str, help='pretrained model path to local checkpoint') parser.add_argument('--generate_dur_train', type=bool, help='Generate reconstructed input utterances during training with CVAE.') parser.add_argument('--temperature',type=float, default=0.95) parser.add_argument('--pseudo_data_ratio', type=float, default=0.05, help="How many pseudo data to generate for each learned task") parser.add_argument('--lr', type=float, default=1e-4) parser.add_argument('--model_type', type=str, default='cvae', choices=['cvae', 'ae_vae_fusion']) parser.add_argument('--warmup', type=int, default=100, help="Amount of iterations to warmup, then decay. (-1 for no warmup and decay)") parser.add_argument("--train_batch_size", default=16, type=int, help="Batch size per GPU/CPU for training.") parser.add_argument("--eval_batch_size", default=16, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument('--switch-time', type=float, default=0, help="Percentage of iterations to spend on short sequence training.") parser.add_argument('--load', type=str, help='path to load model from') # , default='out/test/' parser.add_argument('--workers', default=1, type=int, metavar='N', help='number of data loading workers') parser.add_argument('--gpu', default=0, type=int) parser.add_argument('--no_gpu', action="store_true") # * KL cost annealing, increase beta from beta_0 to 1 in beta_warmup steps parser.add_argument('--beta_0', default=1.00, type=float) parser.add_argument('--beta_warmup', type=int, default=50000) parser.add_argument('--cycle', type=int, default=1000) parser.add_argument("--filename",type=str,help="Data original file to be preprocessed.") parser.add_argument("--init_model_name_or_path", default="./dir_model/gpt2", type=str, help="Path to init pre-trained model") parser.add_argument("--num_workers", default=1, type=int, help="workers used to process data") parser.add_argument("--local_rank", help='used for distributed training', type=int, default=-1) # Other parameters parser.add_argument("--ctx_max_len", default=128, type=int, help="Maximum input length for the sequence") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.") parser.add_argument("--weight_decay", default=0.00, type=float, help="Weight deay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--num_train_epochs", default=10, type=int, help="Total number of training epochs for each task.") parser.add_argument("--warmup_steps", default=-1, type=int, help="Linear warmup step. Will overwrite warmup_proportion.") parser.add_argument("--warmup_proportion", default=0.1, type=float, help="Linear warmup over warmup_proportion * steps.") parser.add_argument("--nouse_scheduler", action='store_true', help="dont use get_linear_schedule_with_warmup, use unchanged lr") parser.add_argument('--logging_steps', type=int, default=10, help="Log every X updates steps.") parser.add_argument('--save_epochs', type=float, default=2, help="Save checkpoint every X epochs.") parser.add_argument('--eval_steps', type=int, default=20, help="Eval current model every X steps.") parser.add_argument('--eval_times_per_task', type=float, default=10, help="How many times to eval in each task, will overwrite eval_steps.") parser.add_argument('--seed', type=int, default=42, help="Seed for everything") parser.add_argument("--log_eval_res", default=True, help="Whether to log out results in evaluation process") parser.add_argument("--debug", action="store_true", help="Use debug mode") # args = parser. parse_args() args.log_file = os.path.join(args.output_dir, 'log.txt') if args.local_rank in [0, -1]: os.makedirs(args.output_dir, exist_ok=True) os.makedirs(args.tb_log_dir, exist_ok=True) else: while (not os.path.isdir(args.output_dir)) or (not os.path.isdir(args.tb_log_dir)): pass if args.debug: args.logging_steps = 1 torch.manual_seed(0) torch.backends.cudnn.deterministric = True # setup distributed training distributed = (args.local_rank != -1) if distributed: print(args.local_rank) # torch.cuda.set_device(0) torch.cuda.set_device(args.local_rank) args.device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group( backend='nccl', init_method='env://') else: if torch.cuda.is_available(): args.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") else: args.device = torch.device("cpu") args.num_train_epochs = {task: args.num_train_epochs for task in args.tasks} return args
null
165,067
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * class LBIDDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, ctx_max_len=100, special_token_ids=None): def get_answer(self, intent): def parse_example(self, example): def per_tokenization(self, task_name, d): def data_tokenization(self, task_name, data): def __len__(self): def __getitem__(self, index): def get_unlabel_dict(path, task, tokz, args): info = TASK2INFO[task] special_token_ids = {'ans_token':tokz.convert_tokens_to_ids('ANS:')} if args.data_type == 'intent': return LBIDDataset(task, tokz, path, args.ctx_max_len, special_token_ids=special_token_ids) else: return None
null
165,068
import torch import csv import os import re import json import numpy as np from settings import parse_args from eda import * args = parse_args() class LBIDDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, ctx_max_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path # self.CLS_PROMPT = CLSPrompt() # self.SlotTagging_PROMPT = SlotTaggingPrompt() self.max_ans_len = 0 self.special_token_ids = special_token_ids with open(data_path, "r", encoding='utf-8') as f: ori_data = [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) def get_answer(self, intent): # get answer text from intent # replace - and _ to make the text seems more natural ans = intent.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): text = example['userInput']['text'] ans = self.get_answer(example['intent']) num_aug = 0 # Number of augmented sentences per sample. if not args.meantc or num_aug == 0: # print('Run this.', flush=True) return [(text, ans)] else: aug_text_list = eda(text, num_aug=num_aug) res = [(aug_text, ans) for aug_text in aug_text_list] res.append((text, ans)) return res def per_tokenization(self, task_name, d): # print(d,flush=True) input_text, ans_text = d input_id = self.tokz.encode(input_text) ans_id = self.tokz.encode(ans_text) self.max_ans_len = max(self.max_ans_len, len(ans_id) + 1) return { 'all_id': [self.tokz.bos_token_id] + input_id + [self.special_token_ids['ans_token']] + ans_id + [self.tokz.eos_token_id], 'input_id': [self.tokz.bos_token_id] + input_id, 'context_id': [self.tokz.bos_token_id] + input_id + [self.special_token_ids['ans_token']], 'ans_id': ans_id + [self.tokz.eos_token_id]} def data_tokenization(self, task_name, data): # print('data',data[:10],flush=True) data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] class ULBIDDataset(torch.utils.data.Dataset): def __init__(self, task_name, tokz, data_path, ctx_max_len=100, special_token_ids=None): self.tokz = tokz self.data_path = data_path self.max_ans_len = 0 self.special_token_ids = special_token_ids with open(data_path, "r", encoding='utf-8') as f: data = [json.loads(i) for i in f.readlines()] data = [self.parse_example(i) for i in data] # [utter, label] self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) def get_answer(self, intent): # get answer text from intent # replace - and _ to make the text seems more natural ans = intent.replace("-", " ").replace("_", " ") return ans def parse_example(self, example): text = example['userInput']['text'] ans = self.get_answer(example['intent']) return text, ans def per_tokenization(self, task_name, d): input_text, ans_text = d input_id = self.tokz.encode(input_text) ans_id = self.tokz.encode(ans_text) self.max_ans_len = max(self.max_ans_len, len(ans_id) + 1) return { 'all_id': [self.tokz.bos_token_id] + input_id + [self.special_token_ids['ans_token']] + ans_id + [self.tokz.eos_token_id], 'input_id': [self.tokz.bos_token_id] + input_id, # 'input_id': [self.tokz.bos_token_id] + input_id + [self.special_token_ids['ans_token']], 'context_id': [self.tokz.bos_token_id] + input_id + [self.special_token_ids['ans_token']], 'ans_id': ans_id + [self.tokz.eos_token_id]} def data_tokenization(self, task_name, data): data = [self.per_tokenization(task_name, i) for i in data] return data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] if args.data_type == 'intent': TASK2INFO = { "banking": { "dataset_class": LBIDDataset, "dataset_folder": "banking", "task_type": "CLS", }, "clinc": { "dataset_class": LBIDDataset, "dataset_folder": "clinc", "task_type": "CLS", }, "hwu": { "dataset_class": LBIDDataset, "dataset_folder": "hwu", "task_type": "CLS", }, "atis": { "dataset_class": LBIDDataset, "dataset_folder": "atis", "task_type": "CLS", }, "tod": { "dataset_class": LBIDDataset, "dataset_folder": "FB_TOD_SF", "task_type": "CLS", }, "snips": { "dataset_class": LBIDDataset, "dataset_folder": "snips", "task_type": "CLS", }, "top_split1": { "dataset_class": LBIDDataset, "dataset_folder": "top_split1", "task_type": "CLS", }, "top_split2": { "dataset_class": LBIDDataset, "dataset_folder": "top_split2", "task_type": "CLS", }, "top_split3": { "dataset_class": LBIDDataset, "dataset_folder": "top_split3", "task_type": "CLS", } } else: TASK2INFO = { "dstc8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "dstc8", "task_type": "SlotTagging", }, "restaurant8": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "restaurant8", "task_type": "SlotTagging", }, "atis": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "atis", "task_type": "SlotTagging", }, "mit_movie_eng": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_eng", "task_type": "SlotTagging", }, "mit_movie_trivia": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_movie_trivia", "task_type": "SlotTagging", }, "mit_restaurant": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "mit_restaurant", "task_type": "SlotTagging", }, "snips": { "dataset_class": PromptSlotTaggingDataset, "dataset_folder": "snips", "task_type": "SlotTagging", }, } class AugDataset(LBIDDataset): def __init__(self, task_name, tokz, label_data_path, unlabel_data_path, ctx_max_len=100, special_token_ids=None): self.tokz = tokz self.max_ans_len = 0 self.special_token_ids = special_token_ids with open(label_data_path, "r", encoding='utf-8') as f: ori_data = [json.loads(i) for i in f.readlines()] with open(unlabel_data_path, "r", encoding='utf-8') as f: ori_data += [json.loads(i) for i in f.readlines()] data = [] for i in ori_data: data += self.parse_example(i) self.data = [] if len(data) > 0: self.data = self.data_tokenization(task_name, data) def parse_example(self, example): text = example['userInput']['text'] aug_text_list = eda(text, num_aug=args.num_aug) ans = self.get_answer(example['intent']) res = [(aug_text, ans) for aug_text in aug_text_list] res.append((text, ans)) return res def get_datasets(path, tasks, tokz, ctx_max_len=100, special_token_ids=None): res = {} for task in tasks: res[task] = {} info = TASK2INFO[task] if args.data_type == "intent": res[task]['label_train'] = LBIDDataset( task, tokz, os.path.join(path, info['dataset_folder'], 'label_train.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) res[task]['unlabel_train'] = ULBIDDataset( task, tokz, os.path.join(path, info['dataset_folder'], 'unlabel_train.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) if args.meantc: filename = 'unlabel_' + str(args.num_unlabel) + '_train.json' res[task]['aug_train'] = AugDataset(task, tokz, os.path.join(path, info['dataset_folder'], 'label_train.json'), os.path.join(path, info['dataset_folder'], filename), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) res[task]['val'] = TASK2INFO[task]['dataset_class'](task, tokz, os.path.join(path, info['dataset_folder'], 'valid.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) res[task]['test'] = TASK2INFO[task]['dataset_class'](task, tokz, os.path.join(path, info['dataset_folder'], 'test.json'), ctx_max_len=ctx_max_len, special_token_ids=special_token_ids) return res
null
165,069
from transformers import MarianMTModel, MarianTokenizer import torch def translate(texts, model, tokenizer, language="fr"): def back_translate(texts, target_model, target_tokenizer, en_model, en_tokenizer, source_lang="en", target_lang="fr"): # Translate from source to target language fr_texts = translate(texts, target_model, target_tokenizer, language=target_lang) # Translate from target language back to source language back_translated_texts = translate(fr_texts, en_model, en_tokenizer, language=source_lang) return back_translated_texts
null
165,070
import nltk import re import random from random import shuffle random.seed(1) def get_only_chars(line): clean_line = "" line = line.replace("’", "") line = line.replace("'", "") line = line.replace("-", " ") # replace hyphens with spaces line = line.replace("\t", " ") line = line.replace("\n", " ") line = line.lower() for char in line: if char in 'qwertyuiopasdfghjklzxcvbnm ': clean_line += char else: clean_line += ' ' clean_line = re.sub(' +', ' ', clean_line) # delete extra spaces if clean_line[0] == ' ': clean_line = clean_line[1:] return clean_line def synonym_replacement(words, n): new_words = words.copy() random_word_list = list( set([word for word in words if word not in stop_words])) random.shuffle(random_word_list) num_replaced = 0 for random_word in random_word_list: synonyms = get_synonyms(random_word) if len(synonyms) >= 1: synonym = random.choice(list(synonyms)) new_words = [synonym if word == random_word else word for word in new_words] #print("replaced", random_word, "with", synonym) num_replaced += 1 if num_replaced >= n: # only replace up to n words break #this is stupid but we need it, trust me sentence = ' '.join(new_words) new_words = sentence.split(' ') return new_words def random_deletion(words, p): #obviously, if there's only one word, don't delete it if len(words) == 1: return words #randomly delete words with probability p new_words = [] for word in words: r = random.uniform(0, 1) if r > p: new_words.append(word) #if you end up deleting all words, just return a random word if len(new_words) == 0 and len(words)>1: rand_int = random.randint(0, len(words)-1) return [words[rand_int]] return new_words def random_swap(words, n): new_words = words.copy() for _ in range(n): if len(new_words) > 1: new_words = swap_word(new_words) else: new_words = words return new_words def random_insertion(words, n): new_words = words.copy() for _ in range(n): add_word(new_words) return new_words def eda(sentence, alpha_sr=0.0, alpha_ri=0.0, alpha_rs=0.1, p_rd=0.05, num_aug=5): sentence = get_only_chars(sentence) words = sentence.split(' ') words = [word for word in words if word!=''] num_words = len(words) augmented_sentences = [] num_new_per_technique = int(num_aug/4)+1 #sr if (alpha_sr > 0): n_sr = max(1, int(alpha_sr*num_words)) for _ in range(num_new_per_technique): a_words = synonym_replacement(words, n_sr) augmented_sentences.append(' '.join(a_words)) #ri if (alpha_ri > 0): n_ri = max(1, int(alpha_ri*num_words)) for _ in range(num_new_per_technique): a_words = random_insertion(words, n_ri) augmented_sentences.append(' '.join(a_words)) #rs if (alpha_rs > 0): n_rs = max(1, int(alpha_rs*num_words)) for _ in range(num_new_per_technique): a_words = random_swap(words, n_rs) augmented_sentences.append(' '.join(a_words)) #rd if (p_rd > 0): for _ in range(num_new_per_technique): a_words = random_deletion(words, p_rd) augmented_sentences.append(' '.join(a_words)) augmented_sentences = [get_only_chars(sentence) for sentence in augmented_sentences] shuffle(augmented_sentences) #trim so that we have the desired number of augmented sentences if num_aug >= 1: augmented_sentences = augmented_sentences[:num_aug] else: keep_prob = num_aug / len(augmented_sentences) augmented_sentences = [s for s in augmented_sentences if random.uniform(0, 1) < keep_prob] #append the original sentence augmented_sentences.append(sentence) shuffle(augmented_sentences) return augmented_sentences
null
165,072
import torch import csv import os import json import logging from fp16 import FP16_Module import GPUtil from collections import OrderedDict from settings import args, MODEL_CLASS, TOKENIZER, SPECIAL_TOKEN_IDS, init_logging from settings import MEMORY_FACTOR, LEN_FACTOR, TASK_DICT, MODEL_CONFIG, DATA_ATTRS, SPECIAL_TOKENS, CONFIG_CLASS, CONFIG_NAME from utils import QADataset, top_k_top_p_filtering, create_dataloader, logits_to_tokens, get_model_dir from utils import sample_sequence, remove_id, get_gen_token, lll_unbound_setting from metrics import * logger = logging.getLogger(__name__) def test_one_to_one(curr_task, task_eval, model, score_dict,last=True, eval_data=None, out_dir=None): logger.info('Start to evaluate %s'%task_eval) max_ans_len = eval_data.max_ans_len + 1 # print('Maximum answer length',max_ans_len,flush=True) if out_dir is not None: if not os.path.exists(out_dir): os.makedirs(out_dir) out_dir = os.path.join( out_dir, f'{task_eval}.json') out_dir_content = [] with torch.no_grad(): model.set_active_adapters(task_eval) # print('model of task: {}'.format(task),list(model.parameters()), flush=True) model.eval() pred_ans_all, gold_ans_all = [], [] context_all = [] all_pred_task_name = [] for i, data in enumerate(eval_data): example = data['context_id'].cuda() example_mask = data['context_mask'].cuda() if out_dir is not None: context_all.append(example) gold_ans = data['ans_id'].cuda() # Print model inputs to check. # if i==0: # print('context:',self.tokz.decode(example[0]),flush=True) # print('ans:',self.tokz.decode(gold_ans[0]),flush=True) pred_ans, _ = get_answer(self.tokz, model, example, example_mask, self.args.max_ans_len, args=self.args, is_eval=True) # print('context shape',context.shape,flush=True) # pred_ans = pred_ans[:,context.shape[1]:] pred_ans = pred_ans[:,1:] # Remove the first <pad> token. # print('pred',pred_ans,flush=True) # print('gold',gold_ans,flush=True) # output tensors pred_ans_all.append(pred_ans) gold_ans_all.append(gold_ans) # * Compute score. # print('task_eval',task_eval,flush=True) get_test_score(task_eval, qa_results, score_dict) return model, score_dict def training_test_one_to_many(model,curr_task,step,last=True, dataloaders=None, args=None): # task_load like 'hwu' 'banking' model.eval() score_dicts = [] logger.info("task: {}, step: {}".format(curr_task, step)) score_dict = {k:None for k in args.tasks} with torch.no_grad(): for task_eval in args.tasks: if args.test_overfit: eval_data = dataloaders[task]['label_train'] else: eval_data = dataloaders[task]['test'] eval_dir = os.path.join(args.output_dir, curr_task) test_one_to_one(curr_task, task_eval, model, score_dict, last=last, eval_data=eval_data, out_dir=eval_dir) logger.info("score: {}".format(score_dict)) score_dicts.append(score_dict) return score_dicts[0]
null
165,073
import collections import string import re import numpy as np def normalize_text(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s)))) def computeLFEM(greedy, answer): count = 0 correct = 0 text_answers = [] for idx, (g, ex) in enumerate(zip(greedy, answer)): count += 1 text_answers.append([ex['answer'].lower()]) try: gt = ex['sql'] conds = gt['conds'] lower_conds = [] for c in conds: lc = c lc[2] = str(lc[2]).lower().replace(' ', '') lower_conds.append(lc) gt['conds'] = lower_conds lf = to_lf(g, ex['table']) correct += lf == gt except Exception as e: continue return (correct / count) * 100, text_answers def computeF1(outputs, targets): return sum([metric_max_over_ground_truths(f1_score, o, t) for o, t in zip(outputs, targets)]) / len(outputs) * 100 def computeEM(outputs, targets): outs = [metric_max_over_ground_truths(exact_match, o, t) for o, t in zip(outputs, targets)] # print(f'EM outs: {outs}',flush=True) return sum(outs) / len(outputs) * 100 def computeCF1(greedy, answer): scores = np.zeros(4) for g, a in zip(greedy, answer): scores += score(g, a) tp, tn, sys_pos, real_pos = scores.tolist() total = len(answer) if tp == 0: p = r = f = 0.0 else: p = tp / float(sys_pos) r = tp / float(real_pos) f = 2 * p * r / (p + r) return f * 100, p * 100, r * 100 def computeDialogue(greedy, answer): examples = [] for idx, (g, a) in enumerate(zip(greedy, answer)): examples.append((a[0], g, a[1], idx)) #examples.sort() turn_request_positives = 0 turn_goal_positives = 0 joint_goal_positives = 0 ldt = None for ex in examples: if ldt is None or ldt.split('_')[:-1] != ex[0].split('_')[:-1]: state, answer_state = {}, {} ldt = ex[0] delta_state = to_delta_state(ex[1]) answer_delta_state = to_delta_state(ex[2]) state = update_state(state, delta_state['inform']) answer_state = update_state(answer_state, answer_delta_state['inform']) if dict_cmp(state, answer_state): joint_goal_positives += 1 if delta_state['request'] == answer_delta_state['request']: turn_request_positives += 1 if dict_cmp(delta_state['inform'], answer_delta_state['inform']): turn_goal_positives += 1 joint_goal_em = joint_goal_positives / len(examples) * 100 turn_request_em = turn_request_positives / len(examples) * 100 turn_goal_em = turn_goal_positives / len(examples) * 100 answer = [(x[-1], x[-2]) for x in examples] #answer.sort() answer = [[x[1]] for x in answer] return joint_goal_em, turn_request_em, turn_goal_em, answer def compute_metrics(data, rouge=False, bleu=False, corpus_f1=False, logical_form=False, dialogue=False): greedy = [datum[0] for datum in data] # prediction answer = [datum[1] for datum in data] # ground truth for i in range(3): pred, tgt = data[i] print('pred', pred,'tgt',tgt, flush=True) metric_keys = [] metric_values = [] if logical_form: lfem, answer = computeLFEM(greedy, answer) metric_keys += ['lfem'] metric_values += [lfem] em = computeEM(greedy, answer) metric_keys.append('em') metric_values.append(em) norm_greedy = [normalize_text(g) for g in greedy] norm_answer = [[normalize_text(a) for a in ans] for ans in answer] nf1 = computeF1(norm_greedy, norm_answer) nem = computeEM(norm_greedy, norm_answer) metric_keys.extend(['nf1', 'nem']) metric_values.extend([nf1, nem]) if corpus_f1: corpus_f1, precision, recall = computeCF1(norm_greedy, norm_answer) metric_keys += ['corpus_f1', 'precision', 'recall'] metric_values += [corpus_f1, precision, recall] if dialogue: joint_goal_em, request_em, turn_goal_em, answer = computeDialogue(greedy, answer) avg_dialogue = (joint_goal_em + request_em) / 2 metric_keys += ['joint_goal_em', 'turn_request_em', 'turn_goal_em', 'avg_dialogue'] metric_values += [joint_goal_em, request_em, turn_goal_em, avg_dialogue] metric_dict = collections.OrderedDict(list(zip(metric_keys, metric_values))) return metric_dict
null
165,074
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os import argparse from gloc.utils import twoD_list_transpose def merge_dic(dic_col: Dict,dic_row: Dict): new_dic = {} keys = range(max(len(dic_col), len(dic_row))) for key in keys: key = str(key) data_it = copy.deepcopy(dic_col[key]['data_item']) if len(dic_col) != 0 else copy.deepcopy(dic_row[key]['data_item']) col_gen = copy.deepcopy(dic_col[key]['generations']) if len(dic_col) != 0 else [] row_gen = copy.deepcopy(dic_row[key]['generations']) if len(dic_row) != 0 else [] new_dic[key] = { 'data_item': data_it, 'generations':{ 'col':col_gen, 'row':row_gen } } return new_dic
null
165,075
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os import argparse from gloc.utils import twoD_list_transpose def twoD_list_transpose(arr:List[List],keep_num_rows:int=3): arr = arr[:keep_num_rows+1] if keep_num_rows + 1 <= len(arr) else arr return [[arr[i][j] for i in range(len(arr))] for j in range(len(arr[0]))] def filter_col(table,pred_col): table = twoD_list_transpose(table,len(table)) new_table = [] for cols in table: if cols[0] in pred_col: new_table.append(copy.deepcopy(cols)) if len(new_table) == 0: new_table = table new_table = twoD_list_transpose(new_table,len(new_table)) return new_table
null
165,076
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os import argparse from gloc.utils import twoD_list_transpose def filter_row(table,pred_row): if '*' in pred_row: return table new_table = [copy.deepcopy(table[0])] for idx in range(len(table)): if str(idx) in pred_row: new_table.append(copy.deepcopy(table[idx])) if len(new_table) == 1: new_table = table return new_table
null
165,077
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os import argparse from gloc.utils import twoD_list_transpose def union_lists(to_union:List[List[str]],nums=None): if nums is None: return list(set().union(*to_union)) return list(set().union(*to_union[:nums])) def preprocess(dic:Dict,union_col:int=1,union_row:int=2): def l_tb(tb): stb = '' header = tb[0] stb += 'col : '+ ' | '.join(header) for row_idx, row in enumerate(tb[1:]): line = ' row {} : '.format(row_idx + 1) + ' | '.join(row) stb += line return stb pattern_col = '(f_col\(\[(.*?)\]\))' pattern_col = re.compile(pattern_col, re.S) pattern_row = '(f_row\(\[(.*?)\]\))' pattern_row = re.compile(pattern_row, re.S) input_f = open(f'wtq_{args.dataset_split}_span_{union_col}_{union_row}.jsonl', "w", encoding="utf8") for key in dic: it = dic[key] # CodeX 没有产生任何东西 table = it['data_item']['table_text'] ######### col filed################ preds = it['generations']['col'] if len(preds) != 0 and union_col !=0: to_union = {} for pred in preds: log_prob_mean = pred[2] try: pred = re.findall(pattern_col,pred[0])[0][1] except Exception: continue pred = pred.split(', ') pred = [i.strip() for i in pred] key = str(pred) if key in to_union.keys(): to_union[key] += np.exp(log_prob_mean) else: to_union[key] = np.exp(log_prob_mean) d_ordered = sorted(to_union.items(),key=lambda x:x[1],reverse=True) t_list = [eval(i[0]) for i in d_ordered] cols = union_lists(t_list,union_col) # table = filter_col(table,cols) ######### row filed################ preds = it['generations']['row'] if len(preds) != 0 and union_row != 0: to_union = {} for pred in preds: log_prob_mean = pred[2] try: pred = re.findall(pattern_row,pred[0])[0][1] except Exception: continue pred = pred.split(', ') pred = [i.strip().split(' ')[-1] for i in pred] key = str(pred) if key in to_union.keys(): to_union[key] += np.exp(log_prob_mean) else: to_union[key] = np.exp(log_prob_mean) d_ordered = sorted(to_union.items(),key=lambda x:x[1],reverse=True) t_list = [eval(i[0]) for i in d_ordered] rows = union_lists(t_list,union_row) else: rows = ['*'] statement = it['data_item']['statement'] gt = it['data_item']['answer'] line = json.dumps({ 'statement' : statement, 'table_text':it['data_item']['table_text'], 'label': gt, 'cols':cols, 'rows':rows }) input_f.write(line + '\n') input_f.close()
null
165,078
import sys, os, re, argparse import unicodedata from codecs import open from math import isnan, isinf from abc import ABCMeta, abstractmethod def normalize(x): if not isinstance(x, str): x = x.decode('utf8', errors='ignore') # Remove diacritics x = ''.join(c for c in unicodedata.normalize('NFKD', x) if unicodedata.category(c) != 'Mn') # Normalize quotes and dashes x = re.sub(r"[‘’´`]", "'", x) x = re.sub(r"[“”]", "\"", x) x = re.sub(r"[‐‑‒–—−]", "-", x) while True: old_x = x # Remove citations x = re.sub(r"((?<!^)\[[^\]]*\]|\[\d+\]|[•♦†‡*#+])*$", "", x.strip()) # Remove details in parenthesis x = re.sub(r"(?<!^)( \([^)]*\))*$", "", x.strip()) # Remove outermost quotation mark x = re.sub(r'^"([^"]*)"$', r'\1', x.strip()) if x == old_x: break # Remove final '.' if x and x[-1] == '.': x = x[:-1] # Collapse whitespaces and convert to lower case x = re.sub(r'\s+', ' ', x, flags=re.U).lower().strip() return x
null
165,079
import sys, os, re, argparse import unicodedata from codecs import open from math import isnan, isinf from abc import ABCMeta, abstractmethod def to_value(original_string, corenlp_value=None): """Convert the string to Value object. Args: original_string (basestring): Original string corenlp_value (basestring): Optional value returned from CoreNLP Returns: Value """ if isinstance(original_string, Value): # Already a Value return original_string if not corenlp_value: corenlp_value = original_string # Number? amount = NumberValue.parse(corenlp_value) if amount is not None: return NumberValue(amount, original_string) # Date? ymd = DateValue.parse(corenlp_value) if ymd is not None: if ymd[1] == ymd[2] == -1: return NumberValue(ymd[0], original_string) else: return DateValue(ymd[0], ymd[1], ymd[2], original_string) # String. return StringValue(original_string) The provided code snippet includes necessary dependencies for implementing the `to_value_list` function. Write a Python function `def to_value_list(original_strings, corenlp_values=None)` to solve the following problem: Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value] Here is the function: def to_value_list(original_strings, corenlp_values=None): """Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value] """ assert isinstance(original_strings, (list, tuple, set)) if corenlp_values is not None: assert isinstance(corenlp_values, (list, tuple, set)) assert len(original_strings) == len(corenlp_values) return list(set(to_value(x, y) for (x, y) in zip(original_strings, corenlp_values))) else: return list(set(to_value(x) for x in original_strings))
Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value]
165,080
import sys, os, re, argparse import unicodedata from codecs import open from math import isnan, isinf from abc import ABCMeta, abstractmethod The provided code snippet includes necessary dependencies for implementing the `check_denotation` function. Write a Python function `def check_denotation(target_values, predicted_values)` to solve the following problem: Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool Here is the function: def check_denotation(target_values, predicted_values): """Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool """ # Check size if len(target_values) != len(predicted_values): return False # Check items for target in target_values: if not any(target.match(pred) for pred in predicted_values): return False return True
Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool
165,081
import sys, os, re, argparse import unicodedata from codecs import open from math import isnan, isinf from abc import ABCMeta, abstractmethod def tsv_unescape(x): """Unescape strings in the TSV file. Escaped characters include: newline (0x10) -> backslash + n vertical bar (0x7C) -> backslash + p backslash (0x5C) -> backslash + backslash Args: x (str or unicode) Returns: a unicode """ return x.replace(r'\n', '\n').replace(r'\p', '|').replace('\\\\', '\\') The provided code snippet includes necessary dependencies for implementing the `tsv_unescape_list` function. Write a Python function `def tsv_unescape_list(x)` to solve the following problem: Unescape a list in the TSV file. List items are joined with vertical bars (0x5C) Args: x (str or unicode) Returns: a list of unicodes Here is the function: def tsv_unescape_list(x): """Unescape a list in the TSV file. List items are joined with vertical bars (0x5C) Args: x (str or unicode) Returns: a list of unicodes """ return [tsv_unescape(y) for y in x.split('|')]
Unescape a list in the TSV file. List items are joined with vertical bars (0x5C) Args: x (str or unicode) Returns: a list of unicodes
165,082
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os from gloc.utils import twoD_list_transpose def merge_dic(dic_col: Dict,dic_row: Dict): new_dic = {} keys = range(max(len(dic_col), len(dic_row))) for key in keys: key = str(key) data_it = copy.deepcopy(dic_col[key]['data_item']) if len(dic_col) != 0 else copy.deepcopy(dic_row[key]['data_item']) col_gen = copy.deepcopy(dic_col[key]['generations']) if len(dic_col) != 0 else [] row_gen = copy.deepcopy(dic_row[key]['generations']) if len(dic_row) != 0 else [] new_dic[key] = { 'data_item': data_it, 'generations':{ 'col':col_gen, 'row':row_gen } } return new_dic
null
165,083
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os from gloc.utils import twoD_list_transpose def twoD_list_transpose(arr:List[List],keep_num_rows:int=3): def filter_col(table,pred_col): table = twoD_list_transpose(table,len(table)) new_table = [] for cols in table: if cols[0] in pred_col: new_table.append(copy.deepcopy(cols)) if len(new_table) == 0: new_table = table new_table = twoD_list_transpose(new_table,len(new_table)) return new_table
null
165,084
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os from gloc.utils import twoD_list_transpose def filter_row(table,pred_row): if '*' in pred_row: return table new_table = [copy.deepcopy(table[0])] for idx in range(len(table)): if str(idx) in pred_row: new_table.append(copy.deepcopy(table[idx])) if len(new_table) == 1: new_table = table return new_table
null
165,085
import pandas as pd import numpy as np import json import re from typing import Dict,List import copy import sys import os from gloc.utils import twoD_list_transpose def union_lists(to_union:List[List[str]],nums=None): def preprocess(dic:Dict,union_col:int=1,union_row:int=2): cnt_1 = 0 def l_tb(tb): stb = '' header = tb[0] stb += 'col : '+ ' | '.join(header) for row_idx, row in enumerate(tb[1:]): line = ' row {} : '.format(row_idx + 1) + ' | '.join(row) stb += line return stb pattern_col = '(f_col\(\[(.*?)\]\))' pattern_col = re.compile(pattern_col, re.S) pattern_row = '(f_row\(\[(.*?)\]\))' pattern_row = re.compile(pattern_row, re.S) input_f = open(f'tabfact_span_{union_col}_{union_row}.jsonl', "w", encoding="utf8") for key in dic: it = dic[key] # CodeX 没有产生任何东西 table = it['data_item']['table_text'] ######### col filed################ preds = it['generations']['col'] if len(preds) != 0 and union_col !=0: to_union = {} for pred in preds: log_prob_mean = pred[2] try: pred = re.findall(pattern_col,pred[0])[0][1] except Exception: continue pred = pred.split(', ') pred = [i.strip() for i in pred] pred = sorted(pred) key = str(pred) if key in to_union.keys(): to_union[key] += np.exp(log_prob_mean) else: to_union[key] = np.exp(log_prob_mean) d_ordered = sorted(to_union.items(),key=lambda x:x[1],reverse=True) t_list = [eval(i[0]) for i in d_ordered] cols = union_lists(t_list,union_col) # table = filter_col(table,cols) ######### row filed################ preds = it['generations']['row'] if len(preds) != 0 and union_row != 0: to_union = {} for pred in preds: log_prob_mean = pred[2] try: pred = re.findall(pattern_row,pred[0])[0][1] except Exception: continue pred = pred.split(', ') pred = [i.strip().split(' ')[-1] for i in pred] pred = sorted(pred) key = str(pred) if key in to_union.keys(): to_union[key] += np.exp(log_prob_mean) else: to_union[key] = np.exp(log_prob_mean) d_ordered = sorted(to_union.items(),key=lambda x:x[1],reverse=True) t_list = [eval(i[0]) for i in d_ordered] rows = union_lists(t_list,union_row) # table = filter_row(table,rows) if len(table) == 2: cnt_1+=1 else: rows = ['*'] statement = it['data_item']['statement'] gt = it['data_item']['label'] line = json.dumps({ 'statement' : statement, 'table_text':it['data_item']['table_text'], 'label': gt, 'cols':cols, 'rows':rows }) input_f.write(line + '\n') print(cnt_1) input_f.close()
null
165,086
import json import collections import pandas as pd import numpy as np def merge_res(dic): acc = 0. for key in dic: to_union = collections.defaultdict(float) it = dic[key] # CodeX 没有产生任何东西 table = it['data_item']['table_text'] ######### col filed################ preds = it['generations'] for pred in preds: log_prob_mean = pred[2] pred = pred[0] try: # pred = re.findall(pattern,pred[0])[0][1] pred = pred.split(':')[-1] # print(pred) # input() except Exception: continue if pred.count('True')>=1: key = 1 to_union[key] += np.exp(log_prob_mean) elif pred.count('False')>=1: key = 0 to_union[key] += np.exp(log_prob_mean) if to_union[0] > to_union[1]: pred_answer = 0 else: pred_answer = 1 gt = it['data_item']['label'] if gt == pred_answer: acc += 1 print('ACC:', acc/len(dic))
null
165,087
import random from typing import Dict, Tuple import pandas as pd import copy from utils.errors import DuplicateColumnsError from retrieval.retrieve_pool import QAItem from utils.normalizer import prepare_df_for_neuraldb_from_table class DuplicateColumnsError(Exception): def __init__(self, msg): self.msg = msg The provided code snippet includes necessary dependencies for implementing the `_create_table_prompt` function. Write a Python function `def _create_table_prompt(df: pd.DataFrame, title: str)` to solve the following problem: Return the CREATE TABLE clause as prompt. Here is the function: def _create_table_prompt(df: pd.DataFrame, title: str): """ Return the CREATE TABLE clause as prompt. """ string = "CREATE TABLE {}(\n".format(title) for header in df.columns: column_type = 'text' try: if df[header].dtype == 'int64': column_type = 'int' elif df[header].dtype == 'float64': column_type = 'real' elif df[header].dtype == 'datetime64': column_type = 'datetime' except AttributeError as e: raise DuplicateColumnsError(e) string += '\t{} {},\n'.format(header, column_type) string = string.rstrip(',\n') + ')\n' return string
Return the CREATE TABLE clause as prompt.
165,088
import copy import os import sqlite3 import records import sqlalchemy import pandas as pd from typing import Dict, List import uuid from utils.normalizer import convert_df_type, prepare_df_for_neuraldb_from_table from utils.mmqa.image_stuff import get_caption def check_in_and_return(key: str, source: dict): # `` wrapped means as a whole if key.startswith("`") and key.endswith("`"): key = key[1:-1] if key in source.keys(): return source[key] else: for _k, _v in source.items(): if _k.lower() == key.lower(): return _v raise ValueError("{} not in {}".format(key, source))
null
165,089
from typing import List import re import sqlparse class TreeNode(object): def __init__(self, name=None, father=None): self.name: str = name self.rename: str = name self.father: TreeNode = father self.children: List = [] self.produced_col_name_s = None def __eq__(self, other): return self.rename == other.rename def __hash__(self): return hash(self.rename) def set_name(self, name): self.name = name self.rename = name def add_child(self, child): self.children.append(child) child.father = self def rename_father_col(self, col_idx: int, col_prefix: str = "col_"): new_col_name = "{}{}".format(col_prefix, col_idx) self.father.rename = self.father.rename.replace(self.name, "{}".format(new_col_name)) self.produced_col_name_s = [new_col_name] # fixme when multiple outputs for a qa func def rename_father_val(self, val_names): if len(val_names) == 1: val_name = val_names[0] new_val_equals_str = "'{}'".format(val_name) if isinstance(convert_type(val_name), str) else "{}".format( val_name) else: new_val_equals_str = '({})'.format(', '.join(["'{}'".format(val_name) for val_name in val_names])) self.father.rename = self.father.rename.replace(self.name, new_val_equals_str) The provided code snippet includes necessary dependencies for implementing the `get_cfg_tree` function. Write a Python function `def get_cfg_tree(nsql: str)` to solve the following problem: Parse QA() into a tree for execution guiding. @param nsql: @return: Here is the function: def get_cfg_tree(nsql: str): """ Parse QA() into a tree for execution guiding. @param nsql: @return: """ stack: List = [] # Saving the state of the char. expression_stack: List = [] # Saving the state of the expression. current_tree_node = TreeNode(name=nsql) for idx in range(len(nsql)): if nsql[idx] == "(": stack.append(idx) if idx > 1 and nsql[idx - 2:idx + 1] == "QA(" and idx - 2 != 0: tree_node = TreeNode() current_tree_node.add_child(tree_node) expression_stack.append(current_tree_node) current_tree_node = tree_node elif nsql[idx] == ")": left_clause_idx = stack.pop() if idx > 1 and nsql[left_clause_idx - 2:left_clause_idx + 1] == "QA(" and left_clause_idx - 2 != 0: # the QA clause nsql_span = nsql[left_clause_idx - 2:idx + 1] current_tree_node.set_name(nsql_span) current_tree_node = expression_stack.pop() return current_tree_node
Parse QA() into a tree for execution guiding. @param nsql: @return:
165,090
from typing import List import re import sqlparse class TreeNode(object): def __init__(self, name=None, father=None): self.name: str = name self.rename: str = name self.father: TreeNode = father self.children: List = [] self.produced_col_name_s = None def __eq__(self, other): return self.rename == other.rename def __hash__(self): return hash(self.rename) def set_name(self, name): self.name = name self.rename = name def add_child(self, child): self.children.append(child) child.father = self def rename_father_col(self, col_idx: int, col_prefix: str = "col_"): new_col_name = "{}{}".format(col_prefix, col_idx) self.father.rename = self.father.rename.replace(self.name, "{}".format(new_col_name)) self.produced_col_name_s = [new_col_name] # fixme when multiple outputs for a qa func def rename_father_val(self, val_names): if len(val_names) == 1: val_name = val_names[0] new_val_equals_str = "'{}'".format(val_name) if isinstance(convert_type(val_name), str) else "{}".format( val_name) else: new_val_equals_str = '({})'.format(', '.join(["'{}'".format(val_name) for val_name in val_names])) self.father.rename = self.father.rename.replace(self.name, new_val_equals_str) The provided code snippet includes necessary dependencies for implementing the `get_steps` function. Write a Python function `def get_steps(tree_node: TreeNode, steps: List)` to solve the following problem: Pred-Order Traversal Here is the function: def get_steps(tree_node: TreeNode, steps: List): """Pred-Order Traversal""" for child in tree_node.children: get_steps(child, steps) steps.append(tree_node)
Pred-Order Traversal
165,091
from typing import List import re import sqlparse def parse_question_paras(nsql: str, qa_model): # We assume there's no nested qa inside when running this func nsql = nsql.strip(" ;") assert nsql[:3] == "QA(" and nsql[-1] == ")", "must start with QA( symbol and end with )" assert not "QA" in nsql[2:-1], "must have no nested qa inside" # Get question and the left part(paras_raw_str) all_quote_idx = [i.start() for i in re.finditer('\"', nsql)] question = nsql[all_quote_idx[0] + 1: all_quote_idx[1]] paras_raw_str = nsql[all_quote_idx[1] + 1:-1].strip(" ;") # Split Parameters(SQL/column/value) from all parameters. paras = [_para.strip(' ;') for _para in sqlparse.split(paras_raw_str)] return question, paras
null
165,092
from typing import List import re import sqlparse def convert_type(value): try: return eval(value) except Exception as e: return value
null
165,093
from typing import List import re import sqlparse The provided code snippet includes necessary dependencies for implementing the `nsql_role_recognize` function. Write a Python function `def nsql_role_recognize(nsql_like_str, all_headers, all_passage_titles, all_image_titles)` to solve the following problem: Recognize role. (SQL/column/value) Here is the function: def nsql_role_recognize(nsql_like_str, all_headers, all_passage_titles, all_image_titles): """Recognize role. (SQL/column/value) """ orig_nsql_like_str = nsql_like_str # strip the first and the last '`' if nsql_like_str.startswith('`') and nsql_like_str.endswith('`'): nsql_like_str = nsql_like_str[1:-1] # Case 1: if col in header, it is column type. if nsql_like_str in all_headers or nsql_like_str in list(map(lambda x: x.lower(), all_headers)): return 'col', orig_nsql_like_str # fixme: add case when the this nsql_like_str both in table headers, images title and in passages title. # Case 2.1: if it is title of certain passage. if (nsql_like_str.lower() in list(map(lambda x: x.lower(), all_passage_titles))) \ and (nsql_like_str.lower() in list(map(lambda x: x.lower(), all_image_titles))): return "passage_title_and_image_title", orig_nsql_like_str else: try: nsql_like_str_evaled = str(eval(nsql_like_str)) if (nsql_like_str_evaled.lower() in list(map(lambda x: x.lower(), all_passage_titles))) \ and (nsql_like_str_evaled.lower() in list(map(lambda x: x.lower(), all_image_titles))): return "passage_title_and_image_title", nsql_like_str_evaled except: pass # Case 2.2: if it is title of certain passage. if nsql_like_str.lower() in list(map(lambda x: x.lower(), all_passage_titles)): return "passage_title", orig_nsql_like_str else: try: nsql_like_str_evaled = str(eval(nsql_like_str)) if nsql_like_str_evaled.lower() in list(map(lambda x: x.lower(), all_passage_titles)): return "passage_title", nsql_like_str_evaled except: pass # Case 2.3: if it is title of certain picture. if nsql_like_str.lower() in list(map(lambda x: x.lower(), all_image_titles)): return "image_title", orig_nsql_like_str else: try: nsql_like_str_evaled = str(eval(nsql_like_str)) if nsql_like_str_evaled.lower() in list(map(lambda x: x.lower(), all_image_titles)): return "image_title", nsql_like_str_evaled except: pass # Case 4: if it can be parsed by eval(), it is value type. try: eval(nsql_like_str) return 'val', orig_nsql_like_str except Exception as e: pass # Case 5: else it should be the sql, if it isn't, exception will be raised. return 'complete_sql', orig_nsql_like_str
Recognize role. (SQL/column/value)
165,094
from typing import List import re import sqlparse def remove_duplicate(original_list): no_duplicate_list = [] [no_duplicate_list.append(i) for i in original_list if i not in no_duplicate_list] return no_duplicate_list
null
165,095
from typing import List import re import sqlparse def extract_answers(sub_table): if not sub_table or sub_table['header'] is None: return [] answer = [] if 'row_id' in sub_table['header']: for _row in sub_table['rows']: answer.extend(_row[1:]) return answer else: for _row in sub_table['rows']: answer.extend(_row) return answer
null
165,096
import requests import base64 import time def vqa_call(question, image_path, api_url='https://hf.space/embed/OFA-Sys/OFA-vqa/+/api/predict/'): with open(image_path, "rb") as f: base64_data = base64.b64encode(f.read()) base64_data_to_send = "data:image/{};base64,{}".format(image_path.split(".")[-1], str(base64_data)[2:-1]) return requests.post(url=api_url, json={"data": [base64_data_to_send, question]}).json()['data'][0]
null
165,097
import time import json import argparse import copy import os from typing import List import platform import multiprocessing from generation.generator import Generator from utils.utils import load_data_split from nsql.database import NeuralDB class Generator(object): """ Codex generation wrapper. """ def __init__(self, args, keys=None): self.args = args self.keys = keys self.current_key_id = 0 # if the args provided, will initialize with the prompt builder for full usage self.prompt_builder = PromptBuilder(args) if args else None def prompt_row_truncate( self, prompt: str, num_rows_to_remain: int, table_end_token: str = '*/', ): """ Fit prompt into max token limits by row truncation. """ table_end_pos = prompt.rfind(table_end_token) assert table_end_pos != -1 prompt_part1, prompt_part2 = prompt[:table_end_pos], prompt[table_end_pos:] prompt_part1_lines = prompt_part1.split('\n')[::-1] trunc_line_index = None for idx, line in enumerate(prompt_part1_lines): if '\t' not in line: continue row_id = int(line.split('\t')[0]) if row_id <= num_rows_to_remain: trunc_line_index = idx break new_prompt_part1 = '\n'.join(prompt_part1_lines[trunc_line_index:][::-1]) prompt = new_prompt_part1 + '\n' + prompt_part2 return prompt def build_few_shot_prompt_from_file( self, file_path: str, n_shots: int ): """ Build few-shot prompt for generation from file. """ with open(file_path, 'r') as f: lines = f.readlines() few_shot_prompt_list = [] one_shot_prompt = '' last_line = None for line in lines: if line == '\n' and last_line == '\n': few_shot_prompt_list.append(one_shot_prompt) one_shot_prompt = '' else: one_shot_prompt += line last_line = line few_shot_prompt_list.append(one_shot_prompt) few_shot_prompt_list = few_shot_prompt_list[:n_shots] few_shot_prompt_list[-1] = few_shot_prompt_list[ -1].strip() # It is essential for prompting to remove extra '\n' few_shot_prompt = '\n'.join(few_shot_prompt_list) return few_shot_prompt def build_generate_prompt( self, data_item: Dict, generate_type: Tuple ): """ Build the generate prompt """ return self.prompt_builder.build_generate_prompt( **data_item, generate_type=generate_type ) def generate_one_pass( self, prompts: List[Tuple], verbose: bool = False ): """ Generate one pass with codex according to the generation phase. """ result_idx_to_eid = [] for p in prompts: result_idx_to_eid.extend([p[0]] * self.args.sampling_n) prompts = [p[1] for p in prompts] result = self._call_codex_api( engine=self.args.engine, prompt=prompts, max_tokens=self.args.max_generation_tokens, temperature=self.args.temperature, top_p=self.args.top_p, n=self.args.sampling_n, stop=self.args.stop_tokens ) if verbose: print('\n', '*' * 20, 'Codex API Call', '*' * 20) for prompt in prompts: print(prompt) print('\n') print('- - - - - - - - - - ->>') # parse api results response_dict = dict() for idx, g in enumerate(result['choices']): try: text = g['text'] logprob = sum(g['logprobs']['token_logprobs']) eid = result_idx_to_eid[idx] eid_pairs = response_dict.get(eid, None) if eid_pairs is None: eid_pairs = [] response_dict[eid] = eid_pairs eid_pairs.append((text, logprob)) if verbose: print(text) except ValueError as e: if verbose: print('----------- Error Msg--------') print(e) print(text) print('-----------------------------') pass return response_dict def _call_codex_api( self, engine: str, prompt: Union[str, List], max_tokens, temperature: float, top_p: float, n: int, stop: List[str] ): start_time = time.time() result = None while result is None: try: key = self.keys[self.current_key_id] self.current_key_id = (self.current_key_id + 1) % len(self.keys) print(f"Using openai api key: {key}") result = openai.Completion.create( engine=engine, prompt=prompt, api_key=key, max_tokens=max_tokens, temperature=temperature, top_p=top_p, n=n, stop=stop, logprobs=1 ) print('Openai api inference time:', time.time() - start_time) return result except Exception as e: print(e, 'Retry.') time.sleep(20) class NeuralDB(object): def __init__(self, tables: List[Dict[str, Dict]], passages=None, images=None): self.raw_tables = copy.deepcopy(tables) self.passages = {} self.images = {} self.image_captions = {} self.passage_linker = {} # The links from cell value to passage self.image_linker = {} # The links from cell value to images # Get passages if passages: for passage in passages: title, passage_content = passage['title'], passage['text'] self.passages[title] = passage_content # Get images if images: for image in images: _id, title, picture = image['id'], image['title'], image['pic'] self.images[title] = picture self.image_captions[title] = get_caption(_id) # Link grounding resources from other modalities(passages, images). if self.raw_tables[0]['table'].get('rows_with_links', None): rows = self.raw_tables[0]['table']['rows'] rows_with_links = self.raw_tables[0]['table']['rows_with_links'] link_title2cell_map = {} for row_id in range(len(rows)): for col_id in range(len(rows[row_id])): cell = rows_with_links[row_id][col_id] for text, title, url in zip(cell[0], cell[1], cell[2]): text = text.lower().strip() link_title2cell_map[title] = text # Link Passages for passage in passages: title, passage_content = passage['title'], passage['text'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.passage_linker[linked_cell] = title # Images for image in images: title, picture = image['title'], image['pic'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.image_linker[linked_cell] = title for table_info in tables: table_info['table'] = prepare_df_for_neuraldb_from_table(table_info['table']) self.tables = tables # Connect to SQLite database self.tmp_path = "tmp" os.makedirs(self.tmp_path, exist_ok=True) # self.db_path = os.path.join(self.tmp_path, '{}.db'.format(hash(time.time()))) self.db_path = os.path.join(self.tmp_path, '{}.db'.format(uuid.uuid4())) self.sqlite_conn = sqlite3.connect(self.db_path) # Create DB assert len(tables) >= 1, "DB has no table inside" table_0 = tables[0] if len(tables) > 1: raise ValueError("More than one table not support yet.") else: table_0["table"].to_sql("w", self.sqlite_conn) self.table_name = "w" self.table_title = table_0.get('title', None) # Records conn self.db = records.Database('sqlite:///{}'.format(self.db_path)) self.records_conn = self.db.get_connection() def __str__(self): return str(self.execute_query("SELECT * FROM {}".format(self.table_name))) def get_table(self, table_name=None): table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) _table = self.execute_query(sql_query) return _table def get_header(self, table_name=None): _table = self.get_table(table_name) return _table['header'] def get_rows(self, table_name): _table = self.get_table(table_name) return _table['rows'] def get_table_df(self): return self.tables[0]['table'] def get_table_raw(self): return self.raw_tables[0]['table'] def get_table_title(self): return self.tables[0]['title'] def get_passages_titles(self): return list(self.passages.keys()) def get_images_titles(self): return list(self.images.keys()) def get_passage_by_title(self, title: str): return check_in_and_return(title, self.passages) def get_image_by_title(self, title): return check_in_and_return(title, self.images) def get_image_caption_by_title(self, title): return check_in_and_return(title, self.image_captions) def get_image_linker(self): return copy.deepcopy(self.image_linker) def get_passage_linker(self): return copy.deepcopy(self.passage_linker) def execute_query(self, sql_query: str): """ Basic operation. Execute the sql query on the database we hold. """ # When the sql query is a column name (@deprecated: or a certain value with '' and "" surrounded). if len(sql_query.split(' ')) == 1 or (sql_query.startswith('`') and sql_query.endswith('`')): col_name = sql_query new_sql_query = r"SELECT row_id, {} FROM {}".format(col_name, self.table_name) # Here we use a hack that when a value is surrounded by '' or "", the sql will return a column of the value, # while for variable, no ''/"" surrounded, this sql will query for the column. out = self.records_conn.query(new_sql_query) # When the sql query wants all cols or col_id, which is no need for us to add 'row_id'. elif sql_query.lower().startswith("select *") or sql_query.startswith("select col_id"): out = self.records_conn.query(sql_query) else: try: # SELECT row_id in addition, needed for result and old table alignment. new_sql_query = "SELECT row_id, " + sql_query[7:] out = self.records_conn.query(new_sql_query) except sqlalchemy.exc.OperationalError as e: # Execute normal SQL, and in this case the row_id is actually in no need. out = self.records_conn.query(sql_query) results = out.all() unmerged_results = [] merged_results = [] headers = out.dataset.headers for i in range(len(results)): unmerged_results.append(list(results[i].values())) merged_results.extend(results[i].values()) return {"header": headers, "rows": unmerged_results} def add_sub_table(self, sub_table, table_name=None, verbose=True): """ Add sub_table into the table. """ table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) oring_table = self.execute_query(sql_query) old_table = pd.DataFrame(oring_table["rows"], columns=oring_table["header"]) # concat the new column into old table sub_table_df_normed = convert_df_type(pd.DataFrame(data=sub_table['rows'], columns=sub_table['header'])) new_table = old_table.merge(sub_table_df_normed, how='left', on='row_id') # do left join new_table.to_sql(table_name, self.sqlite_conn, if_exists='replace', index=False) if verbose: print("Insert column(s) {} (dtypes: {}) into table.\n".format(', '.join([_ for _ in sub_table['header']]), sub_table_df_normed.dtypes)) The provided code snippet includes necessary dependencies for implementing the `worker_annotate` function. Write a Python function `def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, tokenizer )` to solve the following problem: A worker process for annotating. Here is the function: def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, tokenizer ): """ A worker process for annotating. """ g_dict = dict() built_few_shot_prompts = [] for g_eid in g_eids: try: g_data_item = dataset[g_eid] g_dict[g_eid] = { 'generations': [], 'ori_data_item': copy.deepcopy(g_data_item) } db = NeuralDB( tables=[{'title': g_data_item['table']['page_title'], 'table': g_data_item['table']}] ) g_data_item['table'] = db.get_table_df() g_data_item['title'] = db.get_table_title() n_shots = args.n_shots few_shot_prompt = generator.build_few_shot_prompt_from_file( file_path=args.prompt_file, n_shots=n_shots ) generate_prompt = generator.build_generate_prompt( data_item=g_data_item, generate_type=(args.generate_type,) ) prompt = few_shot_prompt + "\n\n" + generate_prompt # Ensure the input length fit Codex max input tokens by shrinking the n_shots max_prompt_tokens = args.max_api_total_tokens - args.max_generation_tokens while len(tokenizer.tokenize(prompt)) >= max_prompt_tokens: # TODO: Add shrink rows n_shots -= 1 assert n_shots >= 0 few_shot_prompt = generator.build_few_shot_prompt_from_file( file_path=args.prompt_file, n_shots=n_shots ) prompt = few_shot_prompt + "\n\n" + generate_prompt print(f"Process#{pid}: Building prompt for eid#{g_eid}, original_id#{g_data_item['id']}") built_few_shot_prompts.append((g_eid, prompt)) if len(built_few_shot_prompts) < args.n_parallel_prompts: continue print(f"Process#{pid}: Prompts ready with {len(built_few_shot_prompts)} parallels. Run openai API.") response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs built_few_shot_prompts = [] except Exception as e: print(f"Process#{pid}: eid#{g_eid}, wtqid#{g_data_item['id']} generation error: {e}") # Final generation inference if len(built_few_shot_prompts) > 0: response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs return g_dict
A worker process for annotating.
165,098
import time import json import argparse import copy import os import random from typing import List import platform import multiprocessing from generation.generator import Generator from utils.utils import load_data_split from nsql.database import NeuralDB class Generator(object): """ Codex generation wrapper. """ def __init__(self, args, keys=None): self.args = args self.keys = keys self.current_key_id = 0 # if the args provided, will initialize with the prompt builder for full usage self.prompt_builder = PromptBuilder(args) if args else None def prompt_row_truncate( self, prompt: str, num_rows_to_remain: int, table_end_token: str = '*/', ): """ Fit prompt into max token limits by row truncation. """ table_end_pos = prompt.rfind(table_end_token) assert table_end_pos != -1 prompt_part1, prompt_part2 = prompt[:table_end_pos], prompt[table_end_pos:] prompt_part1_lines = prompt_part1.split('\n')[::-1] trunc_line_index = None for idx, line in enumerate(prompt_part1_lines): if '\t' not in line: continue row_id = int(line.split('\t')[0]) if row_id <= num_rows_to_remain: trunc_line_index = idx break new_prompt_part1 = '\n'.join(prompt_part1_lines[trunc_line_index:][::-1]) prompt = new_prompt_part1 + '\n' + prompt_part2 return prompt def build_few_shot_prompt_from_file( self, file_path: str, n_shots: int ): """ Build few-shot prompt for generation from file. """ with open(file_path, 'r') as f: lines = f.readlines() few_shot_prompt_list = [] one_shot_prompt = '' last_line = None for line in lines: if line == '\n' and last_line == '\n': few_shot_prompt_list.append(one_shot_prompt) one_shot_prompt = '' else: one_shot_prompt += line last_line = line few_shot_prompt_list.append(one_shot_prompt) few_shot_prompt_list = few_shot_prompt_list[:n_shots] few_shot_prompt_list[-1] = few_shot_prompt_list[ -1].strip() # It is essential for prompting to remove extra '\n' few_shot_prompt = '\n'.join(few_shot_prompt_list) return few_shot_prompt def build_generate_prompt( self, data_item: Dict, generate_type: Tuple ): """ Build the generate prompt """ return self.prompt_builder.build_generate_prompt( **data_item, generate_type=generate_type ) def generate_one_pass( self, prompts: List[Tuple], verbose: bool = False ): """ Generate one pass with codex according to the generation phase. """ result_idx_to_eid = [] for p in prompts: result_idx_to_eid.extend([p[0]] * self.args.sampling_n) prompts = [p[1] for p in prompts] result = self._call_codex_api( engine=self.args.engine, prompt=prompts, max_tokens=self.args.max_generation_tokens, temperature=self.args.temperature, top_p=self.args.top_p, n=self.args.sampling_n, stop=self.args.stop_tokens ) if verbose: print('\n', '*' * 20, 'Codex API Call', '*' * 20) for prompt in prompts: print(prompt) print('\n') print('- - - - - - - - - - ->>') # parse api results response_dict = dict() for idx, g in enumerate(result['choices']): try: text = g['text'] logprob = sum(g['logprobs']['token_logprobs']) eid = result_idx_to_eid[idx] eid_pairs = response_dict.get(eid, None) if eid_pairs is None: eid_pairs = [] response_dict[eid] = eid_pairs eid_pairs.append((text, logprob)) if verbose: print(text) except ValueError as e: if verbose: print('----------- Error Msg--------') print(e) print(text) print('-----------------------------') pass return response_dict def _call_codex_api( self, engine: str, prompt: Union[str, List], max_tokens, temperature: float, top_p: float, n: int, stop: List[str] ): start_time = time.time() result = None while result is None: try: key = self.keys[self.current_key_id] self.current_key_id = (self.current_key_id + 1) % len(self.keys) print(f"Using openai api key: {key}") result = openai.Completion.create( engine=engine, prompt=prompt, api_key=key, max_tokens=max_tokens, temperature=temperature, top_p=top_p, n=n, stop=stop, logprobs=1 ) print('Openai api inference time:', time.time() - start_time) return result except Exception as e: print(e, 'Retry.') time.sleep(20) class NeuralDB(object): def __init__(self, tables: List[Dict[str, Dict]], passages=None, images=None): self.raw_tables = copy.deepcopy(tables) self.passages = {} self.images = {} self.image_captions = {} self.passage_linker = {} # The links from cell value to passage self.image_linker = {} # The links from cell value to images # Get passages if passages: for passage in passages: title, passage_content = passage['title'], passage['text'] self.passages[title] = passage_content # Get images if images: for image in images: _id, title, picture = image['id'], image['title'], image['pic'] self.images[title] = picture self.image_captions[title] = get_caption(_id) # Link grounding resources from other modalities(passages, images). if self.raw_tables[0]['table'].get('rows_with_links', None): rows = self.raw_tables[0]['table']['rows'] rows_with_links = self.raw_tables[0]['table']['rows_with_links'] link_title2cell_map = {} for row_id in range(len(rows)): for col_id in range(len(rows[row_id])): cell = rows_with_links[row_id][col_id] for text, title, url in zip(cell[0], cell[1], cell[2]): text = text.lower().strip() link_title2cell_map[title] = text # Link Passages for passage in passages: title, passage_content = passage['title'], passage['text'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.passage_linker[linked_cell] = title # Images for image in images: title, picture = image['title'], image['pic'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.image_linker[linked_cell] = title for table_info in tables: table_info['table'] = prepare_df_for_neuraldb_from_table(table_info['table']) self.tables = tables # Connect to SQLite database self.tmp_path = "tmp" os.makedirs(self.tmp_path, exist_ok=True) # self.db_path = os.path.join(self.tmp_path, '{}.db'.format(hash(time.time()))) self.db_path = os.path.join(self.tmp_path, '{}.db'.format(uuid.uuid4())) self.sqlite_conn = sqlite3.connect(self.db_path) # Create DB assert len(tables) >= 1, "DB has no table inside" table_0 = tables[0] if len(tables) > 1: raise ValueError("More than one table not support yet.") else: table_0["table"].to_sql("w", self.sqlite_conn) self.table_name = "w" self.table_title = table_0.get('title', None) # Records conn self.db = records.Database('sqlite:///{}'.format(self.db_path)) self.records_conn = self.db.get_connection() def __str__(self): return str(self.execute_query("SELECT * FROM {}".format(self.table_name))) def get_table(self, table_name=None): table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) _table = self.execute_query(sql_query) return _table def get_header(self, table_name=None): _table = self.get_table(table_name) return _table['header'] def get_rows(self, table_name): _table = self.get_table(table_name) return _table['rows'] def get_table_df(self): return self.tables[0]['table'] def get_table_raw(self): return self.raw_tables[0]['table'] def get_table_title(self): return self.tables[0]['title'] def get_passages_titles(self): return list(self.passages.keys()) def get_images_titles(self): return list(self.images.keys()) def get_passage_by_title(self, title: str): return check_in_and_return(title, self.passages) def get_image_by_title(self, title): return check_in_and_return(title, self.images) def get_image_caption_by_title(self, title): return check_in_and_return(title, self.image_captions) def get_image_linker(self): return copy.deepcopy(self.image_linker) def get_passage_linker(self): return copy.deepcopy(self.passage_linker) def execute_query(self, sql_query: str): """ Basic operation. Execute the sql query on the database we hold. """ # When the sql query is a column name (@deprecated: or a certain value with '' and "" surrounded). if len(sql_query.split(' ')) == 1 or (sql_query.startswith('`') and sql_query.endswith('`')): col_name = sql_query new_sql_query = r"SELECT row_id, {} FROM {}".format(col_name, self.table_name) # Here we use a hack that when a value is surrounded by '' or "", the sql will return a column of the value, # while for variable, no ''/"" surrounded, this sql will query for the column. out = self.records_conn.query(new_sql_query) # When the sql query wants all cols or col_id, which is no need for us to add 'row_id'. elif sql_query.lower().startswith("select *") or sql_query.startswith("select col_id"): out = self.records_conn.query(sql_query) else: try: # SELECT row_id in addition, needed for result and old table alignment. new_sql_query = "SELECT row_id, " + sql_query[7:] out = self.records_conn.query(new_sql_query) except sqlalchemy.exc.OperationalError as e: # Execute normal SQL, and in this case the row_id is actually in no need. out = self.records_conn.query(sql_query) results = out.all() unmerged_results = [] merged_results = [] headers = out.dataset.headers for i in range(len(results)): unmerged_results.append(list(results[i].values())) merged_results.extend(results[i].values()) return {"header": headers, "rows": unmerged_results} def add_sub_table(self, sub_table, table_name=None, verbose=True): """ Add sub_table into the table. """ table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) oring_table = self.execute_query(sql_query) old_table = pd.DataFrame(oring_table["rows"], columns=oring_table["header"]) # concat the new column into old table sub_table_df_normed = convert_df_type(pd.DataFrame(data=sub_table['rows'], columns=sub_table['header'])) new_table = old_table.merge(sub_table_df_normed, how='left', on='row_id') # do left join new_table.to_sql(table_name, self.sqlite_conn, if_exists='replace', index=False) if verbose: print("Insert column(s) {} (dtypes: {}) into table.\n".format(', '.join([_ for _ in sub_table['header']]), sub_table_df_normed.dtypes)) The provided code snippet includes necessary dependencies for implementing the `worker_annotate` function. Write a Python function `def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, tokenizer )` to solve the following problem: A worker process for annotating. Here is the function: def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, tokenizer ): """ A worker process for annotating. """ g_dict = dict() built_few_shot_prompts = [] for g_eid in g_eids: try: g_data_item = dataset[g_eid] g_dict[g_eid] = { 'generations': [], 'ori_data_item': copy.deepcopy(g_data_item) } db = NeuralDB( tables=[{'title': g_data_item['table']['page_title'], 'table': g_data_item['table']}] ) g_data_item['table'] = db.get_table_df() g_data_item['title'] = db.get_table_title() n_shots = args.n_shots few_shot_prompt = generator.build_few_shot_prompt_from_file( file_path=args.prompt_file, n_shots=n_shots ) generate_prompt = generator.build_generate_prompt( data_item=g_data_item, generate_type=(args.generate_type,) ) generate_prompt = generate_prompt.split('Q:',-1)[0] prompt = few_shot_prompt + "\n\n" + generate_prompt sub_q = g_data_item['sub_q'] sub_q = sub_q.strip().split('\n') q_len = len(sub_q) for idx,q in enumerate(sub_q): prompt += 'Q'+str(idx+1)+': ' +q+'\n' prompt += 'NeuralSQL1:' print(prompt) # Ensure the input length fit Codex max input tokens by shrinking the n_shots max_prompt_tokens = args.max_api_total_tokens - args.max_generation_tokens while len(tokenizer.tokenize(prompt)) >= max_prompt_tokens: # TODO: Add shrink rows n_shots -= 1 assert n_shots >= 0 few_shot_prompt = generator.build_few_shot_prompt_from_file( file_path=args.prompt_file, n_shots=n_shots ) prompt = few_shot_prompt + "\n\n" + generate_prompt print(f"Process#{pid}: Building prompt for eid#{g_eid}, original_id#{g_data_item['id']}") built_few_shot_prompts.append((g_eid, prompt)) if len(built_few_shot_prompts) < args.n_parallel_prompts: continue print(f"Process#{pid}: Prompts ready with {len(built_few_shot_prompts)} parallels. Run openai API.") response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs built_few_shot_prompts = [] except Exception as e: print(f"Process#{pid}: eid#{g_eid}, wtqid#{g_data_item['id']} generation error: {e}") # Final generation inference if len(built_few_shot_prompts) > 0: response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs return g_dict
A worker process for annotating.
165,099
import time import json import argparse import copy import os from typing import List import platform import multiprocessing from generation.generator import Generator from utils.utils import load_data_split from nsql.database import NeuralDB from utils.mmqa.qpmc import Question_Passage_Match_Classifier from utils.mmqa.qimc import Question_Image_Match_Classifier class Generator(object): """ Codex generation wrapper. """ def __init__(self, args, keys=None): self.args = args self.keys = keys self.current_key_id = 0 # if the args provided, will initialize with the prompt builder for full usage self.prompt_builder = PromptBuilder(args) if args else None def prompt_row_truncate( self, prompt: str, num_rows_to_remain: int, table_end_token: str = '*/', ): """ Fit prompt into max token limits by row truncation. """ table_end_pos = prompt.rfind(table_end_token) assert table_end_pos != -1 prompt_part1, prompt_part2 = prompt[:table_end_pos], prompt[table_end_pos:] prompt_part1_lines = prompt_part1.split('\n')[::-1] trunc_line_index = None for idx, line in enumerate(prompt_part1_lines): if '\t' not in line: continue row_id = int(line.split('\t')[0]) if row_id <= num_rows_to_remain: trunc_line_index = idx break new_prompt_part1 = '\n'.join(prompt_part1_lines[trunc_line_index:][::-1]) prompt = new_prompt_part1 + '\n' + prompt_part2 return prompt def build_few_shot_prompt_from_file( self, file_path: str, n_shots: int ): """ Build few-shot prompt for generation from file. """ with open(file_path, 'r') as f: lines = f.readlines() few_shot_prompt_list = [] one_shot_prompt = '' last_line = None for line in lines: if line == '\n' and last_line == '\n': few_shot_prompt_list.append(one_shot_prompt) one_shot_prompt = '' else: one_shot_prompt += line last_line = line few_shot_prompt_list.append(one_shot_prompt) few_shot_prompt_list = few_shot_prompt_list[:n_shots] few_shot_prompt_list[-1] = few_shot_prompt_list[ -1].strip() # It is essential for prompting to remove extra '\n' few_shot_prompt = '\n'.join(few_shot_prompt_list) return few_shot_prompt def build_generate_prompt( self, data_item: Dict, generate_type: Tuple ): """ Build the generate prompt """ return self.prompt_builder.build_generate_prompt( **data_item, generate_type=generate_type ) def generate_one_pass( self, prompts: List[Tuple], verbose: bool = False ): """ Generate one pass with codex according to the generation phase. """ result_idx_to_eid = [] for p in prompts: result_idx_to_eid.extend([p[0]] * self.args.sampling_n) prompts = [p[1] for p in prompts] result = self._call_codex_api( engine=self.args.engine, prompt=prompts, max_tokens=self.args.max_generation_tokens, temperature=self.args.temperature, top_p=self.args.top_p, n=self.args.sampling_n, stop=self.args.stop_tokens ) if verbose: print('\n', '*' * 20, 'Codex API Call', '*' * 20) for prompt in prompts: print(prompt) print('\n') print('- - - - - - - - - - ->>') # parse api results response_dict = dict() for idx, g in enumerate(result['choices']): try: text = g['text'] logprob = sum(g['logprobs']['token_logprobs']) eid = result_idx_to_eid[idx] eid_pairs = response_dict.get(eid, None) if eid_pairs is None: eid_pairs = [] response_dict[eid] = eid_pairs eid_pairs.append((text, logprob)) if verbose: print(text) except ValueError as e: if verbose: print('----------- Error Msg--------') print(e) print(text) print('-----------------------------') pass return response_dict def _call_codex_api( self, engine: str, prompt: Union[str, List], max_tokens, temperature: float, top_p: float, n: int, stop: List[str] ): start_time = time.time() result = None while result is None: try: key = self.keys[self.current_key_id] self.current_key_id = (self.current_key_id + 1) % len(self.keys) print(f"Using openai api key: {key}") result = openai.Completion.create( engine=engine, prompt=prompt, api_key=key, max_tokens=max_tokens, temperature=temperature, top_p=top_p, n=n, stop=stop, logprobs=1 ) print('Openai api inference time:', time.time() - start_time) return result except Exception as e: print(e, 'Retry.') time.sleep(20) class NeuralDB(object): def __init__(self, tables: List[Dict[str, Dict]], passages=None, images=None): self.raw_tables = copy.deepcopy(tables) self.passages = {} self.images = {} self.image_captions = {} self.passage_linker = {} # The links from cell value to passage self.image_linker = {} # The links from cell value to images # Get passages if passages: for passage in passages: title, passage_content = passage['title'], passage['text'] self.passages[title] = passage_content # Get images if images: for image in images: _id, title, picture = image['id'], image['title'], image['pic'] self.images[title] = picture self.image_captions[title] = get_caption(_id) # Link grounding resources from other modalities(passages, images). if self.raw_tables[0]['table'].get('rows_with_links', None): rows = self.raw_tables[0]['table']['rows'] rows_with_links = self.raw_tables[0]['table']['rows_with_links'] link_title2cell_map = {} for row_id in range(len(rows)): for col_id in range(len(rows[row_id])): cell = rows_with_links[row_id][col_id] for text, title, url in zip(cell[0], cell[1], cell[2]): text = text.lower().strip() link_title2cell_map[title] = text # Link Passages for passage in passages: title, passage_content = passage['title'], passage['text'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.passage_linker[linked_cell] = title # Images for image in images: title, picture = image['title'], image['pic'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.image_linker[linked_cell] = title for table_info in tables: table_info['table'] = prepare_df_for_neuraldb_from_table(table_info['table']) self.tables = tables # Connect to SQLite database self.tmp_path = "tmp" os.makedirs(self.tmp_path, exist_ok=True) # self.db_path = os.path.join(self.tmp_path, '{}.db'.format(hash(time.time()))) self.db_path = os.path.join(self.tmp_path, '{}.db'.format(uuid.uuid4())) self.sqlite_conn = sqlite3.connect(self.db_path) # Create DB assert len(tables) >= 1, "DB has no table inside" table_0 = tables[0] if len(tables) > 1: raise ValueError("More than one table not support yet.") else: table_0["table"].to_sql("w", self.sqlite_conn) self.table_name = "w" self.table_title = table_0.get('title', None) # Records conn self.db = records.Database('sqlite:///{}'.format(self.db_path)) self.records_conn = self.db.get_connection() def __str__(self): return str(self.execute_query("SELECT * FROM {}".format(self.table_name))) def get_table(self, table_name=None): table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) _table = self.execute_query(sql_query) return _table def get_header(self, table_name=None): _table = self.get_table(table_name) return _table['header'] def get_rows(self, table_name): _table = self.get_table(table_name) return _table['rows'] def get_table_df(self): return self.tables[0]['table'] def get_table_raw(self): return self.raw_tables[0]['table'] def get_table_title(self): return self.tables[0]['title'] def get_passages_titles(self): return list(self.passages.keys()) def get_images_titles(self): return list(self.images.keys()) def get_passage_by_title(self, title: str): return check_in_and_return(title, self.passages) def get_image_by_title(self, title): return check_in_and_return(title, self.images) def get_image_caption_by_title(self, title): return check_in_and_return(title, self.image_captions) def get_image_linker(self): return copy.deepcopy(self.image_linker) def get_passage_linker(self): return copy.deepcopy(self.passage_linker) def execute_query(self, sql_query: str): """ Basic operation. Execute the sql query on the database we hold. """ # When the sql query is a column name (@deprecated: or a certain value with '' and "" surrounded). if len(sql_query.split(' ')) == 1 or (sql_query.startswith('`') and sql_query.endswith('`')): col_name = sql_query new_sql_query = r"SELECT row_id, {} FROM {}".format(col_name, self.table_name) # Here we use a hack that when a value is surrounded by '' or "", the sql will return a column of the value, # while for variable, no ''/"" surrounded, this sql will query for the column. out = self.records_conn.query(new_sql_query) # When the sql query wants all cols or col_id, which is no need for us to add 'row_id'. elif sql_query.lower().startswith("select *") or sql_query.startswith("select col_id"): out = self.records_conn.query(sql_query) else: try: # SELECT row_id in addition, needed for result and old table alignment. new_sql_query = "SELECT row_id, " + sql_query[7:] out = self.records_conn.query(new_sql_query) except sqlalchemy.exc.OperationalError as e: # Execute normal SQL, and in this case the row_id is actually in no need. out = self.records_conn.query(sql_query) results = out.all() unmerged_results = [] merged_results = [] headers = out.dataset.headers for i in range(len(results)): unmerged_results.append(list(results[i].values())) merged_results.extend(results[i].values()) return {"header": headers, "rows": unmerged_results} def add_sub_table(self, sub_table, table_name=None, verbose=True): """ Add sub_table into the table. """ table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) oring_table = self.execute_query(sql_query) old_table = pd.DataFrame(oring_table["rows"], columns=oring_table["header"]) # concat the new column into old table sub_table_df_normed = convert_df_type(pd.DataFrame(data=sub_table['rows'], columns=sub_table['header'])) new_table = old_table.merge(sub_table_df_normed, how='left', on='row_id') # do left join new_table.to_sql(table_name, self.sqlite_conn, if_exists='replace', index=False) if verbose: print("Insert column(s) {} (dtypes: {}) into table.\n".format(', '.join([_ for _ in sub_table['header']]), sub_table_df_normed.dtypes)) The provided code snippet includes necessary dependencies for implementing the `worker_annotate` function. Write a Python function `def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, tokenizer )` to solve the following problem: A worker process for annotating. Here is the function: def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, tokenizer ): """ A worker process for annotating. """ qpmc = Question_Passage_Match_Classifier() qimc = Question_Image_Match_Classifier() g_dict = dict() built_few_shot_prompts = [] for g_eid in g_eids: try: g_data_item = dataset[g_eid] g_dict[g_eid] = { 'generations': dict(), 'ori_data_item': copy.deepcopy(g_data_item) } table = g_data_item['table'] header, rows, rows_with_links = table['header'][0], table['rows'][0], table['rows_with_links'][0] if args.prompt_style == "create_table_select_3_full_table_w_all_passage_image": # Get the retrieved passages & images and re-assign to the neuraldb, # then when running "xxxaxllxxx" prompt_style, it will only show the retrieved parts # Get the retrieved passages new_passages = {"id": [], "title": [], "text": [], "url": []} for _id, title, text, url in zip(g_data_item['passages']['id'], g_data_item['passages']['title'], g_data_item['passages']['text'], g_data_item['passages']['url']): if qpmc.judge_match(question=g_data_item['question'], passage=text): new_passages["id"].append(_id) new_passages["title"].append(title) new_passages["text"].append(text) new_passages["url"].append(url) g_data_item['passages'] = new_passages # Get the retrieved images new_images = {"id": [], "title": [], "pic": [], "url": [], "path": []} for _id, title, pic, url, path in zip(g_data_item['images']['id'], g_data_item['images']['title'], g_data_item['images']['pic'], g_data_item['images']['url'], g_data_item['images']['path']): if qimc.judge_match(g_data_item['id'], g_data_item['question'], pic): new_images["id"].append(_id) new_images["title"].append(title) new_images["pic"].append(pic) new_images["url"].append(url) new_images["path"].append(path) g_data_item['images'] = new_images else: assert args.prompt_style == "create_table_select_3_full_table_w_gold_passage_image" db = NeuralDB([{ "title": "{} ({})".format(table['title'][0], table['caption'][0]), "table": {"header": header, "rows": rows, "rows_with_links": rows_with_links} }], passages=[{"id": _id, "title": title, "text": text} for _id, title, text in zip(g_data_item['passages']['id'], g_data_item['passages']['title'], g_data_item['passages']['text'])], images=[{"id": _id, "title": title, "pic": pic} for _id, title, pic in zip(g_data_item['images']['id'], g_data_item['images']['title'], g_data_item['images']['pic'])]) g_data_item['table'] = db.get_table_df() g_data_item['title'] = db.get_table_title() n_shots = args.n_shots few_shot_prompt = generator.build_few_shot_prompt_from_file( file_path=args.prompt_file, n_shots=n_shots ) generate_prompt = generator.build_generate_prompt( data_item=g_data_item, generate_type=(args.generate_type,) ) prompt = few_shot_prompt + "\n\n" + generate_prompt # Ensure the input length fit Codex max input tokens by shrinking the n_shots max_prompt_tokens = args.max_api_total_tokens - args.max_generation_tokens while len(tokenizer.tokenize(prompt)) >= max_prompt_tokens: # TODO: Add shrink rows n_shots -= 1 assert n_shots >= 0 few_shot_prompt = generator.build_few_shot_prompt_from_file( file_path=args.prompt_file, n_shots=n_shots ) prompt = few_shot_prompt + "\n\n" + generate_prompt print(f"Process#{pid}: Building prompt for eid#{g_eid}, original_id#{g_data_item['id']}") built_few_shot_prompts.append((g_eid, prompt)) if len(built_few_shot_prompts) < args.n_parallel_prompts: continue print(f"Process#{pid}: Prompts ready with {len(built_few_shot_prompts)} parallels. Run openai API.") response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs built_few_shot_prompts = [] except Exception as e: print(f"Process#{pid}: eid#{g_eid}, wtqid#{g_data_item['id']} generation error: {e}") # Final generation inference if len(built_few_shot_prompts) > 0: response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs return g_dict
A worker process for annotating.
165,100
import json import argparse import platform, multiprocessing import os import time from nsql.nsql_exec import Executor, NeuralDB from utils.normalizer import post_process_sql from utils.utils import load_data_split, majority_vote from utils.evaluator import Evaluator class Executor(object): def __init__(self, args, keys=None): self.new_col_name_id = 0 self.qa_model = OpenAIQAModel(args, keys) def generate_new_col_names(self, number): col_names = ["col_{}".format(i) for i in range(self.new_col_name_id, self.new_col_name_id + number)] self.new_col_name_id += number return col_names def sql_exec(self, sql: str, db: NeuralDB, verbose=True): if verbose: print("Exec SQL '{}' with additional row_id on {}".format(sql, db)) result = db.execute_query(sql) return result def nsql_exec(self, nsql: str, db: NeuralDB, verbose=True): steps = [] root_node = get_cfg_tree(nsql) # Parse execution tree from nsql. get_steps(root_node, steps) # Flatten the execution tree and get the steps. steps = remove_duplicate(steps) # Remove the duplicate steps. if verbose: print("Steps:", [s.rename for s in steps]) col_idx = 0 for step in steps: # All steps should be formatted as 'QA()' except for last step which could also be normal SQL. assert isinstance(step, TreeNode), "step must be treenode" nsql = step.rename if nsql.startswith('QA('): question, sql_s = parse_question_paras(nsql, self.qa_model) sql_executed_sub_tables = [] # Execute all SQLs and get the results as parameters for sql_item in sql_s: role, sql_item = nsql_role_recognize(sql_item, db.get_header(), db.get_passages_titles(), db.get_images_titles()) if role in ['col', 'complete_sql']: sql_executed_sub_table = self.sql_exec(sql_item, db, verbose=verbose) sql_executed_sub_tables.append(sql_executed_sub_table) elif role == 'val': val = eval(sql_item) sql_executed_sub_tables.append({ "header": ["row_id", "val"], "rows": [["0", val]] }) elif role == 'passage_title_and_image_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_passage_by_title(sql_item) + db.get_image_caption_by_title(sql_item) # "{} (The answer of '{}' is {})".format( # sql_item, # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(sql_item))) ]] }) elif role == 'passage_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_passage_by_title(sql_item)]] }) elif role == 'image_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_image_caption_by_title(sql_item)]], # "rows": [["0", "{} (The answer of '{}' is {})".format( # sql_item, # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(sql_item)))]], }) # If the sub_tables to execute with link, append it to the cell. passage_linker = db.get_passage_linker() image_linker = db.get_image_linker() for _sql_executed_sub_table in sql_executed_sub_tables: for i in range(len(_sql_executed_sub_table['rows'])): for j in range(len(_sql_executed_sub_table['rows'][i])): _cell = _sql_executed_sub_table['rows'][i][j] if _cell in passage_linker.keys(): _sql_executed_sub_table['rows'][i][j] += " ({})".format( # Add passage text as backup info db.get_passage_by_title(passage_linker[_cell])) if _cell in image_linker.keys(): _sql_executed_sub_table['rows'][i][j] += " ({})".format( # Add image caption as backup info db.get_image_caption_by_title(image_linker[_cell])) # _sql_executed_sub_table['rows'][i][j] += " (The answer of '{}' is {})".format( # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(image_linker[_cell]))) pass if question.lower().startswith("map@"): # When the question is a type of mapping, we return the mapped column. question = question[len("map@"):] if step.father: step.rename_father_col(col_idx=col_idx) sub_table: Dict = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="map", new_col_name_s=step.produced_col_name_s, verbose=verbose) db.add_sub_table(sub_table, verbose=verbose) col_idx += 1 else: # This step is the final step sub_table: Dict = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="map", new_col_name_s=["col_{}".format(col_idx)], verbose=verbose) return extract_answers(sub_table) elif question.lower().startswith("ans@"): # When the question is a type of answering, we return an answer list. question = question[len("ans@"):] answer: List = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="ans", verbose=verbose) if step.father: step.rename_father_val(answer) else: # This step is the final step return answer else: raise ValueError( "Except for operators or NL question must start with 'map@' or 'ans@'!, check '{}'".format( question)) else: sub_table = self.sql_exec(nsql, db, verbose=verbose) return extract_answers(sub_table) def post_process_sql(sql_str, df, table_title=None, process_program_with_fuzzy_match_on_db=True, verbose=False): """Post process SQL: including basic fix and further fuzzy match on cell and SQL to process""" def basic_fix(sql_str, all_headers, table_title=None): def finditer(sub_str: str, mother_str: str): result = [] start_index = 0 while True: start_index = mother_str.find(sub_str, start_index, -1) if start_index == -1: break end_idx = start_index + len(sub_str) result.append((start_index, end_idx)) start_index = end_idx return result if table_title: sql_str = sql_str.replace("FROM " + table_title, "FROM w") sql_str = sql_str.replace("FROM " + table_title.lower(), "FROM w") """Case 1: Fix the `` missing. """ # Remove the null header. while '' in all_headers: all_headers.remove('') # Remove the '\n' in header. # This is because the WikiTQ won't actually show the str in two lines, # they use '\n' to mean that, and display it in the same line when print. sql_str = sql_str.replace("\\n", "\n") sql_str = sql_str.replace("\n", "\\n") # Add `` in SQL. all_headers.sort(key=lambda x: len(x), reverse=True) have_matched = [0 for i in range(len(sql_str))] # match quotation idx_s_single_quotation = [_ for _ in range(1, len(sql_str)) if sql_str[_] in ["\'"] and sql_str[_ - 1] not in ["\'"]] idx_s_double_quotation = [_ for _ in range(1, len(sql_str)) if sql_str[_] in ["\""] and sql_str[_ - 1] not in ["\""]] for idx_s in [idx_s_single_quotation, idx_s_double_quotation]: if len(idx_s) % 2 == 0: for idx in range(int(len(idx_s) / 2)): start_idx = idx_s[idx * 2] end_idx = idx_s[idx * 2 + 1] have_matched[start_idx: end_idx] = [2 for _ in range(end_idx - start_idx)] # match headers for header in all_headers: if (header in sql_str) and (header not in ALL_KEY_WORDS): all_matched_of_this_header = finditer(header, sql_str) for matched_of_this_header in all_matched_of_this_header: start_idx, end_idx = matched_of_this_header if all(have_matched[start_idx: end_idx]) == 0 and (not sql_str[start_idx - 1] == "`") and ( not sql_str[end_idx] == "`"): have_matched[start_idx: end_idx] = [1 for _ in range(end_idx - start_idx)] # a bit ugly, but anyway. # re-compose sql from the matched idx. start_have_matched = [0] + have_matched end_have_matched = have_matched + [0] start_idx_s = [idx - 1 for idx in range(1, len(start_have_matched)) if start_have_matched[idx - 1] == 0 and start_have_matched[idx] == 1] end_idx_s = [idx for idx in range(len(end_have_matched) - 1) if end_have_matched[idx] == 1 and end_have_matched[idx + 1] == 0] assert len(start_idx_s) == len(end_idx_s) spans = [] current_idx = 0 for start_idx, end_idx in zip(start_idx_s, end_idx_s): spans.append(sql_str[current_idx:start_idx]) spans.append(sql_str[start_idx:end_idx + 1]) current_idx = end_idx + 1 spans.append(sql_str[current_idx:]) sql_str = '`'.join(spans) return sql_str def fuzzy_match_process(sql_str, df, verbose=False): """ Post-process SQL by fuzzy matching value with table contents. """ def _get_matched_cells(value_str, df, fuzz_threshold=70): """ Get matched table cells with value token. """ matched_cells = [] for row_id, row in df.iterrows(): for cell in row: cell = str(cell) fuzz_score = fuzz.ratio(value_str, cell) if fuzz_score == 100: matched_cells = [(cell, fuzz_score)] return matched_cells if fuzz_score >= fuzz_threshold: matched_cells.append((cell, fuzz_score)) matched_cells = sorted(matched_cells, key=lambda x: x[1], reverse=True) return matched_cells def _check_valid_fuzzy_match(value_str, matched_cell): """ Check if the fuzzy match is valid, now considering: 1. The number/date should not be disturbed, but adding new number or deleting number is valid. """ number_pattern = "[+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?" numbers_in_value = re.findall(number_pattern, value_str) numbers_in_matched_cell = re.findall(number_pattern, matched_cell) try: numbers_in_value = [float(num.replace(',', '')) for num in numbers_in_value] except: print(f"Can't convert number string {numbers_in_value} into float in _check_valid_fuzzy_match().") try: numbers_in_matched_cell = [float(num.replace(',', '')) for num in numbers_in_matched_cell] except: print( f"Can't convert number string {numbers_in_matched_cell} into float in _check_valid_fuzzy_match().") numbers_in_value = set(numbers_in_value) numbers_in_matched_cell = set(numbers_in_matched_cell) if numbers_in_value.issubset(numbers_in_matched_cell) or numbers_in_matched_cell.issubset(numbers_in_value): return True else: return False # Drop trailing '\n```', a pattern that may appear in Codex SQL generation sql_str = sql_str.rstrip('```').rstrip('\n') # Replace QA module with placeholder qa_pattern = "QA\(.+?;.*?`.+?`.*?\)" qas = re.findall(qa_pattern, sql_str) for idx, qa in enumerate(qas): sql_str = sql_str.replace(qa, f"placeholder{idx}") # Parse and replace SQL value with table contents sql_tokens = tokenize(sql_str) sql_template_tokens = extract_partial_template_from_sql(sql_str) # Fix 'between' keyword bug in parsing templates fixed_sql_template_tokens = [] sql_tok_bias = 0 for idx, sql_templ_tok in enumerate(sql_template_tokens): sql_tok = sql_tokens[idx + sql_tok_bias] if sql_tok == 'between' and sql_templ_tok == '[WHERE_OP]': fixed_sql_template_tokens.extend(['[WHERE_OP]', '[VALUE]', 'and']) sql_tok_bias += 2 # pass '[VALUE]', 'and' else: fixed_sql_template_tokens.append(sql_templ_tok) sql_template_tokens = fixed_sql_template_tokens for idx, tok in enumerate(sql_tokens): if tok in ALL_KEY_WORDS: sql_tokens[idx] = tok.upper() if verbose: print(sql_tokens) print(sql_template_tokens) assert len(sql_tokens) == len(sql_template_tokens) value_indices = [idx for idx in range(len(sql_template_tokens)) if sql_template_tokens[idx] == '[VALUE]'] for value_idx in value_indices: # Skip the value if the where condition column is QA module if value_idx >= 2 and sql_tokens[value_idx - 2].startswith('placeholder'): continue value_str = sql_tokens[value_idx] # Drop \"\" for fuzzy match is_string = False if value_str[0] == "\"" and value_str[-1] == "\"": value_str = value_str[1:-1] is_string = True # If already fuzzy match, skip if value_str[0] == '%' or value_str[-1] == '%': continue value_str = value_str.lower() # Fuzzy Match matched_cells = _get_matched_cells(value_str, df) if verbose: print(matched_cells) new_value_str = value_str if matched_cells: # new_value_str = matched_cells[0][0] for matched_cell, fuzz_score in matched_cells: if _check_valid_fuzzy_match(value_str, matched_cell): new_value_str = matched_cell if verbose and new_value_str != value_str: print("\tfuzzy match replacing!", value_str, '->', matched_cell, f'fuzz_score:{fuzz_score}') break if is_string: new_value_str = f"\"{new_value_str}\"" sql_tokens[value_idx] = new_value_str # Compose new sql string # Clean column name in SQL since columns may have been tokenized in the postprocessing, e.g., (ppp) -> ( ppp ) new_sql_str = ' '.join(sql_tokens) sql_columns = re.findall('`\s(.*?)\s`', new_sql_str) for sql_col in sql_columns: matched_columns = [] for col in df.columns: score = fuzz.ratio(sql_col.lower(), col) if score == 100: matched_columns = [(col, score)] break if score >= 80: matched_columns.append((col, score)) matched_columns = sorted(matched_columns, key=lambda x: x[1], reverse=True) if matched_columns: matched_col = matched_columns[0][0] new_sql_str = new_sql_str.replace(f"` {sql_col} `", f"`{matched_col}`") else: new_sql_str = new_sql_str.replace(f"` {sql_col} `", f"`{sql_col}`") # Restore QA modules for idx, qa in enumerate(qas): new_sql_str = new_sql_str.replace(f"placeholder{idx}", qa) # Fix '<>' when composing the new sql new_sql_str = new_sql_str.replace('< >', '<>') return new_sql_str sql_str = basic_fix(sql_str, list(df.columns), table_title) if process_program_with_fuzzy_match_on_db: try: sql_str = fuzzy_match_process(sql_str, df, verbose) except: pass return sql_str def majority_vote( nsqls: List, pred_answer_list: List, allow_none_and_empty_answer: bool = False, allow_error_answer: bool = False, answer_placeholder: Union[str, int] = '<error|empty>', vote_method: str = 'prob', answer_biased: Union[str, int] = None, answer_biased_weight: float = None, ): """ Determine the final nsql execution answer by majority vote. """ def _compare_answer_vote_simple(a, b): """ First compare occur times. If equal, then compare max nsql logprob. """ if a[1]['count'] > b[1]['count']: return 1 elif a[1]['count'] < b[1]['count']: return -1 else: if a[1]['nsqls'][0][1] > b[1]['nsqls'][0][1]: return 1 elif a[1]['nsqls'][0][1] == b[1]['nsqls'][0][1]: return 0 else: return -1 def _compare_answer_vote_with_prob(a, b): """ Compare prob sum. """ return 1 if sum([math.exp(nsql[1]) for nsql in a[1]['nsqls']]) > sum( [math.exp(nsql[1]) for nsql in b[1]['nsqls']]) else -1 # Vote answers candi_answer_dict = dict() for (nsql, logprob), pred_answer in zip(nsqls, pred_answer_list): if allow_none_and_empty_answer: if pred_answer == [None] or pred_answer == []: pred_answer = [answer_placeholder] if allow_error_answer: if pred_answer == '<error>': pred_answer = [answer_placeholder] # Invalid execution results if pred_answer == '<error>' or pred_answer == [None] or pred_answer == []: continue if candi_answer_dict.get(tuple(pred_answer), None) is None: candi_answer_dict[tuple(pred_answer)] = { 'count': 0, 'nsqls': [] } answer_info = candi_answer_dict.get(tuple(pred_answer), None) answer_info['count'] += 1 answer_info['nsqls'].append([nsql, logprob]) # All candidates execution errors if len(candi_answer_dict) == 0: return answer_placeholder, [(nsqls[0][0], nsqls[0][-1])] # Sort if vote_method == 'simple': sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_simple), reverse=True) elif vote_method == 'prob': sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_with_prob), reverse=True) elif vote_method == 'answer_biased': # Specifically for Tabfact entailed answer, i.e., `1`. # If there exists nsql that produces `1`, we consider it more significant because `0` is very common. assert answer_biased_weight is not None and answer_biased_weight > 0 for answer, answer_dict in candi_answer_dict.items(): if answer == (answer_biased,): answer_dict['count'] *= answer_biased_weight sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_simple), reverse=True) elif vote_method == 'lf_biased': # Assign weights to different types of logic forms (lf) to control interpretability and coverage for answer, answer_dict in candi_answer_dict.items(): count = 0 for nsql, _ in answer_dict['nsqls']: if 'map@' in nsql: count += 10 elif 'ans@' in nsql: count += 10 else: count += 1 answer_dict['count'] = count sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_simple), reverse=True) else: raise ValueError(f"Vote method {vote_method} is not supported.") pred_answer_info = sorted_candi_answer_list[0] pred_answer, pred_answer_nsqls = list(pred_answer_info[0]), pred_answer_info[1]['nsqls'] return pred_answer, pred_answer_nsqls class Evaluator(): def __init__(self, transition_system, table_path='data/tables.json', database_dir='data/database'): super(Evaluator, self).__init__() self.transition_system = transition_system self.kmaps = build_foreign_key_map_from_json(table_path) self.database_dir = database_dir self.engine = Engine() self.checker = Checker(table_path, database_dir) self.acc_dict = { "sql": self.sql_acc, # use golden sql as references "ast": self.ast_acc, # compare ast accuracy, ast may be incorrect when constructed from raw sql "beam": self.beam_acc, # if the correct answer exist in the beam, assume the result is true } def acc(self, pred_hyps, dataset, output_path=None, acc_type='sql', etype='match', use_checker=False): assert len(pred_hyps) == len(dataset) and acc_type in self.acc_dict and etype in ['match', 'exec'] acc_method = self.acc_dict[acc_type] return acc_method(pred_hyps, dataset, output_path, etype, use_checker) def beam_acc(self, pred_hyps, dataset, output_path, etype, use_checker): scores, results = {}, [] for each in ['easy', 'medium', 'hard', 'extra', 'all']: scores[each] = [0, 0.] # first is count, second is total score for idx, pred in enumerate(pred_hyps): question, gold_sql, db = dataset[idx].ex['question'], dataset[idx].query, dataset[idx].db for b_id, hyp in enumerate(pred): pred_sql = self.transition_system.ast_to_surface_code(hyp.tree, db) score, hardness = self.single_acc(pred_sql, gold_sql, db['db_id'], etype) if int(score) == 1: scores[hardness][0] += 1 scores[hardness][1] += 1.0 scores['all'][0] += 1 scores['all'][1] += 1.0 results.append((hardness, question, gold_sql, pred_sql, b_id, True)) break else: scores[hardness][0] += 1 scores['all'][0] += 1 pred_sql = self.transition_system.ast_to_surface_code(pred[0].tree, db) results.append((hardness, question, gold_sql, pred_sql, 0, False)) for each in scores: accuracy = scores[each][1] / float(scores[each][0]) if scores[each][0] != 0 else 0. scores[each].append(accuracy) of = open(output_path, 'w', encoding='utf8') if output_path is not None else \ tempfile.TemporaryFile('w+t') for item in results: of.write('Level: %s\n' % (item[0])) of.write('Question: %s\n' % (item[1])) of.write('Gold SQL: %s\n' %(item[2])) of.write('Pred SQL (%s): %s\n' % (item[4], item[3])) of.write('Correct: %s\n\n' % (item[5])) for each in scores: of.write('Level %s: %s\n' % (each, scores[each])) of.close() return scores['all'][2] def single_acc(self, pred_sql, gold_sql, db, etype): """ score(float): 0 or 1, etype score hardness(str): one of 'easy', 'medium', 'hard', 'extra' """ db_name = db db = os.path.join(self.database_dir, db, db + ".sqlite") schema = Schema(get_schema(db)) g_sql = get_sql(schema, gold_sql) hardness = self.engine.eval_hardness(g_sql) try: p_sql = get_sql(schema, pred_sql) except: # If p_sql is not valid, then we will use an empty sql to evaluate with the correct sql p_sql = { "except": None, "from": { "conds": [], "table_units": [] }, "groupBy": [], "having": [], "intersect": None, "limit": None, "orderBy": [], "select": [ False, [] ], "union": None, "where": [] } kmap = self.kmaps[db_name] g_valid_col_units = build_valid_col_units(g_sql['from']['table_units'], schema) g_sql = rebuild_sql_val(g_sql) g_sql = rebuild_sql_col(g_valid_col_units, g_sql, kmap) # kmap: map __tab.col__ to pivot __tab.col__ p_valid_col_units = build_valid_col_units(p_sql['from']['table_units'], schema) p_sql = rebuild_sql_val(p_sql) p_sql = rebuild_sql_col(p_valid_col_units, p_sql, kmap) if etype == 'exec': score = float(eval_exec_match(db, pred_sql, gold_sql, p_sql, g_sql)) if etype == 'match': score = float(self.engine.eval_exact_match(p_sql, g_sql)) return score, hardness def ast_acc(self, pred_hyps, dataset, output_path, etype, use_checker): pred_asts = [hyp[0].tree for hyp in pred_hyps] ref_asts = [ex.ast for ex in dataset] dbs = [ex.db for ex in dataset] pred_sqls, ref_sqls = [], [] for pred, ref, db in zip(pred_asts, ref_asts, dbs): pred_sql = self.transition_system.ast_to_surface_code(pred, db) ref_sql = self.transition_system.ast_to_surface_code(ref, db) pred_sqls.append(pred_sql) ref_sqls.append(ref_sql) with tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_pred, \ tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_ref: of = open(output_path, 'w', encoding='utf8') if output_path is not None \ else tempfile.TemporaryFile('w+t') # write pred and ref sqls for s in pred_sqls: tmp_pred.write(s + '\n') tmp_pred.flush() for s, db in zip(ref_sqls, dbs): tmp_ref.write(s + '\t' + db['db_id'] + '\n') tmp_ref.flush() # calculate ast accuracy old_print = sys.stdout sys.stdout = of result_type = 'exact' if etype == 'match' else 'exec' all_exact_acc = evaluate(tmp_ref.name, tmp_pred.name, self.database_dir, etype, self.kmaps)['all'][result_type] sys.stdout = old_print of.close() return float(all_exact_acc) def sql_acc(self, pred_hyps, dataset, output_path, etype, use_checker): pred_sqls, ref_sqls = [], [ex.query for ex in dataset] dbs = [ex.db for ex in dataset] for idx, hyp in enumerate(pred_hyps): if use_checker: pred_sql = self.obtain_sql(hyp, dbs[idx]) else: best_ast = hyp[0].tree # by default, the top beam prediction pred_sql = self.transition_system.ast_to_surface_code(best_ast, dbs[idx]) pred_sqls.append(pred_sql) with tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_pred, \ tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_ref: of = open(output_path, 'w', encoding='utf8') if output_path is not None \ else tempfile.TemporaryFile('w+t') # write pred and ref sqls for s in pred_sqls: tmp_pred.write(s + '\n') tmp_pred.flush() for s, db in zip(ref_sqls, dbs): tmp_ref.write(s + '\t' + db['db_id'] + '\n') tmp_ref.flush() # calculate sql accuracy old_print = sys.stdout sys.stdout = of result_type = 'exact' if etype == 'match' else 'exec' all_exact_acc = evaluate(tmp_ref.name, tmp_pred.name, self.database_dir, etype, self.kmaps)['all'][result_type] sys.stdout = old_print of.close() return float(all_exact_acc) def obtain_sql(self, hyps, db): beam = len(hyps) for hyp in hyps: cur_ast = hyp.tree pred_sql = self.transition_system.ast_to_surface_code(cur_ast, db) if self.checker.validity_check(pred_sql, db['db_id']): sql = pred_sql break else: best_ast = hyps[0].tree sql = self.transition_system.ast_to_surface_code(best_ast, db) return sql The provided code snippet includes necessary dependencies for implementing the `worker_execute` function. Write a Python function `def worker_execute( pid, args, dataset, nsql_dict, keys )` to solve the following problem: A worker process for execution. Here is the function: def worker_execute( pid, args, dataset, nsql_dict, keys ): """ A worker process for execution. """ result_dict = dict() n_total_samples, n_correct_samples = 0, 0 for eid, data_item in enumerate(dataset): eid = str(eid) if eid not in nsql_dict: continue print(f"Process#{pid}: eid {eid}, wtq-id {data_item['id']}") result_dict[eid] = dict() result_dict[eid]['question'] = data_item['question'] result_dict[eid]['gold_answer'] = data_item['answer_text'].split(" | ") n_total_samples += 1 # Load table table = data_item['table'] header, rows, rows_with_links = table['header'][0], table['rows'][0], table['rows_with_links'][0] title = table['title'][0] executor = Executor(args, keys) # Execute exec_answer_list = [] nsql_exec_answer_dict = dict() for idx, (nsql, logprob) in enumerate(nsql_dict[eid]['nsqls']): print(f"Process#{pid}: eid {eid}, original_id {data_item['id']}, executing program#{idx}, logprob={logprob}") try: if nsql in nsql_exec_answer_dict: exec_answer = nsql_exec_answer_dict[nsql] else: db = NeuralDB([{ "title": "{} ({})".format(table['title'][0], table['caption'][0]), "table": {"header": header, "rows": rows, "rows_with_links": rows_with_links} }], passages=[{"id": _id, "title": title, "text": text} for _id, title, text in zip(data_item['passages']['id'], data_item['passages']['title'], data_item['passages']['text'])], images=[{"id": _id, "title": title, "pic": pic} for _id, title, pic in zip(data_item['images']['id'], data_item['images']['title'], data_item['images']['pic'])]) nsql = post_process_sql( sql_str=nsql, df=db.get_table_df(), process_program_with_fuzzy_match_on_db=args.process_program_with_fuzzy_match_on_db, table_title=title ) exec_answer = executor.nsql_exec(nsql, db, verbose=args.verbose) if isinstance(exec_answer, str): exec_answer = [exec_answer] nsql_exec_answer_dict[nsql] = exec_answer exec_answer_list.append(exec_answer) except Exception as e: print(f"Process#{pid}: Execution error {e}") exec_answer = '<error>' exec_answer_list.append(exec_answer) # Store tmp execution answers if nsql_dict[eid].get('exec_answers', None) is None: nsql_dict[eid]['exec_answers'] = [] nsql_dict[eid]['exec_answers'].append(exec_answer) # Majority vote to determine the final prediction answer pred_answer, pred_answer_nsqls = majority_vote( nsqls=nsql_dict[eid]['nsqls'], pred_answer_list=exec_answer_list, allow_none_and_empty_answer=args.allow_none_and_empty_answer, answer_placeholder=args.answer_placeholder, vote_method=args.vote_method, answer_biased=args.answer_biased, answer_biased_weight=args.answer_biased_weight ) # Evaluate result_dict[eid]['pred_answer'] = pred_answer result_dict[eid]['nsql'] = pred_answer_nsqls gold_answer = data_item['answer_text'].split(" | ") score = Evaluator().evaluate( pred_answer, gold_answer, dataset=args.dataset, question=result_dict[eid]['question'] ) n_correct_samples += score print(f'Process#{pid}: pred answer: {pred_answer}') print(f'Process#{pid}: gold answer: {gold_answer}') if score == 1: print(f'Process#{pid}: Correct!') else: print(f'Process#{pid}: Wrong.') print(f'Process#{pid}: Accuracy: {n_correct_samples}/{n_total_samples}') return result_dict
A worker process for execution.
165,101
import time import json import argparse import copy import os from typing import List import platform import multiprocessing import pandas as pd from generation.generator import Generator from utils.utils import load_data_split from nsql.database import NeuralDB ROOT_DIR = os.path.join(os.path.dirname(__file__), "../../") class Generator(object): """ Codex generation wrapper. """ def __init__(self, args, keys=None): self.args = args self.keys = keys self.current_key_id = 0 # if the args provided, will initialize with the prompt builder for full usage self.prompt_builder = PromptBuilder(args) if args else None def prompt_row_truncate( self, prompt: str, num_rows_to_remain: int, table_end_token: str = '*/', ): """ Fit prompt into max token limits by row truncation. """ table_end_pos = prompt.rfind(table_end_token) assert table_end_pos != -1 prompt_part1, prompt_part2 = prompt[:table_end_pos], prompt[table_end_pos:] prompt_part1_lines = prompt_part1.split('\n')[::-1] trunc_line_index = None for idx, line in enumerate(prompt_part1_lines): if '\t' not in line: continue row_id = int(line.split('\t')[0]) if row_id <= num_rows_to_remain: trunc_line_index = idx break new_prompt_part1 = '\n'.join(prompt_part1_lines[trunc_line_index:][::-1]) prompt = new_prompt_part1 + '\n' + prompt_part2 return prompt def build_few_shot_prompt_from_file( self, file_path: str, n_shots: int ): """ Build few-shot prompt for generation from file. """ with open(file_path, 'r') as f: lines = f.readlines() few_shot_prompt_list = [] one_shot_prompt = '' last_line = None for line in lines: if line == '\n' and last_line == '\n': few_shot_prompt_list.append(one_shot_prompt) one_shot_prompt = '' else: one_shot_prompt += line last_line = line few_shot_prompt_list.append(one_shot_prompt) few_shot_prompt_list = few_shot_prompt_list[:n_shots] few_shot_prompt_list[-1] = few_shot_prompt_list[ -1].strip() # It is essential for prompting to remove extra '\n' few_shot_prompt = '\n'.join(few_shot_prompt_list) return few_shot_prompt def build_generate_prompt( self, data_item: Dict, generate_type: Tuple ): """ Build the generate prompt """ return self.prompt_builder.build_generate_prompt( **data_item, generate_type=generate_type ) def generate_one_pass( self, prompts: List[Tuple], verbose: bool = False ): """ Generate one pass with codex according to the generation phase. """ result_idx_to_eid = [] for p in prompts: result_idx_to_eid.extend([p[0]] * self.args.sampling_n) prompts = [p[1] for p in prompts] result = self._call_codex_api( engine=self.args.engine, prompt=prompts, max_tokens=self.args.max_generation_tokens, temperature=self.args.temperature, top_p=self.args.top_p, n=self.args.sampling_n, stop=self.args.stop_tokens ) if verbose: print('\n', '*' * 20, 'Codex API Call', '*' * 20) for prompt in prompts: print(prompt) print('\n') print('- - - - - - - - - - ->>') # parse api results response_dict = dict() for idx, g in enumerate(result['choices']): try: text = g['text'] logprob = sum(g['logprobs']['token_logprobs']) eid = result_idx_to_eid[idx] eid_pairs = response_dict.get(eid, None) if eid_pairs is None: eid_pairs = [] response_dict[eid] = eid_pairs eid_pairs.append((text, logprob)) if verbose: print(text) except ValueError as e: if verbose: print('----------- Error Msg--------') print(e) print(text) print('-----------------------------') pass return response_dict def _call_codex_api( self, engine: str, prompt: Union[str, List], max_tokens, temperature: float, top_p: float, n: int, stop: List[str] ): start_time = time.time() result = None while result is None: try: key = self.keys[self.current_key_id] self.current_key_id = (self.current_key_id + 1) % len(self.keys) print(f"Using openai api key: {key}") result = openai.Completion.create( engine=engine, prompt=prompt, api_key=key, max_tokens=max_tokens, temperature=temperature, top_p=top_p, n=n, stop=stop, logprobs=1 ) print('Openai api inference time:', time.time() - start_time) return result except Exception as e: print(e, 'Retry.') time.sleep(20) class NeuralDB(object): def __init__(self, tables: List[Dict[str, Dict]], passages=None, images=None): self.raw_tables = copy.deepcopy(tables) self.passages = {} self.images = {} self.image_captions = {} self.passage_linker = {} # The links from cell value to passage self.image_linker = {} # The links from cell value to images # Get passages if passages: for passage in passages: title, passage_content = passage['title'], passage['text'] self.passages[title] = passage_content # Get images if images: for image in images: _id, title, picture = image['id'], image['title'], image['pic'] self.images[title] = picture self.image_captions[title] = get_caption(_id) # Link grounding resources from other modalities(passages, images). if self.raw_tables[0]['table'].get('rows_with_links', None): rows = self.raw_tables[0]['table']['rows'] rows_with_links = self.raw_tables[0]['table']['rows_with_links'] link_title2cell_map = {} for row_id in range(len(rows)): for col_id in range(len(rows[row_id])): cell = rows_with_links[row_id][col_id] for text, title, url in zip(cell[0], cell[1], cell[2]): text = text.lower().strip() link_title2cell_map[title] = text # Link Passages for passage in passages: title, passage_content = passage['title'], passage['text'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.passage_linker[linked_cell] = title # Images for image in images: title, picture = image['title'], image['pic'] linked_cell = link_title2cell_map.get(title, None) if linked_cell: self.image_linker[linked_cell] = title for table_info in tables: table_info['table'] = prepare_df_for_neuraldb_from_table(table_info['table']) self.tables = tables # Connect to SQLite database self.tmp_path = "tmp" os.makedirs(self.tmp_path, exist_ok=True) # self.db_path = os.path.join(self.tmp_path, '{}.db'.format(hash(time.time()))) self.db_path = os.path.join(self.tmp_path, '{}.db'.format(uuid.uuid4())) self.sqlite_conn = sqlite3.connect(self.db_path) # Create DB assert len(tables) >= 1, "DB has no table inside" table_0 = tables[0] if len(tables) > 1: raise ValueError("More than one table not support yet.") else: table_0["table"].to_sql("w", self.sqlite_conn) self.table_name = "w" self.table_title = table_0.get('title', None) # Records conn self.db = records.Database('sqlite:///{}'.format(self.db_path)) self.records_conn = self.db.get_connection() def __str__(self): return str(self.execute_query("SELECT * FROM {}".format(self.table_name))) def get_table(self, table_name=None): table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) _table = self.execute_query(sql_query) return _table def get_header(self, table_name=None): _table = self.get_table(table_name) return _table['header'] def get_rows(self, table_name): _table = self.get_table(table_name) return _table['rows'] def get_table_df(self): return self.tables[0]['table'] def get_table_raw(self): return self.raw_tables[0]['table'] def get_table_title(self): return self.tables[0]['title'] def get_passages_titles(self): return list(self.passages.keys()) def get_images_titles(self): return list(self.images.keys()) def get_passage_by_title(self, title: str): return check_in_and_return(title, self.passages) def get_image_by_title(self, title): return check_in_and_return(title, self.images) def get_image_caption_by_title(self, title): return check_in_and_return(title, self.image_captions) def get_image_linker(self): return copy.deepcopy(self.image_linker) def get_passage_linker(self): return copy.deepcopy(self.passage_linker) def execute_query(self, sql_query: str): """ Basic operation. Execute the sql query on the database we hold. """ # When the sql query is a column name (@deprecated: or a certain value with '' and "" surrounded). if len(sql_query.split(' ')) == 1 or (sql_query.startswith('`') and sql_query.endswith('`')): col_name = sql_query new_sql_query = r"SELECT row_id, {} FROM {}".format(col_name, self.table_name) # Here we use a hack that when a value is surrounded by '' or "", the sql will return a column of the value, # while for variable, no ''/"" surrounded, this sql will query for the column. out = self.records_conn.query(new_sql_query) # When the sql query wants all cols or col_id, which is no need for us to add 'row_id'. elif sql_query.lower().startswith("select *") or sql_query.startswith("select col_id"): out = self.records_conn.query(sql_query) else: try: # SELECT row_id in addition, needed for result and old table alignment. new_sql_query = "SELECT row_id, " + sql_query[7:] out = self.records_conn.query(new_sql_query) except sqlalchemy.exc.OperationalError as e: # Execute normal SQL, and in this case the row_id is actually in no need. out = self.records_conn.query(sql_query) results = out.all() unmerged_results = [] merged_results = [] headers = out.dataset.headers for i in range(len(results)): unmerged_results.append(list(results[i].values())) merged_results.extend(results[i].values()) return {"header": headers, "rows": unmerged_results} def add_sub_table(self, sub_table, table_name=None, verbose=True): """ Add sub_table into the table. """ table_name = self.table_name if not table_name else table_name sql_query = "SELECT * FROM {}".format(table_name) oring_table = self.execute_query(sql_query) old_table = pd.DataFrame(oring_table["rows"], columns=oring_table["header"]) # concat the new column into old table sub_table_df_normed = convert_df_type(pd.DataFrame(data=sub_table['rows'], columns=sub_table['header'])) new_table = old_table.merge(sub_table_df_normed, how='left', on='row_id') # do left join new_table.to_sql(table_name, self.sqlite_conn, if_exists='replace', index=False) if verbose: print("Insert column(s) {} (dtypes: {}) into table.\n".format(', '.join([_ for _ in sub_table['header']]), sub_table_df_normed.dtypes)) The provided code snippet includes necessary dependencies for implementing the `worker_annotate` function. Write a Python function `def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, dataset_for_retrieve, tokenizer )` to solve the following problem: A worker process for annotating. Here is the function: def worker_annotate( pid: int, args, generator: Generator, g_eids: List, dataset, dataset_for_retrieve, tokenizer ): """ A worker process for annotating. """ g_dict = dict() built_few_shot_prompts = [] # Hard encode, only work for test with open(os.path.join(ROOT_DIR, "scripts", "w_ic_examples_retrieval", "tab_fact_in_context_examples_test_from_train_ids.json"), "r") as f: tab_fact_in_context_examples_test_from_train_ids = json.load(f) with open(os.path.join(ROOT_DIR, "scripts", "w_ic_examples_retrieval", "nsql_annotations_tab_fact_train.json"), "r") as f: nsql_annotations_tab_fact_train = json.load(f) tab_fact_in_context_examples_test = {} for _id, ids in tab_fact_in_context_examples_test_from_train_ids.items(): nsqls_for_the_examples = [{"nid": nid, "nsql": nsql_annotations_tab_fact_train[nid]} for nid in ids] tab_fact_in_context_examples_test[_id] = nsqls_for_the_examples for g_eid in g_eids: try: g_data_item = dataset[g_eid] g_dict[g_eid] = { 'generations': [], 'ori_data_item': copy.deepcopy(g_data_item) } db = NeuralDB( tables=[{'title': g_data_item['table']['page_title'], 'table': g_data_item['table']}] ) g_data_item['table'] = db.get_table_df() g_data_item['title'] = db.get_table_title() n_shots = args.n_shots all_nsqls = tab_fact_in_context_examples_test[str(g_eid)] few_shot_prompts = [] for in_context_example in all_nsqls[:n_shots]: ic_eid = int(in_context_example['nid']) ic_data_item = dataset_for_retrieve[ic_eid] if not isinstance(ic_data_item['table'], pd.DataFrame): db = NeuralDB( tables=[{'title': ic_data_item['table']['page_title'], 'table': ic_data_item['table']}] ) ic_data_item['table'] = db.get_table_df() ic_data_item['title'] = db.get_table_title() ic_data_item['nsql'] = in_context_example['nsql'] ic_prompt = generator.prompt_builder.build_one_shot_prompt( **ic_data_item, prompt_type=('question', 'nsql') ) few_shot_prompts.append(ic_prompt) few_shot_prompt = """Generate SQL given the statement and table to verify the statement correctly. If statement-relevant column(s) contents are not suitable for SQL comparisons or calculations, map it to a new column with clean content by a new grammar QA("map@"). If mapping to a new column still can not answer the statement with valid SQL, turn to an end-to-end solution by a new grammar QA("ans@"). This grammar aims to solve all the rest of complex statements or tables. """ + "\n" + "\n\n\n".join([_.strip() for _ in few_shot_prompts]) generate_prompt = generator.build_generate_prompt( data_item=g_data_item, generate_type=('nsql',) ) prompt = few_shot_prompt + "\n\n" + generate_prompt # Ensure the input length fit Codex max input tokens by shrinking the n_shots max_prompt_tokens = args.max_api_total_tokens - args.max_generation_tokens while len(tokenizer.tokenize(prompt)) >= max_prompt_tokens: # TODO: Add shrink rows n_shots -= 1 assert n_shots >= 0 few_shot_prompt = "\n\n\n".join(few_shot_prompt.split("\n\n\n")[:-1]) prompt = few_shot_prompt + "\n\n" + generate_prompt print(f"Process#{pid}: Building prompt for eid#{g_eid}, original_id#{g_data_item['id']}") built_few_shot_prompts.append((g_eid, prompt)) if len(built_few_shot_prompts) < args.n_parallel_prompts: continue print(f"Process#{pid}: Prompts ready with {len(built_few_shot_prompts)} parallels. Run openai API.") response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs built_few_shot_prompts = [] except Exception as e: print(f"Process#{pid}: eid#{g_eid}, wtqid#{g_data_item['id']} generation error: {e}") # Final generation inference if len(built_few_shot_prompts) > 0: response_dict = generator.generate_one_pass( prompts=built_few_shot_prompts, verbose=args.verbose ) for eid, g_pairs in response_dict.items(): g_pairs = sorted(g_pairs, key=lambda x: x[-1], reverse=True) g_dict[eid]['generations'] = g_pairs return g_dict
A worker process for annotating.
165,103
import json import argparse import platform, multiprocessing import os import time from nsql.nsql_exec import Executor, NeuralDB from utils.normalizer import post_process_sql from utils.utils import load_data_split, majority_vote from utils.evaluator import Evaluator class Executor(object): def __init__(self, args, keys=None): self.new_col_name_id = 0 self.qa_model = OpenAIQAModel(args, keys) def generate_new_col_names(self, number): col_names = ["col_{}".format(i) for i in range(self.new_col_name_id, self.new_col_name_id + number)] self.new_col_name_id += number return col_names def sql_exec(self, sql: str, db: NeuralDB, verbose=True): if verbose: print("Exec SQL '{}' with additional row_id on {}".format(sql, db)) result = db.execute_query(sql) return result def nsql_exec(self, nsql: str, db: NeuralDB, verbose=True): steps = [] root_node = get_cfg_tree(nsql) # Parse execution tree from nsql. get_steps(root_node, steps) # Flatten the execution tree and get the steps. steps = remove_duplicate(steps) # Remove the duplicate steps. if verbose: print("Steps:", [s.rename for s in steps]) col_idx = 0 for step in steps: # All steps should be formatted as 'QA()' except for last step which could also be normal SQL. assert isinstance(step, TreeNode), "step must be treenode" nsql = step.rename if nsql.startswith('QA('): question, sql_s = parse_question_paras(nsql, self.qa_model) sql_executed_sub_tables = [] # Execute all SQLs and get the results as parameters for sql_item in sql_s: role, sql_item = nsql_role_recognize(sql_item, db.get_header(), db.get_passages_titles(), db.get_images_titles()) if role in ['col', 'complete_sql']: sql_executed_sub_table = self.sql_exec(sql_item, db, verbose=verbose) sql_executed_sub_tables.append(sql_executed_sub_table) elif role == 'val': val = eval(sql_item) sql_executed_sub_tables.append({ "header": ["row_id", "val"], "rows": [["0", val]] }) elif role == 'passage_title_and_image_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_passage_by_title(sql_item) + db.get_image_caption_by_title(sql_item) # "{} (The answer of '{}' is {})".format( # sql_item, # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(sql_item))) ]] }) elif role == 'passage_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_passage_by_title(sql_item)]] }) elif role == 'image_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_image_caption_by_title(sql_item)]], # "rows": [["0", "{} (The answer of '{}' is {})".format( # sql_item, # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(sql_item)))]], }) # If the sub_tables to execute with link, append it to the cell. passage_linker = db.get_passage_linker() image_linker = db.get_image_linker() for _sql_executed_sub_table in sql_executed_sub_tables: for i in range(len(_sql_executed_sub_table['rows'])): for j in range(len(_sql_executed_sub_table['rows'][i])): _cell = _sql_executed_sub_table['rows'][i][j] if _cell in passage_linker.keys(): _sql_executed_sub_table['rows'][i][j] += " ({})".format( # Add passage text as backup info db.get_passage_by_title(passage_linker[_cell])) if _cell in image_linker.keys(): _sql_executed_sub_table['rows'][i][j] += " ({})".format( # Add image caption as backup info db.get_image_caption_by_title(image_linker[_cell])) # _sql_executed_sub_table['rows'][i][j] += " (The answer of '{}' is {})".format( # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(image_linker[_cell]))) pass if question.lower().startswith("map@"): # When the question is a type of mapping, we return the mapped column. question = question[len("map@"):] if step.father: step.rename_father_col(col_idx=col_idx) sub_table: Dict = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="map", new_col_name_s=step.produced_col_name_s, verbose=verbose) db.add_sub_table(sub_table, verbose=verbose) col_idx += 1 else: # This step is the final step sub_table: Dict = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="map", new_col_name_s=["col_{}".format(col_idx)], verbose=verbose) return extract_answers(sub_table) elif question.lower().startswith("ans@"): # When the question is a type of answering, we return an answer list. question = question[len("ans@"):] answer: List = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="ans", verbose=verbose) if step.father: step.rename_father_val(answer) else: # This step is the final step return answer else: raise ValueError( "Except for operators or NL question must start with 'map@' or 'ans@'!, check '{}'".format( question)) else: sub_table = self.sql_exec(nsql, db, verbose=verbose) return extract_answers(sub_table) def post_process_sql(sql_str, df, table_title=None, process_program_with_fuzzy_match_on_db=True, verbose=False): """Post process SQL: including basic fix and further fuzzy match on cell and SQL to process""" def basic_fix(sql_str, all_headers, table_title=None): def finditer(sub_str: str, mother_str: str): result = [] start_index = 0 while True: start_index = mother_str.find(sub_str, start_index, -1) if start_index == -1: break end_idx = start_index + len(sub_str) result.append((start_index, end_idx)) start_index = end_idx return result if table_title: sql_str = sql_str.replace("FROM " + table_title, "FROM w") sql_str = sql_str.replace("FROM " + table_title.lower(), "FROM w") """Case 1: Fix the `` missing. """ # Remove the null header. while '' in all_headers: all_headers.remove('') # Remove the '\n' in header. # This is because the WikiTQ won't actually show the str in two lines, # they use '\n' to mean that, and display it in the same line when print. sql_str = sql_str.replace("\\n", "\n") sql_str = sql_str.replace("\n", "\\n") # Add `` in SQL. all_headers.sort(key=lambda x: len(x), reverse=True) have_matched = [0 for i in range(len(sql_str))] # match quotation idx_s_single_quotation = [_ for _ in range(1, len(sql_str)) if sql_str[_] in ["\'"] and sql_str[_ - 1] not in ["\'"]] idx_s_double_quotation = [_ for _ in range(1, len(sql_str)) if sql_str[_] in ["\""] and sql_str[_ - 1] not in ["\""]] for idx_s in [idx_s_single_quotation, idx_s_double_quotation]: if len(idx_s) % 2 == 0: for idx in range(int(len(idx_s) / 2)): start_idx = idx_s[idx * 2] end_idx = idx_s[idx * 2 + 1] have_matched[start_idx: end_idx] = [2 for _ in range(end_idx - start_idx)] # match headers for header in all_headers: if (header in sql_str) and (header not in ALL_KEY_WORDS): all_matched_of_this_header = finditer(header, sql_str) for matched_of_this_header in all_matched_of_this_header: start_idx, end_idx = matched_of_this_header if all(have_matched[start_idx: end_idx]) == 0 and (not sql_str[start_idx - 1] == "`") and ( not sql_str[end_idx] == "`"): have_matched[start_idx: end_idx] = [1 for _ in range(end_idx - start_idx)] # a bit ugly, but anyway. # re-compose sql from the matched idx. start_have_matched = [0] + have_matched end_have_matched = have_matched + [0] start_idx_s = [idx - 1 for idx in range(1, len(start_have_matched)) if start_have_matched[idx - 1] == 0 and start_have_matched[idx] == 1] end_idx_s = [idx for idx in range(len(end_have_matched) - 1) if end_have_matched[idx] == 1 and end_have_matched[idx + 1] == 0] assert len(start_idx_s) == len(end_idx_s) spans = [] current_idx = 0 for start_idx, end_idx in zip(start_idx_s, end_idx_s): spans.append(sql_str[current_idx:start_idx]) spans.append(sql_str[start_idx:end_idx + 1]) current_idx = end_idx + 1 spans.append(sql_str[current_idx:]) sql_str = '`'.join(spans) return sql_str def fuzzy_match_process(sql_str, df, verbose=False): """ Post-process SQL by fuzzy matching value with table contents. """ def _get_matched_cells(value_str, df, fuzz_threshold=70): """ Get matched table cells with value token. """ matched_cells = [] for row_id, row in df.iterrows(): for cell in row: cell = str(cell) fuzz_score = fuzz.ratio(value_str, cell) if fuzz_score == 100: matched_cells = [(cell, fuzz_score)] return matched_cells if fuzz_score >= fuzz_threshold: matched_cells.append((cell, fuzz_score)) matched_cells = sorted(matched_cells, key=lambda x: x[1], reverse=True) return matched_cells def _check_valid_fuzzy_match(value_str, matched_cell): """ Check if the fuzzy match is valid, now considering: 1. The number/date should not be disturbed, but adding new number or deleting number is valid. """ number_pattern = "[+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?" numbers_in_value = re.findall(number_pattern, value_str) numbers_in_matched_cell = re.findall(number_pattern, matched_cell) try: numbers_in_value = [float(num.replace(',', '')) for num in numbers_in_value] except: print(f"Can't convert number string {numbers_in_value} into float in _check_valid_fuzzy_match().") try: numbers_in_matched_cell = [float(num.replace(',', '')) for num in numbers_in_matched_cell] except: print( f"Can't convert number string {numbers_in_matched_cell} into float in _check_valid_fuzzy_match().") numbers_in_value = set(numbers_in_value) numbers_in_matched_cell = set(numbers_in_matched_cell) if numbers_in_value.issubset(numbers_in_matched_cell) or numbers_in_matched_cell.issubset(numbers_in_value): return True else: return False # Drop trailing '\n```', a pattern that may appear in Codex SQL generation sql_str = sql_str.rstrip('```').rstrip('\n') # Replace QA module with placeholder qa_pattern = "QA\(.+?;.*?`.+?`.*?\)" qas = re.findall(qa_pattern, sql_str) for idx, qa in enumerate(qas): sql_str = sql_str.replace(qa, f"placeholder{idx}") # Parse and replace SQL value with table contents sql_tokens = tokenize(sql_str) sql_template_tokens = extract_partial_template_from_sql(sql_str) # Fix 'between' keyword bug in parsing templates fixed_sql_template_tokens = [] sql_tok_bias = 0 for idx, sql_templ_tok in enumerate(sql_template_tokens): sql_tok = sql_tokens[idx + sql_tok_bias] if sql_tok == 'between' and sql_templ_tok == '[WHERE_OP]': fixed_sql_template_tokens.extend(['[WHERE_OP]', '[VALUE]', 'and']) sql_tok_bias += 2 # pass '[VALUE]', 'and' else: fixed_sql_template_tokens.append(sql_templ_tok) sql_template_tokens = fixed_sql_template_tokens for idx, tok in enumerate(sql_tokens): if tok in ALL_KEY_WORDS: sql_tokens[idx] = tok.upper() if verbose: print(sql_tokens) print(sql_template_tokens) assert len(sql_tokens) == len(sql_template_tokens) value_indices = [idx for idx in range(len(sql_template_tokens)) if sql_template_tokens[idx] == '[VALUE]'] for value_idx in value_indices: # Skip the value if the where condition column is QA module if value_idx >= 2 and sql_tokens[value_idx - 2].startswith('placeholder'): continue value_str = sql_tokens[value_idx] # Drop \"\" for fuzzy match is_string = False if value_str[0] == "\"" and value_str[-1] == "\"": value_str = value_str[1:-1] is_string = True # If already fuzzy match, skip if value_str[0] == '%' or value_str[-1] == '%': continue value_str = value_str.lower() # Fuzzy Match matched_cells = _get_matched_cells(value_str, df) if verbose: print(matched_cells) new_value_str = value_str if matched_cells: # new_value_str = matched_cells[0][0] for matched_cell, fuzz_score in matched_cells: if _check_valid_fuzzy_match(value_str, matched_cell): new_value_str = matched_cell if verbose and new_value_str != value_str: print("\tfuzzy match replacing!", value_str, '->', matched_cell, f'fuzz_score:{fuzz_score}') break if is_string: new_value_str = f"\"{new_value_str}\"" sql_tokens[value_idx] = new_value_str # Compose new sql string # Clean column name in SQL since columns may have been tokenized in the postprocessing, e.g., (ppp) -> ( ppp ) new_sql_str = ' '.join(sql_tokens) sql_columns = re.findall('`\s(.*?)\s`', new_sql_str) for sql_col in sql_columns: matched_columns = [] for col in df.columns: score = fuzz.ratio(sql_col.lower(), col) if score == 100: matched_columns = [(col, score)] break if score >= 80: matched_columns.append((col, score)) matched_columns = sorted(matched_columns, key=lambda x: x[1], reverse=True) if matched_columns: matched_col = matched_columns[0][0] new_sql_str = new_sql_str.replace(f"` {sql_col} `", f"`{matched_col}`") else: new_sql_str = new_sql_str.replace(f"` {sql_col} `", f"`{sql_col}`") # Restore QA modules for idx, qa in enumerate(qas): new_sql_str = new_sql_str.replace(f"placeholder{idx}", qa) # Fix '<>' when composing the new sql new_sql_str = new_sql_str.replace('< >', '<>') return new_sql_str sql_str = basic_fix(sql_str, list(df.columns), table_title) if process_program_with_fuzzy_match_on_db: try: sql_str = fuzzy_match_process(sql_str, df, verbose) except: pass return sql_str def majority_vote( nsqls: List, pred_answer_list: List, allow_none_and_empty_answer: bool = False, allow_error_answer: bool = False, answer_placeholder: Union[str, int] = '<error|empty>', vote_method: str = 'prob', answer_biased: Union[str, int] = None, answer_biased_weight: float = None, ): """ Determine the final nsql execution answer by majority vote. """ def _compare_answer_vote_simple(a, b): """ First compare occur times. If equal, then compare max nsql logprob. """ if a[1]['count'] > b[1]['count']: return 1 elif a[1]['count'] < b[1]['count']: return -1 else: if a[1]['nsqls'][0][1] > b[1]['nsqls'][0][1]: return 1 elif a[1]['nsqls'][0][1] == b[1]['nsqls'][0][1]: return 0 else: return -1 def _compare_answer_vote_with_prob(a, b): """ Compare prob sum. """ return 1 if sum([math.exp(nsql[1]) for nsql in a[1]['nsqls']]) > sum( [math.exp(nsql[1]) for nsql in b[1]['nsqls']]) else -1 # Vote answers candi_answer_dict = dict() for (nsql, logprob), pred_answer in zip(nsqls, pred_answer_list): if allow_none_and_empty_answer: if pred_answer == [None] or pred_answer == []: pred_answer = [answer_placeholder] if allow_error_answer: if pred_answer == '<error>': pred_answer = [answer_placeholder] # Invalid execution results if pred_answer == '<error>' or pred_answer == [None] or pred_answer == []: continue if candi_answer_dict.get(tuple(pred_answer), None) is None: candi_answer_dict[tuple(pred_answer)] = { 'count': 0, 'nsqls': [] } answer_info = candi_answer_dict.get(tuple(pred_answer), None) answer_info['count'] += 1 answer_info['nsqls'].append([nsql, logprob]) # All candidates execution errors if len(candi_answer_dict) == 0: return answer_placeholder, [(nsqls[0][0], nsqls[0][-1])] # Sort if vote_method == 'simple': sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_simple), reverse=True) elif vote_method == 'prob': sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_with_prob), reverse=True) elif vote_method == 'answer_biased': # Specifically for Tabfact entailed answer, i.e., `1`. # If there exists nsql that produces `1`, we consider it more significant because `0` is very common. assert answer_biased_weight is not None and answer_biased_weight > 0 for answer, answer_dict in candi_answer_dict.items(): if answer == (answer_biased,): answer_dict['count'] *= answer_biased_weight sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_simple), reverse=True) elif vote_method == 'lf_biased': # Assign weights to different types of logic forms (lf) to control interpretability and coverage for answer, answer_dict in candi_answer_dict.items(): count = 0 for nsql, _ in answer_dict['nsqls']: if 'map@' in nsql: count += 10 elif 'ans@' in nsql: count += 10 else: count += 1 answer_dict['count'] = count sorted_candi_answer_list = sorted(list(candi_answer_dict.items()), key=cmp_to_key(_compare_answer_vote_simple), reverse=True) else: raise ValueError(f"Vote method {vote_method} is not supported.") pred_answer_info = sorted_candi_answer_list[0] pred_answer, pred_answer_nsqls = list(pred_answer_info[0]), pred_answer_info[1]['nsqls'] return pred_answer, pred_answer_nsqls class Evaluator(): def __init__(self, transition_system, table_path='data/tables.json', database_dir='data/database'): super(Evaluator, self).__init__() self.transition_system = transition_system self.kmaps = build_foreign_key_map_from_json(table_path) self.database_dir = database_dir self.engine = Engine() self.checker = Checker(table_path, database_dir) self.acc_dict = { "sql": self.sql_acc, # use golden sql as references "ast": self.ast_acc, # compare ast accuracy, ast may be incorrect when constructed from raw sql "beam": self.beam_acc, # if the correct answer exist in the beam, assume the result is true } def acc(self, pred_hyps, dataset, output_path=None, acc_type='sql', etype='match', use_checker=False): assert len(pred_hyps) == len(dataset) and acc_type in self.acc_dict and etype in ['match', 'exec'] acc_method = self.acc_dict[acc_type] return acc_method(pred_hyps, dataset, output_path, etype, use_checker) def beam_acc(self, pred_hyps, dataset, output_path, etype, use_checker): scores, results = {}, [] for each in ['easy', 'medium', 'hard', 'extra', 'all']: scores[each] = [0, 0.] # first is count, second is total score for idx, pred in enumerate(pred_hyps): question, gold_sql, db = dataset[idx].ex['question'], dataset[idx].query, dataset[idx].db for b_id, hyp in enumerate(pred): pred_sql = self.transition_system.ast_to_surface_code(hyp.tree, db) score, hardness = self.single_acc(pred_sql, gold_sql, db['db_id'], etype) if int(score) == 1: scores[hardness][0] += 1 scores[hardness][1] += 1.0 scores['all'][0] += 1 scores['all'][1] += 1.0 results.append((hardness, question, gold_sql, pred_sql, b_id, True)) break else: scores[hardness][0] += 1 scores['all'][0] += 1 pred_sql = self.transition_system.ast_to_surface_code(pred[0].tree, db) results.append((hardness, question, gold_sql, pred_sql, 0, False)) for each in scores: accuracy = scores[each][1] / float(scores[each][0]) if scores[each][0] != 0 else 0. scores[each].append(accuracy) of = open(output_path, 'w', encoding='utf8') if output_path is not None else \ tempfile.TemporaryFile('w+t') for item in results: of.write('Level: %s\n' % (item[0])) of.write('Question: %s\n' % (item[1])) of.write('Gold SQL: %s\n' %(item[2])) of.write('Pred SQL (%s): %s\n' % (item[4], item[3])) of.write('Correct: %s\n\n' % (item[5])) for each in scores: of.write('Level %s: %s\n' % (each, scores[each])) of.close() return scores['all'][2] def single_acc(self, pred_sql, gold_sql, db, etype): """ score(float): 0 or 1, etype score hardness(str): one of 'easy', 'medium', 'hard', 'extra' """ db_name = db db = os.path.join(self.database_dir, db, db + ".sqlite") schema = Schema(get_schema(db)) g_sql = get_sql(schema, gold_sql) hardness = self.engine.eval_hardness(g_sql) try: p_sql = get_sql(schema, pred_sql) except: # If p_sql is not valid, then we will use an empty sql to evaluate with the correct sql p_sql = { "except": None, "from": { "conds": [], "table_units": [] }, "groupBy": [], "having": [], "intersect": None, "limit": None, "orderBy": [], "select": [ False, [] ], "union": None, "where": [] } kmap = self.kmaps[db_name] g_valid_col_units = build_valid_col_units(g_sql['from']['table_units'], schema) g_sql = rebuild_sql_val(g_sql) g_sql = rebuild_sql_col(g_valid_col_units, g_sql, kmap) # kmap: map __tab.col__ to pivot __tab.col__ p_valid_col_units = build_valid_col_units(p_sql['from']['table_units'], schema) p_sql = rebuild_sql_val(p_sql) p_sql = rebuild_sql_col(p_valid_col_units, p_sql, kmap) if etype == 'exec': score = float(eval_exec_match(db, pred_sql, gold_sql, p_sql, g_sql)) if etype == 'match': score = float(self.engine.eval_exact_match(p_sql, g_sql)) return score, hardness def ast_acc(self, pred_hyps, dataset, output_path, etype, use_checker): pred_asts = [hyp[0].tree for hyp in pred_hyps] ref_asts = [ex.ast for ex in dataset] dbs = [ex.db for ex in dataset] pred_sqls, ref_sqls = [], [] for pred, ref, db in zip(pred_asts, ref_asts, dbs): pred_sql = self.transition_system.ast_to_surface_code(pred, db) ref_sql = self.transition_system.ast_to_surface_code(ref, db) pred_sqls.append(pred_sql) ref_sqls.append(ref_sql) with tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_pred, \ tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_ref: of = open(output_path, 'w', encoding='utf8') if output_path is not None \ else tempfile.TemporaryFile('w+t') # write pred and ref sqls for s in pred_sqls: tmp_pred.write(s + '\n') tmp_pred.flush() for s, db in zip(ref_sqls, dbs): tmp_ref.write(s + '\t' + db['db_id'] + '\n') tmp_ref.flush() # calculate ast accuracy old_print = sys.stdout sys.stdout = of result_type = 'exact' if etype == 'match' else 'exec' all_exact_acc = evaluate(tmp_ref.name, tmp_pred.name, self.database_dir, etype, self.kmaps)['all'][result_type] sys.stdout = old_print of.close() return float(all_exact_acc) def sql_acc(self, pred_hyps, dataset, output_path, etype, use_checker): pred_sqls, ref_sqls = [], [ex.query for ex in dataset] dbs = [ex.db for ex in dataset] for idx, hyp in enumerate(pred_hyps): if use_checker: pred_sql = self.obtain_sql(hyp, dbs[idx]) else: best_ast = hyp[0].tree # by default, the top beam prediction pred_sql = self.transition_system.ast_to_surface_code(best_ast, dbs[idx]) pred_sqls.append(pred_sql) with tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_pred, \ tempfile.NamedTemporaryFile('w+t', encoding='utf8', suffix='.sql') as tmp_ref: of = open(output_path, 'w', encoding='utf8') if output_path is not None \ else tempfile.TemporaryFile('w+t') # write pred and ref sqls for s in pred_sqls: tmp_pred.write(s + '\n') tmp_pred.flush() for s, db in zip(ref_sqls, dbs): tmp_ref.write(s + '\t' + db['db_id'] + '\n') tmp_ref.flush() # calculate sql accuracy old_print = sys.stdout sys.stdout = of result_type = 'exact' if etype == 'match' else 'exec' all_exact_acc = evaluate(tmp_ref.name, tmp_pred.name, self.database_dir, etype, self.kmaps)['all'][result_type] sys.stdout = old_print of.close() return float(all_exact_acc) def obtain_sql(self, hyps, db): beam = len(hyps) for hyp in hyps: cur_ast = hyp.tree pred_sql = self.transition_system.ast_to_surface_code(cur_ast, db) if self.checker.validity_check(pred_sql, db['db_id']): sql = pred_sql break else: best_ast = hyps[0].tree sql = self.transition_system.ast_to_surface_code(best_ast, db) return sql The provided code snippet includes necessary dependencies for implementing the `worker_execute` function. Write a Python function `def worker_execute( pid, args, dataset, nsql_dict, keys )` to solve the following problem: A worker process for execution. Here is the function: def worker_execute( pid, args, dataset, nsql_dict, keys ): """ A worker process for execution. """ result_dict = dict() n_total_samples, n_correct_samples = 0, 0 for eid, data_item in enumerate(dataset): eid = str(eid) if eid not in nsql_dict: continue print(f"Process#{pid}: eid {eid}, wtq-id {data_item['id']}") result_dict[eid] = dict() result_dict[eid]['question'] = data_item['question'] result_dict[eid]['gold_answer'] = data_item['answer_text'] n_total_samples += 1 table = data_item['table'] title = table['page_title'] executor = Executor(args, keys) # Execute exec_answer_list = [] nsql_exec_answer_dict = dict() for idx, (nsql, logprob) in enumerate(nsql_dict[eid]['nsqls']): print(f"Process#{pid}: eid {eid}, original_id {data_item['id']}, executing program#{idx}, logprob={logprob}") try: if nsql in nsql_exec_answer_dict: exec_answer = nsql_exec_answer_dict[nsql] else: db = NeuralDB( tables=[{"title": title, "table": table}] ) nsql = post_process_sql( sql_str=nsql, df=db.get_table_df(), process_program_with_fuzzy_match_on_db=args.process_program_with_fuzzy_match_on_db, table_title=title ) exec_answer = executor.nsql_exec(nsql, db, verbose=args.verbose) if isinstance(exec_answer, str): exec_answer = [exec_answer] nsql_exec_answer_dict[nsql] = exec_answer exec_answer_list.append(exec_answer) except Exception as e: print(f"Process#{pid}: Execution error {e}") exec_answer = '<error>' exec_answer_list.append(exec_answer) # Store tmp execution answers if nsql_dict[eid].get('exec_answers', None) is None: nsql_dict[eid]['exec_answers'] = [] nsql_dict[eid]['exec_answers'].append(exec_answer) # Majority vote to determine the final prediction answer pred_answer, pred_answer_nsqls = majority_vote( nsqls=nsql_dict[eid]['nsqls'], pred_answer_list=exec_answer_list, allow_none_and_empty_answer=args.allow_none_and_empty_answer, answer_placeholder=args.answer_placeholder, vote_method=args.vote_method, answer_biased=args.answer_biased, answer_biased_weight=args.answer_biased_weight ) # Evaluate result_dict[eid]['pred_answer'] = pred_answer result_dict[eid]['nsql'] = pred_answer_nsqls gold_answer = data_item['answer_text'] score = Evaluator().evaluate( pred_answer, gold_answer, dataset=args.dataset, question=result_dict[eid]['question'] ) n_correct_samples += score print(f'Process#{pid}: pred answer: {pred_answer}') print(f'Process#{pid}: gold answer: {gold_answer}') if score == 1: print(f'Process#{pid}: Correct!') else: print(f'Process#{pid}: Wrong.') print(f'Process#{pid}: Accuracy: {n_correct_samples}/{n_total_samples}') return result_dict
A worker process for execution.
165,104
import json import argparse import platform, multiprocessing import os import time from nsql.nsql_exec import Executor, NeuralDB from utils.normalizer import post_process_sql from utils.utils import load_data_split, majority_vote from utils.evaluator import Evaluator class Executor(object): def __init__(self, args, keys=None): self.new_col_name_id = 0 self.qa_model = OpenAIQAModel(args, keys) def generate_new_col_names(self, number): col_names = ["col_{}".format(i) for i in range(self.new_col_name_id, self.new_col_name_id + number)] self.new_col_name_id += number return col_names def sql_exec(self, sql: str, db: NeuralDB, verbose=True): if verbose: print("Exec SQL '{}' with additional row_id on {}".format(sql, db)) result = db.execute_query(sql) return result def nsql_exec(self, nsql: str, db: NeuralDB, verbose=True): steps = [] root_node = get_cfg_tree(nsql) # Parse execution tree from nsql. get_steps(root_node, steps) # Flatten the execution tree and get the steps. steps = remove_duplicate(steps) # Remove the duplicate steps. if verbose: print("Steps:", [s.rename for s in steps]) col_idx = 0 for step in steps: # All steps should be formatted as 'QA()' except for last step which could also be normal SQL. assert isinstance(step, TreeNode), "step must be treenode" nsql = step.rename if nsql.startswith('QA('): question, sql_s = parse_question_paras(nsql, self.qa_model) sql_executed_sub_tables = [] # Execute all SQLs and get the results as parameters for sql_item in sql_s: role, sql_item = nsql_role_recognize(sql_item, db.get_header(), db.get_passages_titles(), db.get_images_titles()) if role in ['col', 'complete_sql']: sql_executed_sub_table = self.sql_exec(sql_item, db, verbose=verbose) sql_executed_sub_tables.append(sql_executed_sub_table) elif role == 'val': val = eval(sql_item) sql_executed_sub_tables.append({ "header": ["row_id", "val"], "rows": [["0", val]] }) elif role == 'passage_title_and_image_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_passage_by_title(sql_item) + db.get_image_caption_by_title(sql_item) # "{} (The answer of '{}' is {})".format( # sql_item, # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(sql_item))) ]] }) elif role == 'passage_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_passage_by_title(sql_item)]] }) elif role == 'image_title': sql_executed_sub_tables.append({ "header": ["row_id", "{}".format(sql_item)], "rows": [["0", db.get_image_caption_by_title(sql_item)]], # "rows": [["0", "{} (The answer of '{}' is {})".format( # sql_item, # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(sql_item)))]], }) # If the sub_tables to execute with link, append it to the cell. passage_linker = db.get_passage_linker() image_linker = db.get_image_linker() for _sql_executed_sub_table in sql_executed_sub_tables: for i in range(len(_sql_executed_sub_table['rows'])): for j in range(len(_sql_executed_sub_table['rows'][i])): _cell = _sql_executed_sub_table['rows'][i][j] if _cell in passage_linker.keys(): _sql_executed_sub_table['rows'][i][j] += " ({})".format( # Add passage text as backup info db.get_passage_by_title(passage_linker[_cell])) if _cell in image_linker.keys(): _sql_executed_sub_table['rows'][i][j] += " ({})".format( # Add image caption as backup info db.get_image_caption_by_title(image_linker[_cell])) # _sql_executed_sub_table['rows'][i][j] += " (The answer of '{}' is {})".format( # # Add image qa result as backup info # question[len("***@"):], # vqa_call(question=question[len("***@"):], # image_path=db.get_image_by_title(image_linker[_cell]))) pass if question.lower().startswith("map@"): # When the question is a type of mapping, we return the mapped column. question = question[len("map@"):] if step.father: step.rename_father_col(col_idx=col_idx) sub_table: Dict = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="map", new_col_name_s=step.produced_col_name_s, verbose=verbose) db.add_sub_table(sub_table, verbose=verbose) col_idx += 1 else: # This step is the final step sub_table: Dict = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="map", new_col_name_s=["col_{}".format(col_idx)], verbose=verbose) return extract_answers(sub_table) elif question.lower().startswith("ans@"): # When the question is a type of answering, we return an answer list. question = question[len("ans@"):] answer: List = self.qa_model.qa(question, sql_executed_sub_tables, table_title=db.table_title, qa_type="ans", verbose=verbose) if step.father: step.rename_father_val(answer) else: # This step is the final step return answer else: raise ValueError( "Except for operators or NL question must start with 'map@' or 'ans@'!, check '{}'".format( question)) else: sub_table = self.sql_exec(nsql, db, verbose=verbose) return extract_answers(sub_table) def post_process_sql(sql_str, df, table_title=None, process_program_with_fuzzy_match_on_db=True, verbose=False): """Post process SQL: including basic fix and further fuzzy match on cell and SQL to process""" def basic_fix(sql_str, all_headers, table_title=None): def finditer(sub_str: str, mother_str: str): result = [] start_index = 0 while True: start_index = mother_str.find(sub_str, start_index, -1) if start_index == -1: break end_idx = start_index + len(sub_str) result.append((start_index, end_idx)) start_index = end_idx return result if table_title: sql_str = sql_str.replace("FROM " + table_title, "FROM w") sql_str = sql_str.replace("FROM " + table_title.lower(), "FROM w") """Case 1: Fix the `` missing. """ # Remove the null header. while '' in all_headers: all_headers.remove('') # Remove the '\n' in header. # This is because the WikiTQ won't actually show the str in two lines, # they use '\n' to mean that, and display it in the same line when print. sql_str = sql_str.replace("\\n", "\n") sql_str = sql_str.replace("\n", "\\n") # Add `` in SQL. all_headers.sort(key=lambda x: len(x), reverse=True) have_matched = [0 for i in range(len(sql_str))] # match quotation idx_s_single_quotation = [_ for _ in range(1, len(sql_str)) if sql_str[_] in ["\'"] and sql_str[_ - 1] not in ["\'"]] idx_s_double_quotation = [_ for _ in range(1, len(sql_str)) if sql_str[_] in ["\""] and sql_str[_ - 1] not in ["\""]] for idx_s in [idx_s_single_quotation, idx_s_double_quotation]: if len(idx_s) % 2 == 0: for idx in range(int(len(idx_s) / 2)): start_idx = idx_s[idx * 2] end_idx = idx_s[idx * 2 + 1] have_matched[start_idx: end_idx] = [2 for _ in range(end_idx - start_idx)] # match headers for header in all_headers: if (header in sql_str) and (header not in ALL_KEY_WORDS): all_matched_of_this_header = finditer(header, sql_str) for matched_of_this_header in all_matched_of_this_header: start_idx, end_idx = matched_of_this_header if all(have_matched[start_idx: end_idx]) == 0 and (not sql_str[start_idx - 1] == "`") and ( not sql_str[end_idx] == "`"): have_matched[start_idx: end_idx] = [1 for _ in range(end_idx - start_idx)] # a bit ugly, but anyway. # re-compose sql from the matched idx. start_have_matched = [0] + have_matched end_have_matched = have_matched + [0] start_idx_s = [idx - 1 for idx in range(1, len(start_have_matched)) if start_have_matched[idx - 1] == 0 and start_have_matched[idx] == 1] end_idx_s = [idx for idx in range(len(end_have_matched) - 1) if end_have_matched[idx] == 1 and end_have_matched[idx + 1] == 0] assert len(start_idx_s) == len(end_idx_s) spans = [] current_idx = 0 for start_idx, end_idx in zip(start_idx_s, end_idx_s): spans.append(sql_str[current_idx:start_idx]) spans.append(sql_str[start_idx:end_idx + 1]) current_idx = end_idx + 1 spans.append(sql_str[current_idx:]) sql_str = '`'.join(spans) return sql_str def fuzzy_match_process(sql_str, df, verbose=False): """ Post-process SQL by fuzzy matching value with table contents. """ def _get_matched_cells(value_str, df, fuzz_threshold=70): """ Get matched table cells with value token. """ matched_cells = [] for row_id, row in df.iterrows(): for cell in row: cell = str(cell) fuzz_score = fuzz.ratio(value_str, cell) if fuzz_score == 100: matched_cells = [(cell, fuzz_score)] return matched_cells if fuzz_score >= fuzz_threshold: matched_cells.append((cell, fuzz_score)) matched_cells = sorted(matched_cells, key=lambda x: x[1], reverse=True) return matched_cells def _check_valid_fuzzy_match(value_str, matched_cell): """ Check if the fuzzy match is valid, now considering: 1. The number/date should not be disturbed, but adding new number or deleting number is valid. """ number_pattern = "[+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?" numbers_in_value = re.findall(number_pattern, value_str) numbers_in_matched_cell = re.findall(number_pattern, matched_cell) try: numbers_in_value = [float(num.replace(',', '')) for num in numbers_in_value] except: print(f"Can't convert number string {numbers_in_value} into float in _check_valid_fuzzy_match().") try: numbers_in_matched_cell = [float(num.replace(',', '')) for num in numbers_in_matched_cell] except: print( f"Can't convert number string {numbers_in_matched_cell} into float in _check_valid_fuzzy_match().") numbers_in_value = set(numbers_in_value) numbers_in_matched_cell = set(numbers_in_matched_cell) if numbers_in_value.issubset(numbers_in_matched_cell) or numbers_in_matched_cell.issubset(numbers_in_value): return True else: return False # Drop trailing '\n```', a pattern that may appear in Codex SQL generation sql_str = sql_str.rstrip('```').rstrip('\n') # Replace QA module with placeholder qa_pattern = "QA\(.+?;.*?`.+?`.*?\)" qas = re.findall(qa_pattern, sql_str) for idx, qa in enumerate(qas): sql_str = sql_str.replace(qa, f"placeholder{idx}") # Parse and replace SQL value with table contents sql_tokens = tokenize(sql_str) sql_template_tokens = extract_partial_template_from_sql(sql_str) # Fix 'between' keyword bug in parsing templates fixed_sql_template_tokens = [] sql_tok_bias = 0 for idx, sql_templ_tok in enumerate(sql_template_tokens): sql_tok = sql_tokens[idx + sql_tok_bias] if sql_tok == 'between' and sql_templ_tok == '[WHERE_OP]': fixed_sql_template_tokens.extend(['[WHERE_OP]', '[VALUE]', 'and']) sql_tok_bias += 2 # pass '[VALUE]', 'and' else: fixed_sql_template_tokens.append(sql_templ_tok) sql_template_tokens = fixed_sql_template_tokens for idx, tok in enumerate(sql_tokens): if tok in ALL_KEY_WORDS: sql_tokens[idx] = tok.upper() if verbose: print(sql_tokens) print(sql_template_tokens) assert len(sql_tokens) == len(sql_template_tokens) value_indices = [idx for idx in range(len(sql_template_tokens)) if sql_template_tokens[idx] == '[VALUE]'] for value_idx in value_indices: # Skip the value if the where condition column is QA module if value_idx >= 2 and sql_tokens[value_idx - 2].startswith('placeholder'): continue value_str = sql_tokens[value_idx] # Drop \"\" for fuzzy match is_string = False if value_str[0] == "\"" and value_str[-1] == "\"": value_str = value_str[1:-1] is_string = True # If already fuzzy match, skip if value_str[0] == '%' or value_str[-1] == '%': continue value_str = value_str.lower() # Fuzzy Match matched_cells = _get_matched_cells(value_str, df) if verbose: print(matched_cells) new_value_str = value_str if matched_cells: # new_value_str = matched_cells[0][0] for matched_cell, fuzz_score in matched_cells: if _check_valid_fuzzy_match(value_str, matched_cell): new_value_str = matched_cell if verbose and new_value_str != value_str: print("\tfuzzy match replacing!", value_str, '->', matched_cell, f'fuzz_score:{fuzz_score}') break if is_string: new_value_str = f"\"{new_value_str}\"" sql_tokens[value_idx] = new_value_str # Compose new sql string # Clean column name in SQL since columns may have been tokenized in the postprocessing, e.g., (ppp) -> ( ppp ) new_sql_str = ' '.join(sql_tokens) sql_columns = re.findall('`\s(.*?)\s`', new_sql_str) for sql_col in sql_columns: matched_columns = [] for col in df.columns: score = fuzz.ratio(sql_col.lower(), col) if score == 100: matched_columns = [(col, score)] break if score >= 80: matched_columns.append((col, score)) matched_columns = sorted(matched_columns, key=lambda x: x[1], reverse=True) if matched_columns: matched_col = matched_columns[0][0] new_sql_str = new_sql_str.replace(f"` {sql_col} `", f"`{matched_col}`") else: new_sql_str = new_sql_str.replace(f"` {sql_col} `", f"`{sql_col}`") # Restore QA modules for idx, qa in enumerate(qas): new_sql_str = new_sql_str.replace(f"placeholder{idx}", qa) # Fix '<>' when composing the new sql new_sql_str = new_sql_str.replace('< >', '<>') return new_sql_str sql_str = basic_fix(sql_str, list(df.columns), table_title) if process_program_with_fuzzy_match_on_db: try: sql_str = fuzzy_match_process(sql_str, df, verbose) except: pass return sql_str The provided code snippet includes necessary dependencies for implementing the `worker_execute` function. Write a Python function `def worker_execute( pid, args, dataset, nsql_dict, keys )` to solve the following problem: A worker process for execution. Here is the function: def worker_execute( pid, args, dataset, nsql_dict, keys ): """ A worker process for execution. """ result_dict = dict() n_total_samples, n_correct_samples = 0, 0 for eid, data_item in enumerate(dataset): eid = str(eid) if eid not in nsql_dict: continue print(f"Process#{pid}: eid {eid}, wtq-id {data_item['id']}") result_dict[eid] = dict() result_dict[eid]['question'] = data_item['question'] result_dict[eid]['gold_answer'] = data_item['answer_text'] n_total_samples += 1 table = data_item['table'] title = table['page_title'] executor = Executor(args, keys) # Execute exec_answer_list = [] nsql_exec_answer_dict = dict() for idx, (nsql, logprob) in enumerate(nsql_dict[eid]['nsqls']): print(f"Process#{pid}: eid {eid}, original_id {data_item['id']}, executing program#{idx}, logprob={logprob}") n_nsql = nsql n_nsql = nsql.strip().split('\n') nsql = None for sql_idx,nsql in enumerate(n_nsql): if sql_idx != 0: nsql = nsql[12:].strip() try: if nsql in nsql_exec_answer_dict: exec_answer = nsql_exec_answer_dict[nsql] else: db = NeuralDB( tables=[{"title": title, "table": table}] ) print(nsql) # nsql = "SELECT COUNT(*) FROM w WHERE `directed by` = 'david moore'" # print(nsql) nsql = post_process_sql( sql_str=nsql, df=db.get_table_df(), process_program_with_fuzzy_match_on_db=args.process_program_with_fuzzy_match_on_db, table_title=title ) # print(db) exec_answer = executor.nsql_exec(nsql, db, verbose=args.verbose) # print(nsql) # exec_answer = executor.sql_exec(nsql, db, verbose=args.verbose) # exec_answer = executor.sql_exec(nsql, db) print('*'*20) print(exec_answer) print('-'*20) if isinstance(exec_answer, str): exec_answer = [exec_answer] nsql_exec_answer_dict[nsql] = exec_answer exec_answer_list.append(exec_answer) except Exception as e: print(f"Process#{pid}: Execution error {e}") exec_answer = '<error>' exec_answer_list.append(exec_answer) # Store tmp execution answers if nsql_dict[eid].get('exec_answers', None) is None: nsql_dict[eid]['exec_answers'] = {} if nsql_dict[eid]['exec_answers'].get(str(sql_idx), None) is None: nsql_dict[eid]['exec_answers'][str(sql_idx)] = [] nsql_dict[eid]['exec_answers'][str(sql_idx)].append(exec_answer) # Majority vote to determine the final prediction answer # pred_answer, pred_answer_nsqls = majority_vote( # nsqls=nsql_dict[eid]['nsqls'], # pred_answer_list=exec_answer_list, # allow_none_and_empty_answer=args.allow_none_and_empty_answer, # answer_placeholder=args.answer_placeholder, # vote_method=args.vote_method, # answer_biased=args.answer_biased, # answer_biased_weight=args.answer_biased_weight # ) # Evaluate # result_dict[eid]['pred_answer'] = pred_answer # result_dict[eid]['nsql'] = pred_answer_nsqls # gold_answer = data_item['answer_text'] # score = Evaluator().evaluate( # pred_answer, # gold_answer, # dataset=args.dataset, # question=result_dict[eid]['question'] # ) result_dict[eid]['pred_answer'] = nsql_dict[eid]['exec_answers'] result_dict[eid]['nsql'] = nsql_dict[eid]['nsqls'] # n_correct_samples += score # print(f'Process#{pid}: pred answer: {pred_answer}') # print(f'Process#{pid}: gold answer: {gold_answer}') # if score == 1: # print(f'Process#{pid}: Correct!') # else: # print(f'Process#{pid}: Wrong.') # print(f'Process#{pid}: Accuracy: {n_correct_samples}/{n_total_samples}') return result_dict
A worker process for execution.
165,106
import json import os from typing import List, Union, Dict from functools import cmp_to_key import math from collections.abc import Iterable from datasets import load_dataset ROOT_DIR = os.path.join(os.path.dirname(__file__), "../") def load_data_split(dataset_to_load, split, data_dir=os.path.join(ROOT_DIR, 'datasets/')): dataset_split_loaded = load_dataset( path=os.path.join(data_dir, "{}.py".format(dataset_to_load)), cache_dir=os.path.join(data_dir, "data"))[split] # unify names of keys if dataset_to_load in ['wikitq', 'has_squall', 'missing_squall', 'wikitq', 'wikitq_sql_solvable', 'wikitq_sql_unsolvable', 'wikitq_sql_unsolvable_but_in_squall', 'wikitq_scalability_ori', 'wikitq_scalability_100rows', 'wikitq_scalability_200rows', 'wikitq_scalability_500rows', 'wikitq_robustness' ]: pass elif dataset_to_load == 'tab_fact': new_dataset_split_loaded = [] for data_item in dataset_split_loaded: data_item['question'] = data_item['statement'] data_item['answer_text'] = data_item['label'] data_item['table']['page_title'] = data_item['table']['caption'] new_dataset_split_loaded.append(data_item) dataset_split_loaded = new_dataset_split_loaded elif dataset_to_load == 'hybridqa': new_dataset_split_loaded = [] for data_item in dataset_split_loaded: data_item['table']['page_title'] = data_item['context'].split(' | ')[0] new_dataset_split_loaded.append(data_item) dataset_split_loaded = new_dataset_split_loaded elif dataset_to_load == 'mmqa': new_dataset_split_loaded = [] for data_item in dataset_split_loaded: data_item['table']['page_title'] = data_item['table']['title'] new_dataset_split_loaded.append(data_item) dataset_split_loaded = new_dataset_split_loaded else: raise ValueError(f'{dataset_to_load} dataset is not supported now.') return dataset_split_loaded
null
165,107
import json import os from typing import List, Union, Dict from functools import cmp_to_key import math from collections.abc import Iterable from datasets import load_dataset def pprint_dict(dic): print(json.dumps(dic, indent=2))
null
165,108
import json import os from typing import List, Union, Dict from functools import cmp_to_key import math from collections.abc import Iterable from datasets import load_dataset def flatten(nested_list): for x in nested_list: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): yield from flatten(x) else: yield x
null
165,109
from typing import List, Dict import pandas as pd import recognizers_suite from recognizers_suite import Culture import re import unicodedata from fuzzywuzzy import fuzz from utils.sql.extraction_from_sql import * from utils.sql.all_keywords import ALL_KEY_WORDS def convert_df_type(df: pd.DataFrame, lower_case=True): """ A simple converter of dataframe data type from string to int/float/datetime. """ def get_table_content_in_column(table): if isinstance(table, pd.DataFrame): header = table.columns.tolist() rows = table.values.tolist() else: # Standard table dict format header, rows = table['header'], table['rows'] all_col_values = [] for i in range(len(header)): one_col_values = [] for _row in rows: one_col_values.append(_row[i]) all_col_values.append(one_col_values) return all_col_values # Rename empty columns new_columns = [] for idx, header in enumerate(df.columns): if header == '': new_columns.append('FilledColumnName') # Fixme: give it a better name when all finished! else: new_columns.append(header) df.columns = new_columns # Rename duplicate columns new_columns = [] for idx, header in enumerate(df.columns): if header in new_columns: new_header, suffix = header, 2 while new_header in new_columns: new_header = header + '_' + str(suffix) suffix += 1 new_columns.append(new_header) else: new_columns.append(header) df.columns = new_columns # Recognize null values like "-" null_tokens = ['', '-', '/'] for header in df.columns: df[header] = df[header].map(lambda x: str(None) if x in null_tokens else x) # Convert the null values in digit column to "NaN" all_col_values = get_table_content_in_column(df) for col_i, one_col_values in enumerate(all_col_values): all_number_flag = True for row_i, cell_value in enumerate(one_col_values): try: float(cell_value) except Exception as e: if not cell_value in [str(None), str(None).lower()]: # None or none all_number_flag = False if all_number_flag: _header = df.columns[col_i] df[_header] = df[_header].map(lambda x: "NaN" if x in [str(None), str(None).lower()] else x) # Normalize cell values. for header in df.columns: df[header] = df[header].map(lambda x: str_normalize(x)) # Strip the mis-added "01-01 00:00:00" all_col_values = get_table_content_in_column(df) for col_i, one_col_values in enumerate(all_col_values): all_with_00_00_00 = True all_with_01_00_00_00 = True all_with_01_01_00_00_00 = True for row_i, cell_value in enumerate(one_col_values): if not str(cell_value).endswith(" 00:00:00"): all_with_00_00_00 = False if not str(cell_value).endswith("-01 00:00:00"): all_with_01_00_00_00 = False if not str(cell_value).endswith("-01-01 00:00:00"): all_with_01_01_00_00_00 = False if all_with_01_01_00_00_00: _header = df.columns[col_i] df[_header] = df[_header].map(lambda x: x[:-len("-01-01 00:00:00")]) continue if all_with_01_00_00_00: _header = df.columns[col_i] df[_header] = df[_header].map(lambda x: x[:-len("-01 00:00:00")]) continue if all_with_00_00_00: _header = df.columns[col_i] df[_header] = df[_header].map(lambda x: x[:-len(" 00:00:00")]) continue # Do header and cell value lower case if lower_case: new_columns = [] for header in df.columns: lower_header = str(header).lower() if lower_header in new_columns: new_header, suffix = lower_header, 2 while new_header in new_columns: new_header = lower_header + '-' + str(suffix) suffix += 1 new_columns.append(new_header) else: new_columns.append(lower_header) df.columns = new_columns for header in df.columns: # df[header] = df[header].map(lambda x: str(x).lower()) df[header] = df[header].map(lambda x: str(x).lower().strip()) # Recognize header type for header in df.columns: float_able = False int_able = False datetime_able = False # Recognize int & float type try: df[header].astype("float") float_able = True except: pass if float_able: try: if all(df[header].astype("float") == df[header].astype(int)): int_able = True except: pass if float_able: if int_able: df[header] = df[header].astype(int) else: df[header] = df[header].astype(float) # Recognize datetime type try: df[header].astype("datetime64") datetime_able = True except: pass if datetime_able: df[header] = df[header].astype("datetime64") return df def prepare_df_for_neuraldb_from_table(table: Dict, add_row_id=True, normalize=True, lower_case=True): header, rows = table['header'], table['rows'] if add_row_id and 'row_id' not in header: header = ["row_id"] + header rows = [["{}".format(i)] + row for i, row in enumerate(rows)] if normalize: df = convert_df_type(pd.DataFrame(data=rows, columns=header), lower_case=lower_case) else: df = pd.DataFrame(data=rows, columns=header) return df
null
165,110
from typing import List, Dict import pandas as pd import recognizers_suite from recognizers_suite import Culture import re import unicodedata from fuzzywuzzy import fuzz from utils.sql.extraction_from_sql import * from utils.sql.all_keywords import ALL_KEY_WORDS The provided code snippet includes necessary dependencies for implementing the `normalize` function. Write a Python function `def normalize(x)` to solve the following problem: Normalize string. Here is the function: def normalize(x): """ Normalize string. """ # Copied from WikiTableQuestions dataset official evaluator. if x is None: return None # Remove diacritics x = ''.join(c for c in unicodedata.normalize('NFKD', x) if unicodedata.category(c) != 'Mn') # Normalize quotes and dashes x = re.sub("[‘’´`]", "'", x) x = re.sub("[“”]", "\"", x) x = re.sub("[‐‑‒–—−]", "-", x) while True: old_x = x # Remove citations x = re.sub("((?<!^)\[[^\]]*\]|\[\d+\]|[•♦†‡*#+])*$", "", x.strip()) # Remove details in parenthesis x = re.sub("(?<!^)( \([^)]*\))*$", "", x.strip()) # Remove outermost quotation mark x = re.sub('^"([^"]*)"$', r'\1', x.strip()) if x == old_x: break # Remove final '.' if x and x[-1] == '.': x = x[:-1] # Collapse whitespaces and convert to lower case x = re.sub('\s+', ' ', x, flags=re.U).lower().strip() return x
Normalize string.
165,114
import json import sqlite3 from nltk import word_tokenize def tokenize(string): string = str(string) string = string.replace("\'", "\"") # ensures all string values wrapped by "" problem?? quote_idxs = [idx for idx, char in enumerate(string) if char == '"'] assert len(quote_idxs) % 2 == 0, "Unexpected quote" # keep string value as token vals = {} for i in range(len(quote_idxs)-1, -1, -2): qidx1 = quote_idxs[i-1] qidx2 = quote_idxs[i] val = string[qidx1: qidx2+1] key = "__val_{}_{}__".format(qidx1, qidx2) string = string[:qidx1] + key + string[qidx2+1:] vals[key] = val # tokenize sql toks_tmp = [word.lower() for word in word_tokenize(string)] toks = [] for tok in toks_tmp: if tok.startswith('=__val_'): tok = tok[1:] toks.append('=') toks.append(tok) # replace with string value token for i in range(len(toks)): if toks[i] in vals: toks[i] = vals[toks[i]] # find if there exists !=, >=, <= eq_idxs = [idx for idx, tok in enumerate(toks) if tok == "="] eq_idxs.reverse() prefix = ('!', '>', '<') for eq_idx in eq_idxs: pre_tok = toks[eq_idx-1] if pre_tok in prefix: toks = toks[:eq_idx-1] + [pre_tok + "="] + toks[eq_idx+1: ] return toks def get_tables_with_alias(schema, toks): tables = scan_alias(toks) for key in schema: assert key not in tables, "Alias {} has the same name in table".format(key) tables[key] = key return tables def parse_sql(toks, start_idx, tables_with_alias, schema): isBlock = False # indicate whether this is a block of sql/sub-sql len_ = len(toks) idx = start_idx sql = {} if toks[idx] == '(': isBlock = True idx += 1 # parse from clause in order to get default tables from_end_idx, table_units, conds, default_tables = parse_from(toks, start_idx, tables_with_alias, schema) sql['from'] = {'table_units': table_units, 'conds': conds} # select clause _, select_col_units = parse_select(toks, idx, tables_with_alias, schema, default_tables) idx = from_end_idx sql['select'] = select_col_units # where clause idx, where_conds = parse_where(toks, idx, tables_with_alias, schema, default_tables) sql['where'] = where_conds # group by clause idx, group_col_units = parse_group_by(toks, idx, tables_with_alias, schema, default_tables) sql['groupBy'] = group_col_units # having clause idx, having_conds = parse_having(toks, idx, tables_with_alias, schema, default_tables) sql['having'] = having_conds # order by clause idx, order_col_units = parse_order_by(toks, idx, tables_with_alias, schema, default_tables) sql['orderBy'] = order_col_units # limit clause idx, limit_val = parse_limit(toks, idx) sql['limit'] = limit_val idx = skip_semicolon(toks, idx) if isBlock: assert toks[idx] == ')' idx += 1 # skip ')' idx = skip_semicolon(toks, idx) # intersect/union/except clause for op in SQL_OPS: # initialize IUE sql[op] = None if idx < len_ and toks[idx] in SQL_OPS: sql_op = toks[idx] idx += 1 idx, IUE_sql = parse_sql(toks, idx, tables_with_alias, schema) sql[sql_op] = IUE_sql return idx, sql def get_sql(schema, query): toks = tokenize(query) tables_with_alias = get_tables_with_alias(schema.schema, toks) _, sql = parse_sql(toks, 0, tables_with_alias, schema) return sql
null
165,115
import json import sqlite3 from nltk import word_tokenize def get_schemas_from_json(fpath): with open(fpath) as f: data = json.load(f) db_names = [db['db_id'] for db in data] tables = {} schemas = {} for db in data: db_id = db['db_id'] schema = {} #{'table': [col.lower, ..., ]} * -> __all__ column_names_original = db['column_names_original'] table_names_original = db['table_names_original'] tables[db_id] = {'column_names_original': column_names_original, 'table_names_original': table_names_original} for i, tabn in enumerate(table_names_original): table = str(tabn.lower()) cols = [str(col.lower()) for td, col in column_names_original if td == i] schema[table] = cols schemas[db_id] = schema return schemas, db_names, tables
null
165,116
import argparse import json from utils.sql.process_sql import ( tokenize, CLAUSE_KEYWORDS, WHERE_OPS, COND_OPS, UNIT_OPS, AGG_OPS, JOIN_KEYWORDS, ORDER_OPS, skip_semicolon, SQL_OPS) def parse_sql(toks, start_idx, schema): isBlock = False # indicate whether this is a block of sql/sub-sql len_ = len(toks) idx = start_idx if toks[idx] == '(': isBlock = True idx += 1 from_end_idx, default_tables, tables_with_alias = parse_from(toks, start_idx, schema) _ = parse_select(toks, idx, tables_with_alias, schema, default_tables) idx = from_end_idx idx = parse_where(toks, idx, tables_with_alias, schema, default_tables) idx = parse_group_by(toks, idx, tables_with_alias, schema, default_tables) idx = parse_having(toks, idx, tables_with_alias, schema, default_tables) idx = parse_order_by(toks, idx, tables_with_alias, schema, default_tables) idx = parse_limit(toks, idx) # idx = skip_semicolon(toks, idx) if isBlock: assert toks[idx] == ')' idx += 1 # skip ')' idx = skip_semicolon(toks, idx) # for op in SQL_OPS: # initialize IUE # sql[op] = None if idx < len_ and toks[idx] in SQL_OPS: sql_op = toks[idx] idx += 1 idx = parse_sql(toks, idx, schema) # sql[sql_op] = IUE_sql return idx def tokenize(string): string = str(string) string = string.replace("\'", "\"") # ensures all string values wrapped by "" problem?? quote_idxs = [idx for idx, char in enumerate(string) if char == '"'] assert len(quote_idxs) % 2 == 0, "Unexpected quote" # keep string value as token vals = {} for i in range(len(quote_idxs)-1, -1, -2): qidx1 = quote_idxs[i-1] qidx2 = quote_idxs[i] val = string[qidx1: qidx2+1] key = "__val_{}_{}__".format(qidx1, qidx2) string = string[:qidx1] + key + string[qidx2+1:] vals[key] = val # tokenize sql toks_tmp = [word.lower() for word in word_tokenize(string)] toks = [] for tok in toks_tmp: if tok.startswith('=__val_'): tok = tok[1:] toks.append('=') toks.append(tok) # replace with string value token for i in range(len(toks)): if toks[i] in vals: toks[i] = vals[toks[i]] # find if there exists !=, >=, <= eq_idxs = [idx for idx, tok in enumerate(toks) if tok == "="] eq_idxs.reverse() prefix = ('!', '>', '<') for eq_idx in eq_idxs: pre_tok = toks[eq_idx-1] if pre_tok in prefix: toks = toks[:eq_idx-1] + [pre_tok + "="] + toks[eq_idx+1: ] return toks def extract_schema_from_sql(schema, sql): toks = tokenize(sql) parse_sql(toks=toks, start_idx=0, schema=schema) return toks
null
165,117
import argparse import json from utils.sql.process_sql import ( tokenize, CLAUSE_KEYWORDS, WHERE_OPS, COND_OPS, UNIT_OPS, AGG_OPS, JOIN_KEYWORDS, ORDER_OPS, skip_semicolon, SQL_OPS) KEPT_WHERE_OP = ('not', 'in', 'exists') CLAUSE_KEYWORDS = ('select', 'from', 'where', 'group', 'order', 'limit', 'intersect', 'union', 'except') WHERE_OPS = ('not', 'between', '=', '>', '<', '>=', '<=', '!=', 'in', 'like', 'is', 'exists') AGG_OPS = ('none', 'max', 'min', 'count', 'sum', 'avg') COND_OPS = ('and', 'or') def tokenize(string): string = str(string) string = string.replace("\'", "\"") # ensures all string values wrapped by "" problem?? quote_idxs = [idx for idx, char in enumerate(string) if char == '"'] assert len(quote_idxs) % 2 == 0, "Unexpected quote" # keep string value as token vals = {} for i in range(len(quote_idxs)-1, -1, -2): qidx1 = quote_idxs[i-1] qidx2 = quote_idxs[i] val = string[qidx1: qidx2+1] key = "__val_{}_{}__".format(qidx1, qidx2) string = string[:qidx1] + key + string[qidx2+1:] vals[key] = val # tokenize sql toks_tmp = [word.lower() for word in word_tokenize(string)] toks = [] for tok in toks_tmp: if tok.startswith('=__val_'): tok = tok[1:] toks.append('=') toks.append(tok) # replace with string value token for i in range(len(toks)): if toks[i] in vals: toks[i] = vals[toks[i]] # find if there exists !=, >=, <= eq_idxs = [idx for idx, tok in enumerate(toks) if tok == "="] eq_idxs.reverse() prefix = ('!', '>', '<') for eq_idx in eq_idxs: pre_tok = toks[eq_idx-1] if pre_tok in prefix: toks = toks[:eq_idx-1] + [pre_tok + "="] + toks[eq_idx+1: ] return toks def extract_template_from_sql(sql, schema={}): try: toks = tokenize(sql) except: print("Tokenization error for {}".format(sql)) toks = [] # print(toks) template = [] # ignore_follow_up_and = False len_ = len(toks) idx = 0 while idx < len_: tok = toks[idx] if tok == "from": template.append(tok) if toks[idx+1] != "(": template.append("[FROM_PART]") idx += 1 while idx < len_ and (toks[idx] not in CLAUSE_KEYWORDS and toks[idx] != ")"): idx += 1 continue elif tok in CLAUSE_KEYWORDS: template.append(tok) elif tok in AGG_OPS: template.append(tok) elif tok in [",", "*", "(", ")", "having", "by", "distinct"]: template.append(tok) elif tok in ["asc", "desc"]: template.append("[ORDER_DIRECTION]") elif tok in WHERE_OPS: if tok in KEPT_WHERE_OP: template.append(tok) else: template.append("[WHERE_OP]") if tok == "between": idx += 2 elif tok in COND_OPS: template.append(tok) elif template[-1] == "[WHERE_OP]": template.append("[VALUE]") elif template[-1] == "limit": template.append("[LIMIT_VALUE]") elif template[-1] != "[MASK]": # value, schema, join on as template.append("[MASK]") idx += 1 return template
null
165,118
import argparse import json from utils.sql.process_sql import ( tokenize, CLAUSE_KEYWORDS, WHERE_OPS, COND_OPS, UNIT_OPS, AGG_OPS, JOIN_KEYWORDS, ORDER_OPS, skip_semicolon, SQL_OPS) KEPT_WHERE_OP = ('not', 'in', 'exists') CLAUSE_KEYWORDS = ('select', 'from', 'where', 'group', 'order', 'limit', 'intersect', 'union', 'except') WHERE_OPS = ('not', 'between', '=', '>', '<', '>=', '<=', '!=', 'in', 'like', 'is', 'exists') AGG_OPS = ('none', 'max', 'min', 'count', 'sum', 'avg') COND_OPS = ('and', 'or') def tokenize(string): string = str(string) string = string.replace("\'", "\"") # ensures all string values wrapped by "" problem?? quote_idxs = [idx for idx, char in enumerate(string) if char == '"'] assert len(quote_idxs) % 2 == 0, "Unexpected quote" # keep string value as token vals = {} for i in range(len(quote_idxs)-1, -1, -2): qidx1 = quote_idxs[i-1] qidx2 = quote_idxs[i] val = string[qidx1: qidx2+1] key = "__val_{}_{}__".format(qidx1, qidx2) string = string[:qidx1] + key + string[qidx2+1:] vals[key] = val # tokenize sql toks_tmp = [word.lower() for word in word_tokenize(string)] toks = [] for tok in toks_tmp: if tok.startswith('=__val_'): tok = tok[1:] toks.append('=') toks.append(tok) # replace with string value token for i in range(len(toks)): if toks[i] in vals: toks[i] = vals[toks[i]] # find if there exists !=, >=, <= eq_idxs = [idx for idx, tok in enumerate(toks) if tok == "="] eq_idxs.reverse() prefix = ('!', '>', '<') for eq_idx in eq_idxs: pre_tok = toks[eq_idx-1] if pre_tok in prefix: toks = toks[:eq_idx-1] + [pre_tok + "="] + toks[eq_idx+1: ] return toks def extract_partial_template_from_sql(sql, schema={}): toks = tokenize(sql) # print(toks) template = [] # ignore_follow_up_and = False len_ = len(toks) idx = 0 while idx < len_: tok = toks[idx] if tok == "from": template.append(tok) if toks[idx+1] != "(": # template.append("[FROM_PART]") idx += 1 while idx < len_ and (toks[idx] not in CLAUSE_KEYWORDS and toks[idx] != ")"): template.append(toks[idx]) idx += 1 continue elif tok in CLAUSE_KEYWORDS: template.append(tok) elif tok in AGG_OPS: template.append(tok) elif tok in [",", "*", "(", ")", "having", "by", "distinct"]: template.append(tok) elif tok in ["asc", "desc"]: template.append("[ORDER_DIRECTION]") elif tok in WHERE_OPS: if tok in KEPT_WHERE_OP: template.append(tok) else: template.append("[WHERE_OP]") if tok == "between": idx += 2 elif tok in COND_OPS: template.append(tok) elif template[-1] == "[WHERE_OP]": template.append("[VALUE]") elif template[-1] == "limit": template.append("[LIMIT_VALUE]") else: template.append(tok) idx += 1 return template
null
165,119
import argparse import json from utils.sql.process_sql import ( tokenize, CLAUSE_KEYWORDS, WHERE_OPS, COND_OPS, UNIT_OPS, AGG_OPS, JOIN_KEYWORDS, ORDER_OPS, skip_semicolon, SQL_OPS) CLAUSE_KEYWORDS = ('select', 'from', 'where', 'group', 'order', 'limit', 'intersect', 'union', 'except') def is_valid_schema(schema): # There is no "." and " " in the column name for table in schema: if "." in table: return False if any([keyword == table for keyword in CLAUSE_KEYWORDS]): return False for column in schema[table]: if "." in column or " " in column or '"' in column or "'" in column: return False return True
null
165,120
import argparse import json from utils.sql.process_sql import ( tokenize, CLAUSE_KEYWORDS, WHERE_OPS, COND_OPS, UNIT_OPS, AGG_OPS, JOIN_KEYWORDS, ORDER_OPS, skip_semicolon, SQL_OPS) def clean_sql(sql): while "JOIN JOIN" in sql: sql = sql.replace("JOIN JOIN", "JOIN") if "JOIN WHERE" in sql: sql = sql.replace("JOIN WHERE", "WHERE") if "JOIN GROUP BY" in sql: sql = sql.replace("JOIN GROUP BY", "GROUP BY") return sql
null
165,125
import re import json import records from typing import List, Dict from sqlalchemy.exc import SQLAlchemyError from utils.sql.all_keywords import ALL_KEY_WORDS def process_table_structure(_wtq_table_content: Dict, _add_all_column: bool = False): # remove id and agg column headers = [_.replace("\n", " ").lower() for _ in _wtq_table_content["headers"][2:]] header_map = {} for i in range(len(headers)): header_map["c" + str(i + 1)] = headers[i] header_types = _wtq_table_content["types"][2:] all_headers = [] all_header_types = [] vertical_content = [] for column_content in _wtq_table_content["contents"][2:]: # only take the first one if _add_all_column: for i in range(len(column_content)): column_alias = column_content[i]["col"] # do not add the numbered column if "_number" in column_alias: continue vertical_content.append([str(_).replace("\n", " ").lower() for _ in column_content[i]["data"]]) if "_" in column_alias: first_slash_pos = column_alias.find("_") column_name = header_map[column_alias[:first_slash_pos]] + " " + \ column_alias[first_slash_pos + 1:].replace("_", " ") else: column_name = header_map[column_alias] all_headers.append(column_name) if column_content[i]["type"] == "TEXT": all_header_types.append("text") else: all_header_types.append("number") else: vertical_content.append([str(_).replace("\n", " ").lower() for _ in column_content[0]["data"]]) row_content = list(map(list, zip(*vertical_content))) if _add_all_column: ret_header = all_headers ret_types = all_header_types else: ret_header = headers ret_types = header_types return { "header": ret_header, "rows": row_content, "types": ret_types, "alias": list(_wtq_table_content["is_list"].keys()) }
null
165,126
import re import json import records from typing import List, Dict from sqlalchemy.exc import SQLAlchemyError from utils.sql.all_keywords import ALL_KEY_WORDS ALL_KEY_WORDS = CLAUSE_KEYWORDS + JOIN_KEYWORDS + WHERE_OPS + UNIT_OPS + AGG_OPS def retrieve_wtq_query_answer(_engine, _table_content, _sql_struct: List): # do not append id / agg headers = _table_content["header"] def flatten_sql(_ex_sql_struct: List): # [ "Keyword", "select", [] ], [ "Column", "c4", [] ] _encode_sql = [] _execute_sql = [] for _ex_tuple in _ex_sql_struct: keyword = str(_ex_tuple[1]) # upper the keywords. if keyword in ALL_KEY_WORDS: keyword = str(keyword).upper() # extra column, which we do not need in result if keyword == "w" or keyword == "from": # add 'FROM w' make it executable _encode_sql.append(keyword) elif re.fullmatch(r"c\d+(_.+)?", keyword): # only take the first part index_key = int(keyword.split("_")[0][1:]) - 1 # wrap it with `` to make it executable _encode_sql.append("`{}`".format(headers[index_key])) else: _encode_sql.append(keyword) # c4_list, replace it with the original one if "_address" in keyword or "_list" in keyword: keyword = re.findall(r"c\d+", keyword)[0] _execute_sql.append(keyword) return " ".join(_execute_sql), " ".join(_encode_sql) _exec_sql_str, _encode_sql_str = flatten_sql(_sql_struct) try: _sql_answers = _engine.execute_wtq_query(_exec_sql_str) except SQLAlchemyError as e: _sql_answers = [] _norm_sql_answers = [str(_).replace("\n", " ") for _ in _sql_answers if _ is not None] if "none" in _norm_sql_answers: _norm_sql_answers = [] return _encode_sql_str, _norm_sql_answers, _exec_sql_str
null
165,127
import re import json import records from typing import List, Dict from sqlalchemy.exc import SQLAlchemyError from utils.sql.all_keywords import ALL_KEY_WORDS def _load_table(table_path) -> dict: """ attention: the table_path must be the .tsv path. Load the WikiTableQuestion from csv file. Result in a dict format like: {"header": [header1, header2,...], "rows": [[row11, row12, ...], [row21,...]... [...rownm]]} """ def __extract_content(_line: str): _vals = [_.replace("\n", " ").strip() for _ in _line.strip("\n").split("\t")] return _vals with open(table_path, "r") as f: lines = f.readlines() rows = [] for i, line in enumerate(lines): line = line.strip('\n') if i == 0: header = line.split("\t") else: rows.append(__extract_content(line)) table_item = {"header": header, "rows": rows} # Defense assertion for i in range(len(rows) - 1): if not len(rows[i]) == len(rows[i - 1]): raise ValueError('some rows have diff cols.') return table_item The provided code snippet includes necessary dependencies for implementing the `_load_table_w_page` function. Write a Python function `def _load_table_w_page(table_path, page_title_path=None) -> dict` to solve the following problem: attention: the table_path must be the .tsv path. Load the WikiTableQuestion from csv file. Result in a dict format like: {"header": [header1, header2,...], "rows": [[row11, row12, ...], [row21,...]... [...rownm]]} Here is the function: def _load_table_w_page(table_path, page_title_path=None) -> dict: """ attention: the table_path must be the .tsv path. Load the WikiTableQuestion from csv file. Result in a dict format like: {"header": [header1, header2,...], "rows": [[row11, row12, ...], [row21,...]... [...rownm]]} """ from utils.utils import _load_table table_item = _load_table(table_path) # Load page title if not page_title_path: page_title_path = table_path.replace("csv", "page").replace(".tsv", ".json") with open(page_title_path, "r") as f: page_title = json.load(f)['title'] table_item['page_title'] = page_title return table_item
attention: the table_path must be the .tsv path. Load the WikiTableQuestion from csv file. Result in a dict format like: {"header": [header1, header2,...], "rows": [[row11, row12, ...], [row21,...]... [...rownm]]}
165,128
from typing import Dict,List import pandas as pd The provided code snippet includes necessary dependencies for implementing the `table_linearization` function. Write a Python function `def table_linearization(table: pd.DataFrame, format:str='codex')` to solve the following problem: linearization table according to format. Here is the function: def table_linearization(table: pd.DataFrame, format:str='codex'): """ linearization table according to format. """ assert format in ['tapex', 'codex'] linear_table = '' if format == 'tapex': header = 'col : ' + ' | '.join(table.columns) + ' ' linear_table += header rows = table.values.tolist() for row_idx,row in enumerate(rows): line = 'row {} : '.format(row_idx + 1) + ' | '.join(rows) + ' ' line += '\n' linear_table += line elif format == 'codex': header = 'col : ' + ' | '.join(table.columns) + '\n' linear_table += header rows = table.values.tolist() for row_idx,row in enumerate(rows): line = 'row {} : '.format(row_idx + 1) + ' | '.join(row) if row_idx != len(rows) - 1: line += '\n' linear_table += line return linear_table
linearization table according to format.