id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
163,348
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata The provided code snippet includes necessary dependencies for implementing the `load_vocab` function. Write a Python function `def load_vocab(vocab_file)` to solve the following problem: Loads a vocabulary file into a dictionary. Here is the function: def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with open(vocab_file, "r", encoding="utf-8") as reader: while True: token = reader.readline() if not token: break token = token.strip() vocab[token] = index index += 1 return vocab
Loads a vocabulary file into a dictionary.
163,349
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata The provided code snippet includes necessary dependencies for implementing the `whitespace_tokenize` function. Write a Python function `def whitespace_tokenize(text)` to solve the following problem: Runs basic whitespace cleaning and splitting on a piece of text. Here is the function: def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
Runs basic whitespace cleaning and splitting on a piece of text.
163,350
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata The provided code snippet includes necessary dependencies for implementing the `_is_whitespace` function. Write a Python function `def _is_whitespace(char)` to solve the following problem: Checks whether `chars` is a whitespace character. Here is the function: def _is_whitespace(char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False
Checks whether `chars` is a whitespace character.
163,351
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata The provided code snippet includes necessary dependencies for implementing the `_is_control` function. Write a Python function `def _is_control(char)` to solve the following problem: Checks whether `chars` is a control character. Here is the function: def _is_control(char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False
Checks whether `chars` is a control character.
163,352
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata The provided code snippet includes necessary dependencies for implementing the `_is_punctuation` function. Write a Python function `def _is_punctuation(char)` to solve the following problem: Checks whether `chars` is a punctuation character. Here is the function: def _is_punctuation(char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): return True cat = unicodedata.category(char) if cat.startswith("P"): return True return False
Checks whether `chars` is a punctuation character.
163,353
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata def lru_cache(): return lambda func: func
null
163,354
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the following problem: Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. Here is the function: def bytes_to_unicode(): """ Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. """ _chr = unichr if sys.version_info[0] == 2 else chr bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) cs = bs[:] n = 0 for b in range(2**8): if b not in bs: bs.append(b) cs.append(2**8+n) n += 1 cs = [_chr(n) for n in cs] return dict(zip(bs, cs))
Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on.
163,355
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import os import regex as re import sys import unicodedata The provided code snippet includes necessary dependencies for implementing the `get_pairs` function. Write a Python function `def get_pairs(word)` to solve the following problem: Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). Here is the function: def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
163,356
from itertools import chain import json import numpy as np import pickle import time import subprocess as sp from tqdm import tqdm from galaxy.args import str2bool from galaxy.data.tokenizer import Tokenizer def max_lens(X): lens = [len(X)] while isinstance(X[0], list): lens.append(max(map(len, X))) X = [x for xs in X for x in xs] return lens def list2np(X, padding=0, dtype="int64"): shape = max_lens(X) ret = np.full(shape, padding, dtype=np.int32) if len(shape) == 1: ret = np.array(X) elif len(shape) == 2: for i, x in enumerate(X): ret[i, :len(x)] = np.array(x) elif len(shape) == 3: for i, xs in enumerate(X): for j, x in enumerate(xs): ret[i, j, :len(x)] = np.array(x) return ret.astype(dtype)
null
163,357
from itertools import chain import json import numpy as np import pickle import time import subprocess as sp from tqdm import tqdm from galaxy.args import str2bool from galaxy.data.tokenizer import Tokenizer def _get_file_len(corpus): n_line = int(sp.check_output(f"wc -l {corpus}".split(), universal_newlines=True).split()[0]) return n_line
null
163,358
import os import random from collections import OrderedDict, defaultdict from itertools import chain import json import sqlite3 as sql import numpy as np import spacy from tqdm import tqdm from nltk.tokenize import word_tokenize as nltk_word_tokenize from nltk.stem import WordNetLemmatizer from galaxy.args import str2bool from galaxy.data.tokenizer import Tokenizer from galaxy.utils import ontology, utils from galaxy.utils.db_ops import MultiWozDB from galaxy.utils.ontologies import CamRest676Ontology, KvretOntology def max_lens(X): lens = [len(X)] while isinstance(X[0], list): lens.append(max(map(len, X))) X = [x for xs in X for x in xs] return lens def list2np(X, padding=0, dtype="int64"): shape = max_lens(X) ret = np.full(shape, padding, dtype=np.int32) if len(shape) == 1: ret = np.array(X) elif len(shape) == 2: for i, x in enumerate(X): ret[i, :len(x)] = np.array(x) elif len(shape) == 3: for i, xs in enumerate(X): for j, x in enumerate(xs): ret[i, j, :len(x)] = np.array(x) return ret.astype(dtype)
null
163,360
import argparse import json class HParams(dict): """ Hyper-parameters class Store hyper-parameters in training / infer / ... scripts. """ def __getattr__(self, name): if name in self.keys(): return self[name] for v in self.values(): if isinstance(v, HParams): if name in v: return v[name] raise AttributeError(f"'HParams' object has no attribute '{name}'") def __setattr__(self, name, value): self[name] = value def save(self, filename): with open(filename, "w", encoding="utf-8") as fp: json.dump(self, fp, ensure_ascii=False, indent=4, sort_keys=False) def load(self, filename): with open(filename, "r", encoding="utf-8") as fp: params_dict = json.load(fp) for k, v in params_dict.items(): if isinstance(v, dict): self[k].update(HParams(v)) else: self[k] = v The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args(parser)` to solve the following problem: Parse hyper-parameters from cmdline. Here is the function: def parse_args(parser): """ Parse hyper-parameters from cmdline. """ parsed = parser.parse_args() args = HParams() optional_args = parser._action_groups[1] for action in optional_args._group_actions[1:]: arg_name = action.dest args[arg_name] = getattr(parsed, arg_name) for group in parser._action_groups[2:]: group_args = HParams() for action in group._group_actions: arg_name = action.dest group_args[arg_name] = getattr(parsed, arg_name) if len(group_args) > 0: args[group.title] = group_args return args
Parse hyper-parameters from cmdline.
163,361
import json import logging import os import sys import time from collections import OrderedDict import torch import numpy as np from tqdm import tqdm from transformers.optimization import AdamW, get_linear_schedule_with_warmup from galaxy.args import str2bool from galaxy.data.data_loader import DataLoader from galaxy.metrics.metrics_tracker import MetricsTracker def get_logger(log_path, name="default"): logger = logging.getLogger(name) logger.propagate = False logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(message)s") sh = logging.StreamHandler(sys.stdout) sh.setFormatter(formatter) logger.addHandler(sh) fh = logging.FileHandler(log_path, mode="w") fh.setFormatter(formatter) logger.addHandler(fh) return logger
null
163,362
import logging import os import sys import time from collections import OrderedDict import torch import numpy as np from transformers.optimization import AdamW, get_linear_schedule_with_warmup from galaxy.args import str2bool from galaxy.data.data_loader import DataLoader from galaxy.metrics.metrics_tracker import MetricsTracker def get_logger(log_path, name="default"): logger = logging.getLogger(name) logger.propagate = False logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(message)s") sh = logging.StreamHandler(sys.stdout) sh.setFormatter(formatter) logger.addHandler(sh) fh = logging.FileHandler(log_path, mode="w") fh.setFormatter(formatter) logger.addHandler(fh) return logger
null
163,363
import math import torch import numpy as np from galaxy.args import str2bool def repeat(var, times): if isinstance(var, list): return [repeat(x, times) for x in var] elif isinstance(var, dict): return {k: repeat(v, times) for k, v in var.items()} elif isinstance(var, torch.Tensor): var = var.unsqueeze(1) expand_times = [1] * len(var.shape) expand_times[1] = times dtype = var.dtype var = var.float() var = var.repeat(*expand_times) shape = [var.shape[0] * var.shape[1]] + list(var.shape[2:]) var = var.reshape(*shape) var = torch.tensor(var, dtype=dtype) return var else: return var
null
163,364
import math import torch import numpy as np from galaxy.args import str2bool def gather(var, idx): if isinstance(var, list): return [gather(x, idx) for x in var] elif isinstance(var, dict): return {k: gather(v, idx) for k, v in var.items()} elif isinstance(var, torch.Tensor): out = var.index_select(dim=0, index=idx) return out else: return var
null
163,365
import logging import json import numpy as np from collections import OrderedDict from galaxy.utils import ontology def clean_replace(s, r, t, forward=True, backward=False): def clean_replace_single(s, r, t, forward, backward, sidx=0): # idx = s[sidx:].find(r) idx = s.find(r) if idx == -1: return s, -1 idx_r = idx + len(r) if backward: while idx > 0 and s[idx - 1]: idx -= 1 elif idx > 0 and s[idx - 1] != ' ': return s, -1 if forward: while idx_r < len(s) and (s[idx_r].isalpha() or s[idx_r].isdigit()): idx_r += 1 elif idx_r != len(s) and (s[idx_r].isalpha() or s[idx_r].isdigit()): return s, -1 return s[:idx] + t + s[idx_r:], idx_r # source, replace, target = s, r, t # count = 0 sidx = 0 while sidx != -1: s, sidx = clean_replace_single(s, r, t, forward, backward, sidx) # count += 1 # print(s, sidx) # if count == 20: # print(source, '\n', replace, '\n', target) # quit() return s
null
163,366
import logging import json import numpy as np from collections import OrderedDict from galaxy.utils import ontology def py2np(list): return np.array(list)
null
163,367
import logging import json import numpy as np from collections import OrderedDict from galaxy.utils import ontology def write_dict(fn, dic): with open(fn, 'w') as f: json.dump(dic, f, indent=2)
null
163,368
def get_special_tokens(data_name): if data_name == 'multiwoz': db_tokens = ['<sos_db>', '<eos_db>', '[db_nores]', '[db_0]', '[db_1]', '[db_2]', '[db_3]', '[book_nores]', '[book_fail]', '[book_success]'] special_tokens = ['<go_r>', '<go_b>', '<go_a>', '<eos_u>', '<eos_r>', '<eos_b>', '<eos_a>', '<go_d>', '<eos_d>', '<sos_u>', '<sos_r>', '<sos_b>', '<sos_a>', '<sos_d>'] + db_tokens + \ ['<sos_q>', '<eos_q>'] elif data_name == 'kvret': db_tokens = ['<sos_db>', '<eos_db>', '[db_0]', '[db_1]', '[db_2]', '[db_3]', '[db_4]'] special_tokens = ['<go_r>', '<go_b>', '<go_a>', '<eos_u>', '<eos_r>', '<eos_b>', '<eos_a>', '<go_d>', '<eos_d>', '<sos_u>', '<sos_r>', '<sos_b>', '<sos_a>', '<sos_d>'] + db_tokens + \ [] elif data_name == 'camrest': db_tokens = ['<sos_db>', '<eos_db>', '[db_nores]', '[db_0]', '[db_1]', '[db_2]', '[db_3]', '[db_4]'] special_tokens = ['<go_r>', '<go_b>', '<go_a>', '<eos_u>', '<eos_r>', '<eos_b>', '<eos_a>', '<go_d>', '<eos_d>', '<sos_u>', '<sos_r>', '<sos_b>', '<sos_a>', '<sos_d>'] + db_tokens + \ [] else: raise ValueError("Can't support other dataset!") return special_tokens
null
163,369
import torch from torch.nn.modules.loss import _Loss import torch.nn.functional as F def compute_kl_loss(p, q, filter_scores=None): p_loss = F.kl_div(F.log_softmax(p, dim=-1), F.softmax(q, dim=-1), reduction='none') q_loss = F.kl_div(F.log_softmax(q, dim=-1), F.softmax(p, dim=-1), reduction='none') # You can choose whether to use function "sum" and "mean" depending on your task p_loss = p_loss.sum(dim=-1) q_loss = q_loss.sum(dim=-1) # mask is for filter mechanism if filter_scores is not None: p_loss = filter_scores * p_loss q_loss = filter_scores * q_loss p_loss = p_loss.mean() q_loss = q_loss.mean() loss = (p_loss + q_loss) / 2 return loss
null
163,370
import re from galaxy.utils import ontology def my_clean_text(text): text = re.sub(r'([a-zT]+)\.([a-z])', r'\1 . \2', text) # 'abc.xyz' -> 'abc . xyz' text = re.sub(r'(\w+)\.\.? ', r'\1 . ', text) # if 'abc. ' -> 'abc . ' return text
null
163,371
import json import math from collections import Counter import numpy as np from nltk.util import ngrams from sklearn.metrics import f1_score from galaxy.utils import ontology, utils from galaxy.utils.clean_dataset import clean_slot_values def setsub(a,b): def setsim(a,b): a,b = set(a),set(b) return setsub(a,b) and setsub(b,a)
null
163,372
import json import math from collections import Counter import numpy as np from nltk.util import ngrams from sklearn.metrics import f1_score from galaxy.utils import ontology, utils from galaxy.utils.clean_dataset import clean_slot_values def DAEvaluation(preds, labels): preds = np.array(preds) labels = np.array(labels) results = {} # for avg_name in ['micro', 'macro', 'weighted', 'samples']: for avg_name in ['micro']: my_f1_score = f1_score(y_true=labels, y_pred=preds, average=avg_name) results["f1_{}".format(avg_name)] = my_f1_score return results
null
163,373
from typing import Dict, Any from third_party.sparc.evaluation import * def evaluate(glist, plist, db_dir, etype, kmaps): def compute_interaction_metric(predictions, references) -> Dict[str, Any]: foreign_key_maps = dict() for reference in references: if reference["db_id"] not in foreign_key_maps: foreign_key_maps[reference["db_id"]] = build_foreign_key_map( { "table_names_original": reference["db_table_names"], "column_names_original": list( zip( reference["db_column_names"]["table_id"], reference["db_column_names"]["column_name"], ) ), "foreign_keys": list( zip( reference["db_foreign_keys"]["column_id"], reference["db_foreign_keys"]["other_column_id"], ) ), } ) g_turns_list = [] p_turns_list = [] g_turns = [] p_turns = [] flag = True for prediction, reference in zip(predictions, references): turn_idx = reference.get("turn_idx", 0) # skip final utterance-query pairs, and add the stored predictions and references if turn_idx < 0: if flag: flag = False # skip the very beginning else: g_turns_list.append(g_turns) p_turns_list.append(p_turns) g_turns, p_turns = [], [] else: g_turns.append((reference['query'].lower().replace("! =", "!=").replace("where where", "where"), reference['db_id'])) p_turns.append((prediction.lower().replace("! =", "!=").replace("where where", "where"), reference['db_id'])) g_turns_list.append(g_turns) # add the last turn p_turns_list.append(p_turns) scores = evaluate(g_turns_list, p_turns_list, references[0]["db_path"], "all", foreign_key_maps) return { "interaction_exact_match": scores['joint_all']['exact'], "interaction_exec": scores['joint_all']['exec'], }
null
163,374
from typing import Dict, Any from third_party.spider import evaluation as spider_evaluation def compute_exact_match_metric(predictions, references) -> Dict[str, Any]: foreign_key_maps = dict() for reference in references: if reference["db_id"] not in foreign_key_maps: foreign_key_maps[reference["db_id"]] = spider_evaluation.build_foreign_key_map( { "table_names_original": reference["db_table_names"], "column_names_original": list( zip( reference["db_column_names"]["table_id"], reference["db_column_names"]["column_name"], ) ), "foreign_keys": list( zip( reference["db_foreign_keys"]["column_id"], reference["db_foreign_keys"]["other_column_id"], ) ), } ) evaluator = spider_evaluation.Evaluator(references[0]["db_path"], foreign_key_maps, "match") for prediction, reference in zip(predictions, references): turn_idx = reference.get("turn_idx", 0) # skip final utterance-query pairs if turn_idx < 0: continue _ = evaluator.evaluate_one(reference["db_id"], reference["query"], prediction) evaluator.finalize() spider_evaluation.print_scores(evaluator.scores, "match") return { "exact_match": evaluator.scores["all"]["exact"], "exact_scores": evaluator.scores, }
null
163,375
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def serialize_schema_natural_language( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], db_primary_keys, db_foreign_keys, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: def serialize_schema( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], schema_serialization_type: str = "peteshaw", schema_serialization_randomized: bool = False, schema_serialization_with_db_id: bool = True, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: def cosql_add_serialized_schema(ex: dict, args) -> dict: if getattr(args.seq2seq, "schema_serialization_with_nl"): serialized_schema = serialize_schema_natural_language( question=" | ".join(ex["utterances"]), db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], db_primary_keys=ex["db_primary_keys"], db_foreign_keys=ex["db_foreign_keys"], schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) else: serialized_schema = serialize_schema( question=" | ".join(ex["utterances"]), db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], schema_serialization_type="peteshaw", schema_serialization_randomized=False, schema_serialization_with_db_id=True, schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) return {"serialized_schema": serialized_schema}
null
163,376
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def cosql_get_input( utterances: List[str], serialized_schema: str, prefix: str, sep: str = " | ", ) -> str: # "[prefix] [utterance n] [serialized schema] || [utterance n-1] | [utterance n-2] | ..." if len(utterances) > 1: reversed_utterance_head = (utterance.strip() for utterance in reversed(utterances[:-1])) serialized_reversed_utterance_head = " || " + sep.join(reversed_utterance_head) else: serialized_reversed_utterance_head = "" return prefix + utterances[-1].strip() + " " + serialized_schema.strip() + serialized_reversed_utterance_head def cosql_get_target( query: str, db_id: str, normalize_query: bool, target_with_db_id: bool, ) -> str: _normalize = normalize if normalize_query else (lambda x: x) return f"{db_id} | {_normalize(query)}" if target_with_db_id else _normalize(query) def cosql_pre_process_function(batch: dict, args): prefix = "" inputs = [ cosql_get_input( question=question, serialized_schema=serialized_schema, prefix=prefix ) for question, serialized_schema in zip( batch["question"], batch["serialized_schema"] ) ] targets = [ cosql_get_target( query=query, db_id=db_id, normalize_query=True, target_with_db_id=args.seq2seq.target_with_db_id, ) for db_id, query in zip(batch["db_id"], batch["query"]) ] return zip(inputs, targets)
null
163,377
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def construct_prompt(old_prompt, num_prompt_tokens): token_list = old_prompt.split() new_token_list = [] for token in token_list: new_token_list.append(token) for i in range(1, num_prompt_tokens): new_token_list.append(f"[{token[1:-1]}_{i}]") new_prompt = " ".join(new_token_list) return new_prompt
null
163,378
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): ''' input: sql_query output: { "select": the select clause "from": the from clause ... } assumption: only one intersect/union/except ''' def keywords_fix(s): s = s.replace("group by", "group_by") s = s.replace("order by", "order_by") return s sql_query = keywords_fix(normalize(sql_query)) num = 0 nested = {} while "(select" in sql_query: # has nested sql num += 1 left_index = sql_query.index("(select") right_index = -1 flag = -1 for i in range(left_index + 7, len(sql_query)): flag = flag - 1 if sql_query[i] == "(" else flag flag = flag + 1 if sql_query[i] == ")" else flag if flag == 0: right_index = i + 1 break assert flag == 0, "sql query is not correct!" nested["{}#{}".format(NESTED_SYMBOL, num)] = remove_alias(sql_query[left_index: right_index]) sql_query = sql_query.replace(sql_query[left_index: right_index], "{}#{}".format(NESTED_SYMBOL, num)) has_two_sql = False set_index = 0 set_ops = list(set(sql_query.split()).intersection(set(SET_OPS))) if len(set_ops) > 0: # assume only one intersect/union/except set_index = sql_query.index(set_ops[0]) has_two_sql = True if has_two_sql: first_sql_query = remove_alias(sql_query[:set_index - 1]) second_sql_query = remove_alias(sql_query[set_index + len(set_ops[0]) + 1:]) main = f"{first_sql_query} {set_ops[0]} {second_sql_query}" while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(first_sql_query, nested)) while NESTED_SYMBOL in second_sql_query: num = second_sql_query[second_sql_query.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] second_sql_query = second_sql_query.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict.update({"SQL": f"{set_ops[0]} {second_sql_query}"}) else: sql_query = remove_alias(sql_query) main = sql_query while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(sql_query, nested)) sql_dict.update({"SQL": ""}) return sql_dict def build_data_train(item, sql_dict, args): prefix = "" question = cosql_get_utterances( utterances=item["utterances"], prefix=prefix, ) schema = item.pop("serialized_schema") task2prompt = {} for key, value in vars(args.prompt).items(): if "sql" in key: task2prompt[key.replace("sql", "SQL")] = value else: task2prompt[key] = value keyword2sp_tokens = {} for key, value in vars(args.special_tokens).items(): if "sql" in key: keyword2sp_tokens[key.replace("sql", "SQL")] = value else: keyword2sp_tokens[key] = value seq_out_main = sql_dict.pop("main") if args.target.with_special_tokens: for keyword in CLAUSE_KEYWORDS: seq_out_main = seq_out_main.replace(keyword, keyword2sp_tokens[keyword]) for set_op in SET_OPS: seq_out_main = seq_out_main.replace(set_op, keyword2sp_tokens[set_op]) prompt_main = args.prompt.main text_in = prompt_main + " " + question data = {} data["main"] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out_main, "type": "main", "empty": False, } if args.tasks.task == "main": return data for task in args.tasks.task.split(","): prompt = task2prompt[task] if task != "main": empty = False seq_out = [] for key in prompt.split(): if sql_dict[key[1: -1]]: seq_out.append(sql_dict[key[1: -1]]) else: if args.target.with_empty_sp: seq_out.append(key[1: -1]) if not seq_out: empty = True seq_out = "[empty]" else: seq_out = " ".join(seq_out) if seq_out == prompt.replace("[", "").replace("]", ""): empty = True text_in = prompt + " " + question if args.target.with_special_tokens: for keyword in CLAUSE_KEYWORDS + ["SQL"]: seq_out = seq_out.replace(keyword, keyword2sp_tokens[keyword]) for set_op in SET_OPS: seq_out = seq_out.replace(set_op, keyword2sp_tokens[set_op]) data[task] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out.strip(), "type": task, "empty": empty, } return data def cosql_pre_process_one_function_train(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_train(item, sql_dict, args) return data
null
163,379
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): ''' input: sql_query output: { "select": the select clause "from": the from clause ... } assumption: only one intersect/union/except ''' def keywords_fix(s): s = s.replace("group by", "group_by") s = s.replace("order by", "order_by") return s sql_query = keywords_fix(normalize(sql_query)) num = 0 nested = {} while "(select" in sql_query: # has nested sql num += 1 left_index = sql_query.index("(select") right_index = -1 flag = -1 for i in range(left_index + 7, len(sql_query)): flag = flag - 1 if sql_query[i] == "(" else flag flag = flag + 1 if sql_query[i] == ")" else flag if flag == 0: right_index = i + 1 break assert flag == 0, "sql query is not correct!" nested["{}#{}".format(NESTED_SYMBOL, num)] = remove_alias(sql_query[left_index: right_index]) sql_query = sql_query.replace(sql_query[left_index: right_index], "{}#{}".format(NESTED_SYMBOL, num)) has_two_sql = False set_index = 0 set_ops = list(set(sql_query.split()).intersection(set(SET_OPS))) if len(set_ops) > 0: # assume only one intersect/union/except set_index = sql_query.index(set_ops[0]) has_two_sql = True if has_two_sql: first_sql_query = remove_alias(sql_query[:set_index - 1]) second_sql_query = remove_alias(sql_query[set_index + len(set_ops[0]) + 1:]) main = f"{first_sql_query} {set_ops[0]} {second_sql_query}" while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(first_sql_query, nested)) while NESTED_SYMBOL in second_sql_query: num = second_sql_query[second_sql_query.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] second_sql_query = second_sql_query.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict.update({"SQL": f"{set_ops[0]} {second_sql_query}"}) else: sql_query = remove_alias(sql_query) main = sql_query while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(sql_query, nested)) sql_dict.update({"SQL": ""}) return sql_dict def build_data_eval(item, sql_dict, args): prefix = "" question = cosql_get_utterances( utterances=item["utterances"], prefix=prefix, ) schema = item.pop("serialized_schema") task2prompt = {} for key, value in vars(args.prompt).items(): if "sql" in key: task2prompt[key.replace("sql", "SQL")] = value else: task2prompt[key] = value seq_out_main = sql_dict.pop("main") seq_out_main = seq_out_main.replace("group_by", "group by") seq_out_main = seq_out_main.replace("order_by", "order by") prompt_main = args.prompt.main text_in = prompt_main + " " + question data = {} data["main"] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out_main, "type": "main", "empty": False, } if args.tasks.task == "main": return data for task in args.tasks.task.split(","): prompt = task2prompt[task] if task != "main": empty = False seq_out = [] for key in prompt.split(): if sql_dict[key[1: -1]]: seq_out.append(sql_dict[key[1: -1]]) else: if args.target.with_empty_sp: seq_out.append(key[1: -1]) if not seq_out: empty = True seq_out = "empty" else: seq_out = " ".join(seq_out) if seq_out == prompt.replace("[", "").replace("]", ""): empty = True text_in = prompt + " " + question seq_out = seq_out.replace("group_by", "group by") seq_out = seq_out.replace("order_by", "order by") data[task] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out.strip(), "type": task, "empty": empty, } return data def cosql_pre_process_one_function_eval(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_eval(item, sql_dict, args) return data
null
163,380
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def _get_schemas(examples: Dataset) -> Dict[str, dict]: schemas: Dict[str, dict] = dict() for ex in examples: if ex["db_id"] not in schemas: schemas[ex["db_id"]] = { "db_table_names": ex["db_table_names"], "db_column_names": ex["db_column_names"], "db_column_types": ex["db_column_types"], "db_primary_keys": ex["db_primary_keys"], "db_foreign_keys": ex["db_foreign_keys"], } return schemas
null
163,381
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def balance_data(data, ratio=0.5): empty_data = [x for x in data if x["empty"]] print("len(empty_data): ", len(empty_data)) non_empty_data = [x for x in data if not x["empty"]] print("len(non_empty_data): ", len(non_empty_data)) if len(non_empty_data) / len(data) < ratio: num = int((1-ratio) * len(non_empty_data) / ratio) random.shuffle(empty_data) empty_data = empty_data[:num] print("len(empty_data): ", len(empty_data)) data = empty_data + non_empty_data random.shuffle(data) return data
null
163,382
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def serialize_schema_natural_language( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], db_primary_keys, db_foreign_keys, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: overall_description = f'{db_id} contains tables such as ' \ f'{", ".join([table_name.lower() if normalize_query else table_name for table_name in db_table_names])}.' table_description_primary_key_template = lambda table_name, primary_key: \ f'{primary_key} is the primary key.' table_description = lambda table_name, column_names: \ f'Table {table_name} has columns such as {", ".join(column_names)}.' value_description = lambda column_value_pairs: \ f'{"".join(["The {} contains values such as {}.".format(column, value) for column, value in column_value_pairs])}' foreign_key_description = lambda table_1, column_1, table_2, column_2: \ f'The {column_1} of {table_1} is the foreign key of {column_2} of {table_2}.' db_primary_keys = db_primary_keys["column_id"] db_foreign_keys = list(zip(db_foreign_keys["column_id"], db_foreign_keys["other_column_id"])) descriptions = [overall_description] db_table_name_strs = [] db_column_name_strs = [] value_sep = ", " for table_id, table_name in enumerate(db_table_names): table_name_str = table_name.lower() if normalize_query else table_name db_table_name_strs.append(table_name_str) columns = [] column_value_pairs = [] primary_keys = [] for column_id, (x, y) in enumerate(zip(db_column_names["table_id"], db_column_names["column_name"])): if column_id == 0: continue column_str = y.lower() if normalize_query else y db_column_name_strs.append(column_str) if x == table_id: columns.append(column_str) if column_id in db_primary_keys: primary_keys.append(column_str) if schema_serialization_with_db_content: matches = get_database_matches( question=question, table_name=table_name, column_name=y, db_path=(db_path + "/" + db_id + "/" + db_id + ".sqlite"), ) if matches: column_value_pairs.append((column_str, value_sep.join(matches))) table_description_columns_str = table_description(table_name_str, columns) descriptions.append(table_description_columns_str) table_description_primary_key_str = table_description_primary_key_template(table_name_str, ", ".join(primary_keys)) descriptions.append(table_description_primary_key_str) if len(column_value_pairs) > 0: value_description_str = value_description(column_value_pairs) descriptions.append(value_description_str) for x, y in db_foreign_keys: # get the table and column of x x_table_name = db_table_name_strs[db_column_names["table_id"][x]] x_column_name = db_column_name_strs[x] # get the table and column of y y_table_name = db_table_name_strs[db_column_names["table_id"][y]] y_column_name = db_column_name_strs[y] foreign_key_description_str = foreign_key_description(x_table_name, x_column_name, y_table_name, y_column_name) descriptions.append(foreign_key_description_str) return " ".join(descriptions) def serialize_schema( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], schema_serialization_type: str = "peteshaw", schema_serialization_randomized: bool = False, schema_serialization_with_db_id: bool = True, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: if schema_serialization_type == "verbose": db_id_str = "Database: {db_id}. " table_sep = ". " table_str = "Table: {table}. Columns: {columns}" column_sep = ", " column_str_with_values = "{column} ({values})" column_str_without_values = "{column}" value_sep = ", " elif schema_serialization_type == "peteshaw": # see https://github.com/google-research/language/blob/master/language/nqg/tasks/spider/append_schema.py#L42 db_id_str = " | {db_id}" table_sep = "" table_str = " | {table} : {columns}" column_sep = " , " column_str_with_values = "{column} ( {values} )" column_str_without_values = "{column}" value_sep = " , " else: raise NotImplementedError def get_column_str(table_name: str, column_name: str) -> str: column_name_str = column_name.lower() if normalize_query else column_name if schema_serialization_with_db_content: matches = get_database_matches( question=question, table_name=table_name, column_name=column_name, db_path=(db_path + "/" + db_id + "/" + db_id + ".sqlite"), ) if matches: return column_str_with_values.format( column=column_name_str, values=value_sep.join(matches) ) else: return column_str_without_values.format(column=column_name_str) else: return column_str_without_values.format(column=column_name_str) tables = [ table_str.format( table=table_name.lower() if normalize_query else table_name, columns=column_sep.join( map( lambda y: get_column_str(table_name=table_name, column_name=y[1]), filter( lambda y: y[0] == table_id, zip( db_column_names["table_id"], db_column_names["column_name"], ), ), ) ), ) for table_id, table_name in enumerate(db_table_names) ] if schema_serialization_randomized: random.shuffle(tables) if schema_serialization_with_db_id: serialized_schema = db_id_str.format(db_id=db_id) + table_sep.join(tables) else: serialized_schema = table_sep.join(tables) return serialized_schema def spider_add_serialized_schema(ex: dict, args) -> dict: if getattr(args.seq2seq, "schema_serialization_with_nl"): serialized_schema = serialize_schema_natural_language( question=ex["question"], db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], db_primary_keys=ex["db_primary_keys"], db_foreign_keys=ex["db_foreign_keys"], schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) else: serialized_schema = serialize_schema( question=ex["question"], db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], schema_serialization_type="peteshaw", schema_serialization_randomized=False, schema_serialization_with_db_id=True, schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) return {"serialized_schema": serialized_schema}
null
163,383
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def spider_get_input( question: str, serialized_schema: str, prefix: str, ) -> str: return prefix + question.strip() + " " + serialized_schema.strip() def spider_get_target( query: str, db_id: str, normalize_query: bool, target_with_db_id: bool, ) -> str: _normalize = normalize if normalize_query else (lambda x: x) return f"{db_id} | {_normalize(query)}" if target_with_db_id else _normalize(query) def spider_pre_process_function(batch: dict, args): prefix = "" inputs = [ spider_get_input( question=question, serialized_schema=serialized_schema, prefix=prefix ) for question, serialized_schema in zip( batch["question"], batch["serialized_schema"] ) ] targets = [ spider_get_target( query=query, db_id=db_id, normalize_query=True, target_with_db_id=args.seq2seq.target_with_db_id, ) for db_id, query in zip(batch["db_id"], batch["query"]) ] return zip(inputs, targets)
null
163,384
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): def build_data_train(item, sql_dict, args): def spider_pre_process_one_function_train(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_train(item, sql_dict, args) return data
null
163,385
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): def build_data_eval(item, sql_dict, args): def spider_pre_process_one_function_eval(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_eval(item, sql_dict, args) return data
null
163,388
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def serialize_schema_natural_language( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], db_primary_keys, db_foreign_keys, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: overall_description = f'{db_id} contains tables such as ' \ f'{", ".join([table_name.lower() if normalize_query else table_name for table_name in db_table_names])}.' table_description_primary_key_template = lambda table_name, primary_key: \ f'{primary_key} is the primary key.' table_description = lambda table_name, column_names: \ f'Table {table_name} has columns such as {", ".join(column_names)}.' value_description = lambda column_value_pairs: \ f'{"".join(["The {} contains values such as {}.".format(column, value) for column, value in column_value_pairs])}' foreign_key_description = lambda table_1, column_1, table_2, column_2: \ f'The {column_1} of {table_1} is the foreign key of {column_2} of {table_2}.' db_primary_keys = db_primary_keys["column_id"] db_foreign_keys = list(zip(db_foreign_keys["column_id"], db_foreign_keys["other_column_id"])) descriptions = [overall_description] db_table_name_strs = [] db_column_name_strs = [] value_sep = ", " for table_id, table_name in enumerate(db_table_names): table_name_str = table_name.lower() if normalize_query else table_name db_table_name_strs.append(table_name_str) columns = [] column_value_pairs = [] primary_keys = [] for column_id, (x, y) in enumerate(zip(db_column_names["table_id"], db_column_names["column_name"])): if column_id == 0: continue column_str = y.lower() if normalize_query else y db_column_name_strs.append(column_str) if x == table_id: columns.append(column_str) if column_id in db_primary_keys: primary_keys.append(column_str) if schema_serialization_with_db_content: matches = get_database_matches( question=question, table_name=table_name, column_name=y, db_path=(db_path + "/" + db_id + "/" + db_id + ".sqlite"), ) if matches: column_value_pairs.append((column_str, value_sep.join(matches))) table_description_columns_str = table_description(table_name_str, columns) descriptions.append(table_description_columns_str) table_description_primary_key_str = table_description_primary_key_template(table_name_str, ", ".join(primary_keys)) descriptions.append(table_description_primary_key_str) if len(column_value_pairs) > 0: value_description_str = value_description(column_value_pairs) descriptions.append(value_description_str) for x, y in db_foreign_keys: # get the table and column of x x_table_name = db_table_name_strs[db_column_names["table_id"][x]] x_column_name = db_column_name_strs[x] # get the table and column of y y_table_name = db_table_name_strs[db_column_names["table_id"][y]] y_column_name = db_column_name_strs[y] foreign_key_description_str = foreign_key_description(x_table_name, x_column_name, y_table_name, y_column_name) descriptions.append(foreign_key_description_str) return " ".join(descriptions) def serialize_schema( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], schema_serialization_type: str = "peteshaw", schema_serialization_randomized: bool = False, schema_serialization_with_db_id: bool = True, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: if schema_serialization_type == "verbose": db_id_str = "Database: {db_id}. " table_sep = ". " table_str = "Table: {table}. Columns: {columns}" column_sep = ", " column_str_with_values = "{column} ({values})" column_str_without_values = "{column}" value_sep = ", " elif schema_serialization_type == "peteshaw": # see https://github.com/google-research/language/blob/master/language/nqg/tasks/cosql/append_schema.py#L42 db_id_str = " | {db_id}" table_sep = "" table_str = " | {table} : {columns}" column_sep = " , " column_str_with_values = "{column} ( {values} )" column_str_without_values = "{column}" value_sep = " , " else: raise NotImplementedError def get_column_str(table_name: str, column_name: str) -> str: column_name_str = column_name.lower() if normalize_query else column_name if schema_serialization_with_db_content: matches = get_database_matches( question=question, table_name=table_name, column_name=column_name, db_path=(db_path + "/" + db_id + "/" + db_id + ".sqlite"), ) if matches: return column_str_with_values.format( column=column_name_str, values=value_sep.join(matches) ) else: return column_str_without_values.format(column=column_name_str) else: return column_str_without_values.format(column=column_name_str) tables = [ table_str.format( table=table_name.lower() if normalize_query else table_name, columns=column_sep.join( map( lambda y: get_column_str(table_name=table_name, column_name=y[1]), filter( lambda y: y[0] == table_id, zip( db_column_names["table_id"], db_column_names["column_name"], ), ), ) ), ) for table_id, table_name in enumerate(db_table_names) ] if schema_serialization_randomized: random.shuffle(tables) if schema_serialization_with_db_id: serialized_schema = db_id_str.format(db_id=db_id) + table_sep.join(tables) else: serialized_schema = table_sep.join(tables) return serialized_schema def cosql_add_serialized_schema(ex: dict, args) -> dict: if getattr(args.seq2seq, "schema_serialization_with_nl"): serialized_schema = serialize_schema_natural_language( question=" | ".join(ex["utterances"]), db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], db_primary_keys=ex["db_primary_keys"], db_foreign_keys=ex["db_foreign_keys"], schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) else: serialized_schema = serialize_schema( question=" | ".join(ex["utterances"]), db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], schema_serialization_type="peteshaw", schema_serialization_randomized=False, schema_serialization_with_db_id=True, schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) return {"serialized_schema": serialized_schema}
null
163,392
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): def build_data_eval(item, sql_dict, args): def cosql_pre_process_one_function_eval(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_eval(item, sql_dict, args) return data
null
163,395
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def serialize_schema_natural_language( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], db_primary_keys, db_foreign_keys, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: overall_description = f'{db_id} contains tables such as ' \ f'{", ".join([table_name.lower() if normalize_query else table_name for table_name in db_table_names])}.' table_description_primary_key_template = lambda table_name, primary_key: \ f'{primary_key} is the primary key.' table_description = lambda table_name, column_names: \ f'Table {table_name} has columns such as {", ".join(column_names)}.' value_description = lambda column_value_pairs: \ f'{"".join(["The {} contains values such as {}.".format(column, value) for column, value in column_value_pairs])}' foreign_key_description = lambda table_1, column_1, table_2, column_2: \ f'The {column_1} of {table_1} is the foreign key of {column_2} of {table_2}.' db_primary_keys = db_primary_keys["column_id"] db_foreign_keys = list(zip(db_foreign_keys["column_id"], db_foreign_keys["other_column_id"])) descriptions = [overall_description] db_table_name_strs = [] db_column_name_strs = [] value_sep = ", " for table_id, table_name in enumerate(db_table_names): table_name_str = table_name.lower() if normalize_query else table_name db_table_name_strs.append(table_name_str) columns = [] column_value_pairs = [] primary_keys = [] for column_id, (x, y) in enumerate(zip(db_column_names["table_id"], db_column_names["column_name"])): if column_id == 0: continue column_str = y.lower() if normalize_query else y db_column_name_strs.append(column_str) if x == table_id: columns.append(column_str) if column_id in db_primary_keys: primary_keys.append(column_str) if schema_serialization_with_db_content: matches = get_database_matches( question=question, table_name=table_name, column_name=y, db_path=(db_path + "/" + db_id + "/" + db_id + ".sqlite"), ) if matches: column_value_pairs.append((column_str, value_sep.join(matches))) table_description_columns_str = table_description(table_name_str, columns) descriptions.append(table_description_columns_str) table_description_primary_key_str = table_description_primary_key_template(table_name_str, ", ".join(primary_keys)) descriptions.append(table_description_primary_key_str) if len(column_value_pairs) > 0: value_description_str = value_description(column_value_pairs) descriptions.append(value_description_str) for x, y in db_foreign_keys: # get the table and column of x x_table_name = db_table_name_strs[db_column_names["table_id"][x]] x_column_name = db_column_name_strs[x] # get the table and column of y y_table_name = db_table_name_strs[db_column_names["table_id"][y]] y_column_name = db_column_name_strs[y] foreign_key_description_str = foreign_key_description(x_table_name, x_column_name, y_table_name, y_column_name) descriptions.append(foreign_key_description_str) return " ".join(descriptions) def serialize_schema( question: str, db_path: str, db_id: str, db_column_names: Dict[str, str], db_table_names: List[str], schema_serialization_type: str = "peteshaw", schema_serialization_randomized: bool = False, schema_serialization_with_db_id: bool = True, schema_serialization_with_db_content: bool = False, normalize_query: bool = True, ) -> str: if schema_serialization_type == "verbose": db_id_str = "Database: {db_id}. " table_sep = ". " table_str = "Table: {table}. Columns: {columns}" column_sep = ", " column_str_with_values = "{column} ({values})" column_str_without_values = "{column}" value_sep = ", " elif schema_serialization_type == "peteshaw": # see https://github.com/google-research/language/blob/master/language/nqg/tasks/sparc/append_schema.py#L42 db_id_str = " | {db_id}" table_sep = "" table_str = " | {table} : {columns}" column_sep = " , " column_str_with_values = "{column} ( {values} )" column_str_without_values = "{column}" value_sep = " , " else: raise NotImplementedError def get_column_str(table_name: str, column_name: str) -> str: column_name_str = column_name.lower() if normalize_query else column_name if schema_serialization_with_db_content: matches = get_database_matches( question=question, table_name=table_name, column_name=column_name, db_path=(db_path + "/" + db_id + "/" + db_id + ".sqlite"), ) if matches: return column_str_with_values.format( column=column_name_str, values=value_sep.join(matches) ) else: return column_str_without_values.format(column=column_name_str) else: return column_str_without_values.format(column=column_name_str) tables = [ table_str.format( table=table_name.lower() if normalize_query else table_name, columns=column_sep.join( map( lambda y: get_column_str(table_name=table_name, column_name=y[1]), filter( lambda y: y[0] == table_id, zip( db_column_names["table_id"], db_column_names["column_name"], ), ), ) ), ) for table_id, table_name in enumerate(db_table_names) ] if schema_serialization_randomized: random.shuffle(tables) if schema_serialization_with_db_id: serialized_schema = db_id_str.format(db_id=db_id) + table_sep.join(tables) else: serialized_schema = table_sep.join(tables) return serialized_schema def sparc_add_serialized_schema(ex: dict, args) -> dict: if getattr(args.seq2seq, "schema_serialization_with_nl"): serialized_schema = serialize_schema_natural_language( question=" | ".join(ex["utterances"]), db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], db_primary_keys=ex["db_primary_keys"], db_foreign_keys=ex["db_foreign_keys"], schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) else: serialized_schema = serialize_schema( question=" | ".join(ex["utterances"]), db_path=ex["db_path"], db_id=ex["db_id"], db_column_names=ex["db_column_names"], db_table_names=ex["db_table_names"], schema_serialization_type="peteshaw", schema_serialization_randomized=False, schema_serialization_with_db_id=True, schema_serialization_with_db_content=args.seq2seq.schema_serialization_with_db_content, normalize_query=True, ) return {"serialized_schema": serialized_schema}
null
163,396
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def sparc_get_input( utterances: List[str], serialized_schema: str, prefix: str, sep: str = " | ", ) -> str: # "[prefix] [utterance n] [serialized schema] || [utterance n-1] | [utterance n-2] | ..." if len(utterances) > 1: reversed_utterance_head = (utterance.strip() for utterance in reversed(utterances[:-1])) serialized_reversed_utterance_head = " || " + sep.join(reversed_utterance_head) else: serialized_reversed_utterance_head = "" return prefix + utterances[-1].strip() + " " + serialized_schema.strip() + serialized_reversed_utterance_head def sparc_get_target( query: str, db_id: str, normalize_query: bool, target_with_db_id: bool, ) -> str: _normalize = normalize if normalize_query else (lambda x: x) return f"{db_id} | {_normalize(query)}" if target_with_db_id else _normalize(query) def sparc_pre_process_function(batch: dict, args): prefix = "" inputs = [ sparc_get_input( question=question, serialized_schema=serialized_schema, prefix=prefix ) for question, serialized_schema in zip( batch["question"], batch["serialized_schema"] ) ] targets = [ sparc_get_target( query=query, db_id=db_id, normalize_query=True, target_with_db_id=args.seq2seq.target_with_db_id, ) for db_id, query in zip(batch["db_id"], batch["query"]) ] return zip(inputs, targets)
null
163,398
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): ''' input: sql_query output: { "select": the select clause "from": the from clause ... } assumption: only one intersect/union/except ''' def keywords_fix(s): s = s.replace("group by", "group_by") s = s.replace("order by", "order_by") return s sql_query = keywords_fix(normalize(sql_query)) num = 0 nested = {} while "(select" in sql_query: # has nested sql num += 1 left_index = sql_query.index("(select") right_index = -1 flag = -1 for i in range(left_index + 7, len(sql_query)): flag = flag - 1 if sql_query[i] == "(" else flag flag = flag + 1 if sql_query[i] == ")" else flag if flag == 0: right_index = i + 1 break assert flag == 0, "sql query is not correct!" nested["{}#{}".format(NESTED_SYMBOL, num)] = remove_alias(sql_query[left_index: right_index]) sql_query = sql_query.replace(sql_query[left_index: right_index], "{}#{}".format(NESTED_SYMBOL, num)) has_two_sql = False set_index = 0 set_ops = list(set(sql_query.split()).intersection(set(SET_OPS))) if len(set_ops) > 0: # assume only one intersect/union/except set_index = sql_query.index(set_ops[0]) has_two_sql = True if has_two_sql: first_sql_query = remove_alias(sql_query[:set_index - 1]) second_sql_query = remove_alias(sql_query[set_index + len(set_ops[0]) + 1:]) main = f"{first_sql_query} {set_ops[0]} {second_sql_query}" while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(first_sql_query, nested)) while NESTED_SYMBOL in second_sql_query: num = second_sql_query[second_sql_query.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] second_sql_query = second_sql_query.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict.update({"SQL": f"{set_ops[0]} {second_sql_query}"}) else: sql_query = remove_alias(sql_query) main = sql_query while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(sql_query, nested)) sql_dict.update({"SQL": ""}) return sql_dict def build_data_train(item, sql_dict, args): prefix = "" question = sparc_get_utterances( utterances=item["utterances"], prefix=prefix, ) schema = item.pop("serialized_schema") task2prompt = {} for key, value in vars(args.prompt).items(): if "sql" in key: task2prompt[key.replace("sql", "SQL")] = value else: task2prompt[key] = value keyword2sp_tokens = {} for key, value in vars(args.special_tokens).items(): if "sql" in key: keyword2sp_tokens[key.replace("sql", "SQL")] = value else: keyword2sp_tokens[key] = value seq_out_main = sql_dict.pop("main") if args.target.with_special_tokens: for keyword in CLAUSE_KEYWORDS: seq_out_main = seq_out_main.replace(keyword, keyword2sp_tokens[keyword]) for set_op in SET_OPS: seq_out_main = seq_out_main.replace(set_op, keyword2sp_tokens[set_op]) prompt_main = args.prompt.main text_in = prompt_main + " " + question data = {} data["main"] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out_main, "type": "main", "empty": False, } if args.tasks.task == "main": return data for task in args.tasks.task.split(","): prompt = task2prompt[task] if task != "main": empty = False seq_out = [] for key in prompt.split(): if sql_dict[key[1: -1]]: seq_out.append(sql_dict[key[1: -1]]) else: if args.target.with_empty_sp: seq_out.append(key[1: -1]) if not seq_out: empty = True seq_out = "[empty]" else: seq_out = " ".join(seq_out) if seq_out == prompt.replace("[", "").replace("]", ""): empty = True text_in = prompt + " " + question if args.target.with_special_tokens: for keyword in CLAUSE_KEYWORDS + ["SQL"]: seq_out = seq_out.replace(keyword, keyword2sp_tokens[keyword]) for set_op in SET_OPS: seq_out = seq_out.replace(set_op, keyword2sp_tokens[set_op]) data[task] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out.strip(), "type": task, "empty": empty, } return data def sparc_pre_process_one_function_train(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_train(item, sql_dict, args) return data
null
163,399
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): ''' input: sql_query output: { "select": the select clause "from": the from clause ... } assumption: only one intersect/union/except ''' def keywords_fix(s): s = s.replace("group by", "group_by") s = s.replace("order by", "order_by") return s sql_query = keywords_fix(normalize(sql_query)) num = 0 nested = {} while "(select" in sql_query: # has nested sql num += 1 left_index = sql_query.index("(select") right_index = -1 flag = -1 for i in range(left_index + 7, len(sql_query)): flag = flag - 1 if sql_query[i] == "(" else flag flag = flag + 1 if sql_query[i] == ")" else flag if flag == 0: right_index = i + 1 break assert flag == 0, "sql query is not correct!" nested["{}#{}".format(NESTED_SYMBOL, num)] = remove_alias(sql_query[left_index: right_index]) sql_query = sql_query.replace(sql_query[left_index: right_index], "{}#{}".format(NESTED_SYMBOL, num)) has_two_sql = False set_index = 0 set_ops = list(set(sql_query.split()).intersection(set(SET_OPS))) if len(set_ops) > 0: # assume only one intersect/union/except set_index = sql_query.index(set_ops[0]) has_two_sql = True if has_two_sql: first_sql_query = remove_alias(sql_query[:set_index - 1]) second_sql_query = remove_alias(sql_query[set_index + len(set_ops[0]) + 1:]) main = f"{first_sql_query} {set_ops[0]} {second_sql_query}" while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(first_sql_query, nested)) while NESTED_SYMBOL in second_sql_query: num = second_sql_query[second_sql_query.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] second_sql_query = second_sql_query.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict.update({"SQL": f"{set_ops[0]} {second_sql_query}"}) else: sql_query = remove_alias(sql_query) main = sql_query while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(sql_query, nested)) sql_dict.update({"SQL": ""}) return sql_dict def build_data_eval(item, sql_dict, args): prefix = "" question = sparc_get_utterances( utterances=item["utterances"], prefix=prefix, ) schema = item.pop("serialized_schema") task2prompt = {} for key, value in vars(args.prompt).items(): if "sql" in key: task2prompt[key.replace("sql", "SQL")] = value else: task2prompt[key] = value seq_out_main = sql_dict.pop("main") seq_out_main = seq_out_main.replace("group_by", "group by") seq_out_main = seq_out_main.replace("order_by", "order by") prompt_main = args.prompt.main text_in = prompt_main + " " + question data = {} data["main"] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out_main, "type": "main", "empty": False, } if args.tasks.task == "main": return data for task in args.tasks.task.split(","): prompt = task2prompt[task] if task != "main": empty = False seq_out = [] for key in prompt.split(): if sql_dict[key[1: -1]]: seq_out.append(sql_dict[key[1: -1]]) else: if args.target.with_empty_sp: seq_out.append(key[1: -1]) if not seq_out: empty = True seq_out = "empty" else: seq_out = " ".join(seq_out) if seq_out == prompt.replace("[", "").replace("]", ""): empty = True text_in = prompt + " " + question seq_out = seq_out.replace("group_by", "group by") seq_out = seq_out.replace("order_by", "order by") data[task] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out.strip(), "type": task, "empty": empty, } return data def sparc_pre_process_one_function_eval(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_eval(item, sql_dict, args) return data
null
163,402
import os import math from typing import Dict from copy import deepcopy import numpy as np from datasets import DatasetDict from random import shuffle from torch.utils.data import Dataset, ConcatDataset from torch.utils.data.dataset import T_co from utils.configue import Configure def upsample(data, weight): n_data = len(data) assert weight >= 1 integral = list(range(n_data)) * int(math.floor(weight)) residual = list(range(n_data)) shuffle(residual) residual = residual[:int(n_data * (weight - int(math.floor(weight))))] return [deepcopy(data[idx]) for idx in integral + residual]
null
163,405
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): ''' input: sql_query output: { "select": the select clause "from": the from clause ... } assumption: only one intersect/union/except ''' def keywords_fix(s): s = s.replace("group by", "group_by") s = s.replace("order by", "order_by") return s sql_query = keywords_fix(normalize(sql_query)) num = 0 nested = {} while "(select" in sql_query: # has nested sql query num += 1 left_index = sql_query.index("(select") right_index = -1 flag = -1 for i in range(left_index + 7, len(sql_query)): flag = flag - 1 if sql_query[i] == "(" else flag flag = flag + 1 if sql_query[i] == ")" else flag if flag == 0: right_index = i + 1 break assert flag == 0, "sql query is not correct!" nested["{}#{}".format(NESTED_SYMBOL, num)] = remove_alias(sql_query[left_index: right_index]) sql_query = sql_query.replace(sql_query[left_index: right_index], "{}#{}".format(NESTED_SYMBOL, num)) has_two_sql = False set_index = 0 set_ops = list(set(sql_query.split()).intersection(set(SET_OPS))) if len(set_ops) > 0: # assume only one intersect/union/except set_index = sql_query.index(set_ops[0]) has_two_sql = True if has_two_sql: first_sql_query = remove_alias(sql_query[:set_index - 1]) second_sql_query = remove_alias(sql_query[set_index + len(set_ops[0]) + 1:]) main = f"{first_sql_query} {set_ops[0]} {second_sql_query}" while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(first_sql_query, nested)) while NESTED_SYMBOL in second_sql_query: num = second_sql_query[second_sql_query.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] second_sql_query = second_sql_query.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict.update({"SQL": f"{set_ops[0]} {second_sql_query}"}) else: sql_query = remove_alias(sql_query) main = sql_query while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(sql_query, nested)) sql_dict.update({"SQL": ""}) return sql_dict def build_data_train(item, sql_dict, args): question = item["question"] schema = item.pop("serialized_schema") task2prompt = {} for key, value in vars(args.prompt).items(): if "sql" in key: task2prompt[key.replace("sql", "SQL")] = value else: task2prompt[key] = value keyword2sp_tokens = {} for key, value in vars(args.special_tokens).items(): if "sql" in key: keyword2sp_tokens[key.replace("sql", "SQL")] = value else: keyword2sp_tokens[key] = value seq_out_main = sql_dict.pop("main") if args.target.with_special_tokens: for keyword in CLAUSE_KEYWORDS: seq_out_main = seq_out_main.replace(keyword, keyword2sp_tokens[keyword]) for set_op in SET_OPS: seq_out_main = seq_out_main.replace(set_op, keyword2sp_tokens[set_op]) prompt_main = args.prompt.main text_in = prompt_main + " " + question data = {} data["main"] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out_main, "type": "main", "empty": False, } if args.tasks.task == "main": return data for task in args.tasks.task.split(","): prompt = task2prompt[task] if task != "main": empty = False seq_out = [] for key in prompt.split(): if sql_dict[key[1: -1]]: seq_out.append(sql_dict[key[1: -1]]) else: if args.target.with_empty_sp: seq_out.append(key[1: -1]) if not seq_out: empty = True seq_out = "[empty]" else: seq_out = " ".join(seq_out) if seq_out == prompt.replace("[", "").replace("]", ""): empty = True text_in = prompt + " " + question if args.target.with_special_tokens: for keyword in CLAUSE_KEYWORDS + ["SQL"]: seq_out = seq_out.replace(keyword, keyword2sp_tokens[keyword]) for set_op in SET_OPS: seq_out = seq_out.replace(set_op, keyword2sp_tokens[set_op]) data[task] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out.strip(), "type": task, "empty": empty, } return data def spider_pre_process_one_function_train(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_train(item, sql_dict, args) return data
null
163,406
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): ''' input: sql_query output: { "select": the select clause "from": the from clause ... } assumption: only one intersect/union/except ''' def keywords_fix(s): s = s.replace("group by", "group_by") s = s.replace("order by", "order_by") return s sql_query = keywords_fix(normalize(sql_query)) num = 0 nested = {} while "(select" in sql_query: # has nested sql query num += 1 left_index = sql_query.index("(select") right_index = -1 flag = -1 for i in range(left_index + 7, len(sql_query)): flag = flag - 1 if sql_query[i] == "(" else flag flag = flag + 1 if sql_query[i] == ")" else flag if flag == 0: right_index = i + 1 break assert flag == 0, "sql query is not correct!" nested["{}#{}".format(NESTED_SYMBOL, num)] = remove_alias(sql_query[left_index: right_index]) sql_query = sql_query.replace(sql_query[left_index: right_index], "{}#{}".format(NESTED_SYMBOL, num)) has_two_sql = False set_index = 0 set_ops = list(set(sql_query.split()).intersection(set(SET_OPS))) if len(set_ops) > 0: # assume only one intersect/union/except set_index = sql_query.index(set_ops[0]) has_two_sql = True if has_two_sql: first_sql_query = remove_alias(sql_query[:set_index - 1]) second_sql_query = remove_alias(sql_query[set_index + len(set_ops[0]) + 1:]) main = f"{first_sql_query} {set_ops[0]} {second_sql_query}" while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(first_sql_query, nested)) while NESTED_SYMBOL in second_sql_query: num = second_sql_query[second_sql_query.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] second_sql_query = second_sql_query.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict.update({"SQL": f"{set_ops[0]} {second_sql_query}"}) else: sql_query = remove_alias(sql_query) main = sql_query while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(sql_query, nested)) sql_dict.update({"SQL": ""}) return sql_dict def build_data_eval(item, sql_dict, args): question = item["question"] schema = item.pop("serialized_schema") task2prompt = {} for key, value in vars(args.prompt).items(): if "sql" in key: task2prompt[key.replace("sql", "SQL")] = value else: task2prompt[key] = value seq_out_main = sql_dict.pop("main") seq_out_main = seq_out_main.replace("group_by", "group by") seq_out_main = seq_out_main.replace("order_by", "order by") prompt_main = args.prompt.main text_in = prompt_main + " " + question data = {} data["main"] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out_main, "type": "main", "empty": False, } if args.tasks.task == "main": return data for task in args.tasks.task.split(","): prompt = task2prompt[task] if task != "main": empty = False seq_out = [] for key in prompt.split(): if sql_dict[key[1: -1]]: seq_out.append(sql_dict[key[1: -1]]) else: if args.target.with_empty_sp: seq_out.append(key[1: -1]) if not seq_out: empty = True seq_out = "empty" else: seq_out = " ".join(seq_out) if seq_out == prompt.replace("[", "").replace("]", ""): empty = True text_in = prompt + " " + question seq_out = seq_out.replace("group_by", "group by") seq_out = seq_out.replace("order_by", "order by") data[task] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out.strip(), "type": task, "empty": empty, } return data def spider_pre_process_one_function_eval(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_eval(item, sql_dict, args) return data
null
163,408
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def balance_data(data, ratio=0.5): empty_data = [x for x in data if x["empty"]] print("len(empty_data): ", len(empty_data)) non_empty_data = [x for x in data if not x["empty"]] print("len(non_empty_data): ", len(non_empty_data)) if len(non_empty_data) / len(data) < ratio: num = int((1 - ratio) * len(non_empty_data) / ratio) random.shuffle(empty_data) empty_data = empty_data[:num] print("len(empty_data): ", len(empty_data)) data = empty_data + non_empty_data random.shuffle(data) return data
null
163,416
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def spider_get_input( question: str, serialized_schema: str, prefix: str, ) -> str: def spider_get_target( query: str, db_id: str, normalize_query: bool, target_with_db_id: bool, ) -> str: def spider_pre_process_function(batch: dict, args): prefix = "" inputs = [ spider_get_input( question=question, serialized_schema=serialized_schema, prefix=prefix ) for question, serialized_schema in zip( batch["question"], batch["serialized_schema"] ) ] targets = [ spider_get_target( query=query, db_id=db_id, normalize_query=True, target_with_db_id=args.seq2seq.target_with_db_id, ) for db_id, query in zip(batch["db_id"], batch["query"]) ] return zip(inputs, targets)
null
163,418
import os import torch import random import math import re import numpy as np from copy import deepcopy from typing import List, Dict from datasets.dataset_dict import DatasetDict from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from third_party.miscs.bridge_content_encoder import get_database_matches from tqdm import tqdm def extract_sql_clause(sql_query): ''' input: sql_query output: { "select": the select clause "from": the from clause ... } assumption: only one intersect/union/except ''' def keywords_fix(s): s = s.replace("group by", "group_by") s = s.replace("order by", "order_by") return s sql_query = keywords_fix(normalize(sql_query)) num = 0 nested = {} while "(select" in sql_query: # has nested sql query num += 1 left_index = sql_query.index("(select") right_index = -1 flag = -1 for i in range(left_index + 7, len(sql_query)): flag = flag - 1 if sql_query[i] == "(" else flag flag = flag + 1 if sql_query[i] == ")" else flag if flag == 0: right_index = i + 1 break assert flag == 0, "sql query is not correct!" nested["{}#{}".format(NESTED_SYMBOL, num)] = remove_alias(sql_query[left_index: right_index]) sql_query = sql_query.replace(sql_query[left_index: right_index], "{}#{}".format(NESTED_SYMBOL, num)) has_two_sql = False set_index = 0 set_ops = list(set(sql_query.split()).intersection(set(SET_OPS))) if len(set_ops) > 0: # assume only one intersect/union/except set_index = sql_query.index(set_ops[0]) has_two_sql = True if has_two_sql: first_sql_query = remove_alias(sql_query[:set_index - 1]) second_sql_query = remove_alias(sql_query[set_index + len(set_ops[0]) + 1:]) main = f"{first_sql_query} {set_ops[0]} {second_sql_query}" while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(first_sql_query, nested)) while NESTED_SYMBOL in second_sql_query: num = second_sql_query[second_sql_query.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] second_sql_query = second_sql_query.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict.update({"SQL": f"{set_ops[0]} {second_sql_query}"}) else: sql_query = remove_alias(sql_query) main = sql_query while NESTED_SYMBOL in main: num = main[main.index(NESTED_SYMBOL) + len(NESTED_SYMBOL) + 1] main = main.replace("{}#{}".format(NESTED_SYMBOL, num), nested["{}#{}".format(NESTED_SYMBOL, num)]) sql_dict = {"main": main} sql_dict.update(process_single_sql(sql_query, nested)) sql_dict.update({"SQL": ""}) return sql_dict def build_data_eval(item, sql_dict, args): question = item["question"] schema = item.pop("serialized_schema") task2prompt = {} for key, value in vars(args.prompt).items(): if "sql" in key: task2prompt[key.replace("sql", "SQL")] = value else: task2prompt[key] = value seq_out_main = sql_dict.pop("main") seq_out_main = seq_out_main.replace("group_by", "group by") seq_out_main = seq_out_main.replace("order_by", "order by") prompt_main = args.prompt.main text_in = prompt_main + " " + question data = {} data["main"] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out_main, "type": "main", "empty": False, } if args.tasks.task == "main": return data for task in args.tasks.task.split(","): prompt = task2prompt[task] if task != "main": empty = False seq_out = [] for key in prompt.split(): if sql_dict[key[1: -1]]: seq_out.append(sql_dict[key[1: -1]]) else: if args.target.with_empty_sp: seq_out.append(key[1: -1]) if not seq_out: empty = True seq_out = "empty" else: seq_out = " ".join(seq_out) if seq_out == prompt.replace("[", "").replace("]", ""): empty = True text_in = prompt + " " + question seq_out = seq_out.replace("group_by", "group by") seq_out = seq_out.replace("order_by", "order by") # do not forget this data[task] = { "text_in": text_in.strip(), "struct_in": schema, "seq_out": seq_out.strip(), "type": task, "empty": empty, } return data def spider_pre_process_one_function_eval(item: dict, args): sql_dict = extract_sql_clause(item["query"]) data = build_data_eval(item, sql_dict, args) return data
null
163,434
import json import sqlite3 from nltk import word_tokenize def get_schema_from_json(fpath): with open(fpath) as f: data = json.load(f) schema = {} for entry in data: table = str(entry['table'].lower()) cols = [str(col['column_name'].lower()) for col in entry['col_data']] schema[table] = cols return schema
null
163,436
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def condition_has_or(conds): return 'or' in conds[1::2]
null
163,437
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql WHERE_OPS = ('not', 'between', '=', '>', '<', '>=', '<=', '!=', 'in', 'like', 'is', 'exists') def condition_has_like(conds): return WHERE_OPS.index('like') in [cond_unit[1] for cond_unit in conds[::2]]
null
163,438
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def condition_has_sql(conds): for cond_unit in conds[::2]: val1, val2 = cond_unit[3], cond_unit[4] if val1 is not None and type(val1) is dict: return True if val2 is not None and type(val2) is dict: return True return False
null
163,439
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql UNIT_OPS = ('none', '-', '+', "*", '/') def val_has_op(val_unit): return val_unit[0] != UNIT_OPS.index('none')
null
163,440
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def accuracy(count, total): if count == total: return 1 return 0
null
163,441
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def recall(count, total): if count == total: return 1 return 0
null
163,442
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def F1(acc, rec): if (acc + rec) == 0: return 0 return (2. * acc * rec) / (acc + rec)
null
163,443
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def get_scores(count, pred_total, label_total): if pred_total != label_total: return 0,0,0 elif count == pred_total: return 1,1,1 return 0,0,0
null
163,444
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_sel(pred, label): pred_sel = pred['select'][1] label_sel = label['select'][1] label_wo_agg = [unit[1] for unit in label_sel] pred_total = len(pred_sel) label_total = len(label_sel) cnt = 0 cnt_wo_agg = 0 for unit in pred_sel: if unit in label_sel: cnt += 1 label_sel.remove(unit) if unit[1] in label_wo_agg: cnt_wo_agg += 1 label_wo_agg.remove(unit[1]) return label_total, pred_total, cnt, cnt_wo_agg
null
163,445
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_where(pred, label): pred_conds = [unit for unit in pred['where'][::2]] label_conds = [unit for unit in label['where'][::2]] label_wo_agg = [unit[2] for unit in label_conds] pred_total = len(pred_conds) label_total = len(label_conds) cnt = 0 cnt_wo_agg = 0 for unit in pred_conds: if unit in label_conds: cnt += 1 label_conds.remove(unit) if unit[2] in label_wo_agg: cnt_wo_agg += 1 label_wo_agg.remove(unit[2]) return label_total, pred_total, cnt, cnt_wo_agg
null
163,446
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_group(pred, label): pred_cols = [unit[1] for unit in pred['groupBy']] label_cols = [unit[1] for unit in label['groupBy']] pred_total = len(pred_cols) label_total = len(label_cols) cnt = 0 pred_cols = [pred.split(".")[1] if "." in pred else pred for pred in pred_cols] label_cols = [label.split(".")[1] if "." in label else label for label in label_cols] for col in pred_cols: if col in label_cols: cnt += 1 label_cols.remove(col) return label_total, pred_total, cnt
null
163,447
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_having(pred, label): pred_total = label_total = cnt = 0 if len(pred['groupBy']) > 0: pred_total = 1 if len(label['groupBy']) > 0: label_total = 1 pred_cols = [unit[1] for unit in pred['groupBy']] label_cols = [unit[1] for unit in label['groupBy']] if pred_total == label_total == 1 \ and pred_cols == label_cols \ and pred['having'] == label['having']: cnt = 1 return label_total, pred_total, cnt
null
163,448
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_order(pred, label): pred_total = label_total = cnt = 0 if len(pred['orderBy']) > 0: pred_total = 1 if len(label['orderBy']) > 0: label_total = 1 if len(label['orderBy']) > 0 and pred['orderBy'] == label['orderBy'] and \ ((pred['limit'] is None and label['limit'] is None) or (pred['limit'] is not None and label['limit'] is not None)): cnt = 1 return label_total, pred_total, cnt
null
163,449
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_and_or(pred, label): pred_ao = pred['where'][1::2] label_ao = label['where'][1::2] pred_ao = set(pred_ao) label_ao = set(label_ao) if pred_ao == label_ao: return 1,1,1 return len(pred_ao),len(label_ao),0
null
163,450
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_nested(pred, label): label_total = 0 pred_total = 0 cnt = 0 if pred is not None: pred_total += 1 if label is not None: label_total += 1 if pred is not None and label is not None: cnt += Evaluator().eval_exact_match(pred, label) return label_total, pred_total, cnt def eval_IUEN(pred, label): lt1, pt1, cnt1 = eval_nested(pred['intersect'], label['intersect']) lt2, pt2, cnt2 = eval_nested(pred['except'], label['except']) lt3, pt3, cnt3 = eval_nested(pred['union'], label['union']) label_total = lt1 + lt2 + lt3 pred_total = pt1 + pt2 + pt3 cnt = cnt1 + cnt2 + cnt3 return label_total, pred_total, cnt
null
163,451
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def get_keywords(sql): res = set() if len(sql['where']) > 0: res.add('where') if len(sql['groupBy']) > 0: res.add('group') if len(sql['having']) > 0: res.add('having') if len(sql['orderBy']) > 0: res.add(sql['orderBy'][0]) res.add('order') if sql['limit'] is not None: res.add('limit') if sql['except'] is not None: res.add('except') if sql['union'] is not None: res.add('union') if sql['intersect'] is not None: res.add('intersect') # or keyword ao = sql['from']['conds'][1::2] + sql['where'][1::2] + sql['having'][1::2] if len([token for token in ao if token == 'or']) > 0: res.add('or') cond_units = sql['from']['conds'][::2] + sql['where'][::2] + sql['having'][::2] # not keyword if len([cond_unit for cond_unit in cond_units if cond_unit[0]]) > 0: res.add('not') # in keyword if len([cond_unit for cond_unit in cond_units if cond_unit[1] == WHERE_OPS.index('in')]) > 0: res.add('in') # like keyword if len([cond_unit for cond_unit in cond_units if cond_unit[1] == WHERE_OPS.index('like')]) > 0: res.add('like') return res def eval_keywords(pred, label): pred_keywords = get_keywords(pred) label_keywords = get_keywords(label) pred_total = len(pred_keywords) label_total = len(label_keywords) cnt = 0 for k in pred_keywords: if k in label_keywords: cnt += 1 return label_total, pred_total, cnt
null
163,452
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql WHERE_OPS = ('not', 'between', '=', '>', '<', '>=', '<=', '!=', 'in', 'like', 'is', 'exists') def count_component1(sql): count = 0 if len(sql['where']) > 0: count += 1 if len(sql['groupBy']) > 0: count += 1 if len(sql['orderBy']) > 0: count += 1 if sql['limit'] is not None: count += 1 if len(sql['from']['table_units']) > 0: # JOIN count += len(sql['from']['table_units']) - 1 ao = sql['from']['conds'][1::2] + sql['where'][1::2] + sql['having'][1::2] count += len([token for token in ao if token == 'or']) cond_units = sql['from']['conds'][::2] + sql['where'][::2] + sql['having'][::2] count += len([cond_unit for cond_unit in cond_units if cond_unit[1] == WHERE_OPS.index('like')]) return count
null
163,453
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def get_nestedSQL(sql): def count_component2(sql): nested = get_nestedSQL(sql) return len(nested)
null
163,454
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def count_agg(units): return len([unit for unit in units if has_agg(unit)]) def count_others(sql): count = 0 # number of aggregation agg_count = count_agg(sql['select'][1]) agg_count += count_agg(sql['where'][::2]) agg_count += count_agg(sql['groupBy']) if len(sql['orderBy']) > 0: agg_count += count_agg([unit[1] for unit in sql['orderBy'][1] if unit[1]] + [unit[2] for unit in sql['orderBy'][1] if unit[2]]) agg_count += count_agg(sql['having']) if agg_count > 1: count += 1 # number of select columns if len(sql['select'][1]) > 1: count += 1 # number of where conditions if len(sql['where']) > 1: count += 1 # number of group by clauses if len(sql['groupBy']) > 1: count += 1 return count
null
163,455
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def isValidSQL(sql, db): conn = sqlite3.connect(db) cursor = conn.cursor() try: cursor.execute(sql) except: return False return True
null
163,456
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql class Evaluator: """A simple evaluator""" def __init__(self): self.partial_scores = None def eval_hardness(self, sql): count_comp1_ = count_component1(sql) count_comp2_ = count_component2(sql) count_others_ = count_others(sql) if count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ == 0: return "easy" elif (count_others_ <= 2 and count_comp1_ <= 1 and count_comp2_ == 0) or \ (count_comp1_ <= 2 and count_others_ < 2 and count_comp2_ == 0): return "medium" elif (count_others_ > 2 and count_comp1_ <= 2 and count_comp2_ == 0) or \ (2 < count_comp1_ <= 3 and count_others_ <= 2 and count_comp2_ == 0) or \ (count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ <= 1): return "hard" else: return "extra" def eval_exact_match(self, pred, label): partial_scores = self.eval_partial_match(pred, label) self.partial_scores = partial_scores for key, score in partial_scores.items(): if score['f1'] != 1: return 0 if len(label['from']['table_units']) > 0: label_tables = sorted(label['from']['table_units']) pred_tables = sorted(pred['from']['table_units']) return label_tables == pred_tables return 1 def eval_partial_match(self, pred, label): res = {} label_total, pred_total, cnt, cnt_wo_agg = eval_sel(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['select'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} acc, rec, f1 = get_scores(cnt_wo_agg, pred_total, label_total) res['select(no AGG)'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} label_total, pred_total, cnt, cnt_wo_agg = eval_where(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['where'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} acc, rec, f1 = get_scores(cnt_wo_agg, pred_total, label_total) res['where(no OP)'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} label_total, pred_total, cnt = eval_group(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['group(no Having)'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} label_total, pred_total, cnt = eval_having(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['group'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} label_total, pred_total, cnt = eval_order(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['order'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} label_total, pred_total, cnt = eval_and_or(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['and/or'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} label_total, pred_total, cnt = eval_IUEN(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['IUEN'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} label_total, pred_total, cnt = eval_keywords(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res['keywords'] = {'acc': acc, 'rec': rec, 'f1': f1,'label_total':label_total,'pred_total':pred_total} return res def print_scores(scores, etype): turns = ['turn 1', 'turn 2', 'turn 3', 'turn 4', 'turn >4'] levels = ['easy', 'medium', 'hard', 'extra', 'all', "joint_all"] partial_types = ['select', 'select(no AGG)', 'where', 'where(no OP)', 'group(no Having)', 'group', 'order', 'and/or', 'IUEN', 'keywords'] print("{:20} {:20} {:20} {:20} {:20} {:20} {:20}".format("", *levels)) counts = [scores[level]['count'] for level in levels] print("{:20} {:<20d} {:<20d} {:<20d} {:<20d} {:<20d} {:<20d}".format("count", *counts)) if etype in ["all", "exec"]: print('===================== EXECUTION ACCURACY =====================') this_scores = [scores[level]['exec'] for level in levels] print("{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format("execution", *this_scores)) if etype in ["all", "match"]: print('\n====================== EXACT MATCHING ACCURACY =====================') exact_scores = [scores[level]['exact'] for level in levels] print("{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format("exact match", *exact_scores)) print('\n---------------------PARTIAL MATCHING ACCURACY----------------------') for type_ in partial_types: this_scores = [scores[level]['partial'][type_]['acc'] for level in levels] print("{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(type_, *this_scores)) print('---------------------- PARTIAL MATCHING RECALL ----------------------') for type_ in partial_types: this_scores = [scores[level]['partial'][type_]['rec'] for level in levels] print("{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(type_, *this_scores)) print('---------------------- PARTIAL MATCHING F1 --------------------------') for type_ in partial_types: this_scores = [scores[level]['partial'][type_]['f1'] for level in levels] print("{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(type_, *this_scores)) print("\n\n{:20} {:20} {:20} {:20} {:20} {:20}".format("", *turns)) counts = [scores[turn]['count'] for turn in turns] print("{:20} {:<20d} {:<20d} {:<20d} {:<20d} {:<20d}".format("count", *counts)) if etype in ["all", "exec"]: print('===================== TRUN XECUTION ACCURACY =====================') this_scores = [scores[turn]['exec'] for turn in turns] print("{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format("execution", *this_scores)) if etype in ["all", "match"]: print('\n====================== TRUN EXACT MATCHING ACCURACY =====================') exact_scores = [scores[turn]['exact'] for turn in turns] print("{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format("exact match", *exact_scores)) def eval_exec_match(db, p_str, g_str, pred, gold): """ return 1 if the values between prediction and gold are matching in the corresponding index. Currently not support multiple col_unit(pairs). """ p_str, g_str = postprocess(p_str), postprocess(g_str) conn = sqlite3.connect(db) cursor = conn.cursor() try: cursor.execute(p_str) p_res = cursor.fetchall() except: return False cursor.execute(g_str) q_res = cursor.fetchall() def res_map(res, val_units): rmap = {} for idx, val_unit in enumerate(val_units): key = tuple(val_unit[1]) if not val_unit[2] else (val_unit[0], tuple(val_unit[1]), tuple(val_unit[2])) rmap[key] = [r[idx] for r in res] return rmap p_val_units = [unit[1] for unit in pred['select'][1]] q_val_units = [unit[1] for unit in gold['select'][1]] return res_map(p_res, p_val_units) == res_map(q_res, q_val_units) def rebuild_sql_val(sql): if sql is None or not DISABLE_VALUE: return sql sql['from']['conds'] = rebuild_condition_val(sql['from']['conds']) sql['having'] = rebuild_condition_val(sql['having']) sql['where'] = rebuild_condition_val(sql['where']) sql['intersect'] = rebuild_sql_val(sql['intersect']) sql['except'] = rebuild_sql_val(sql['except']) sql['union'] = rebuild_sql_val(sql['union']) return sql def build_valid_col_units(table_units, schema): col_ids = [table_unit[1] for table_unit in table_units if table_unit[0] == TABLE_TYPE['table_unit']] prefixs = [col_id[:-2] for col_id in col_ids] valid_col_units= [] for value in schema.idMap.values(): if '.' in value and value[:value.index('.')] in prefixs: valid_col_units.append(value) return valid_col_units def rebuild_sql_col(valid_col_units, sql, kmap): if sql is None: return sql sql['select'] = rebuild_select_col(valid_col_units, sql['select'], kmap) sql['from'] = rebuild_from_col(valid_col_units, sql['from'], kmap) sql['where'] = rebuild_condition_col(valid_col_units, sql['where'], kmap) sql['groupBy'] = rebuild_group_by_col(valid_col_units, sql['groupBy'], kmap) sql['orderBy'] = rebuild_order_by_col(valid_col_units, sql['orderBy'], kmap) sql['having'] = rebuild_condition_col(valid_col_units, sql['having'], kmap) sql['intersect'] = rebuild_sql_col(valid_col_units, sql['intersect'], kmap) sql['except'] = rebuild_sql_col(valid_col_units, sql['except'], kmap) sql['union'] = rebuild_sql_col(valid_col_units, sql['union'], kmap) return sql class Schema: """ Simple schema which maps table&column to a unique identifier """ def __init__(self, schema): self._schema = schema self._idMap = self._map(self._schema) def schema(self): return self._schema def idMap(self): return self._idMap def _map(self, schema): idMap = {'*': "__all__"} id = 1 for key, vals in schema.items(): for val in vals: idMap[key.lower() + "." + val.lower()] = "__" + key.lower() + "." + val.lower() + "__" id += 1 for key in schema: idMap[key.lower()] = "__" + key.lower() + "__" id += 1 return idMap def get_schema(db): """ Get database's schema, which is a dict with table name as key and list of column names as value :param db: database path :return: schema dict """ schema = {} conn = sqlite3.connect(db) cursor = conn.cursor() # fetch table names cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = [str(table[0].lower()) for table in cursor.fetchall()] # fetch table info for table in tables: cursor.execute("PRAGMA table_info({})".format(table)) schema[table] = [str(col[1].lower()) for col in cursor.fetchall()] return schema 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 def evaluate(gold, predict, db_dir, etype, kmaps): with open(gold) as f: glist = [] gseq_one = [] for l in f.readlines(): if len(l.strip()) == 0: glist.append(gseq_one) gseq_one = [] else: lstrip = l.strip().split('\t') gseq_one.append(lstrip) #glist = [l.strip().split('\t') for l in f.readlines() if len(l.strip()) > 0] with open(predict) as f: plist = [] pseq_one = [] for l in f.readlines(): if len(l.strip()) == 0: plist.append(pseq_one) pseq_one = [] else: pseq_one.append(l.strip().split('\t')) #plist = [l.strip().split('\t') for l in f.readlines() if len(l.strip()) > 0] # plist = [[("select product_type_code from products group by product_type_code order by count ( * ) desc limit value", "orchestra")]] # glist = [[("SELECT product_type_code FROM Products GROUP BY product_type_code ORDER BY count(*) DESC LIMIT 1", "customers_and_orders")]] evaluator = Evaluator() turns = ['turn 1', 'turn 2', 'turn 3', 'turn 4', 'turn >4'] levels = ['easy', 'medium', 'hard', 'extra', 'all', 'joint_all'] partial_types = ['select', 'select(no AGG)', 'where', 'where(no OP)', 'group(no Having)', 'group', 'order', 'and/or', 'IUEN', 'keywords'] entries = [] scores = {} for turn in turns: scores[turn] = {'count': 0, 'exact': 0.} scores[turn]['exec'] = 0 for level in levels: scores[level] = {'count': 0, 'partial': {}, 'exact': 0.} scores[level]['exec'] = 0 for type_ in partial_types: scores[level]['partial'][type_] = {'acc': 0., 'rec': 0., 'f1': 0.,'acc_count':0,'rec_count':0} eval_err_num = 0 for p, g in zip(plist, glist): scores['joint_all']['count'] += 1 turn_scores = {"exec": [], "exact": []} for idx, pg in enumerate(zip(p, g)): p, g = pg p_str = p[0] p_str = p_str.replace("value", "1") g_str, db = g db_name = db db = os.path.join(db_dir, db, db + ".sqlite") schema = Schema(get_schema(db)) g_sql = get_sql(schema, g_str) hardness = evaluator.eval_hardness(g_sql) if idx > 3: idx = ">4" else: idx += 1 turn_id = "turn " + str(idx) scores[turn_id]['count'] += 1 scores[hardness]['count'] += 1 scores['all']['count'] += 1 try: p_sql = get_sql(schema, p_str) 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": [] } eval_err_num += 1 print("eval_err_num:{}".format(eval_err_num)) # rebuild sql for value evaluation kmap = 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) 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 in ["all", "exec"]: exec_score = eval_exec_match(db, p_str, g_str, p_sql, g_sql) if exec_score: scores[hardness]['exec'] += 1 scores[turn_id]['exec'] += 1 turn_scores['exec'].append(1) else: turn_scores['exec'].append(0) if etype in ["all", "match"]: exact_score = evaluator.eval_exact_match(p_sql, g_sql) partial_scores = evaluator.partial_scores if exact_score == 0: turn_scores['exact'].append(0) print("{} pred: {}".format(hardness,p_str)) print("{} gold: {}".format(hardness,g_str)) print("") else: turn_scores['exact'].append(1) scores[turn_id]['exact'] += exact_score scores[hardness]['exact'] += exact_score scores['all']['exact'] += exact_score for type_ in partial_types: if partial_scores[type_]['pred_total'] > 0: scores[hardness]['partial'][type_]['acc'] += partial_scores[type_]['acc'] scores[hardness]['partial'][type_]['acc_count'] += 1 if partial_scores[type_]['label_total'] > 0: scores[hardness]['partial'][type_]['rec'] += partial_scores[type_]['rec'] scores[hardness]['partial'][type_]['rec_count'] += 1 scores[hardness]['partial'][type_]['f1'] += partial_scores[type_]['f1'] if partial_scores[type_]['pred_total'] > 0: scores['all']['partial'][type_]['acc'] += partial_scores[type_]['acc'] scores['all']['partial'][type_]['acc_count'] += 1 if partial_scores[type_]['label_total'] > 0: scores['all']['partial'][type_]['rec'] += partial_scores[type_]['rec'] scores['all']['partial'][type_]['rec_count'] += 1 scores['all']['partial'][type_]['f1'] += partial_scores[type_]['f1'] entries.append({ 'predictSQL': p_str, 'goldSQL': g_str, 'hardness': hardness, 'exact': exact_score, 'partial': partial_scores }) if all(v == 1 for v in turn_scores["exec"]): scores['joint_all']['exec'] += 1 if all(v == 1 for v in turn_scores["exact"]): scores['joint_all']['exact'] += 1 for turn in turns: if scores[turn]['count'] == 0: continue if etype in ["all", "exec"]: scores[turn]['exec'] /= scores[turn]['count'] if etype in ["all", "match"]: scores[turn]['exact'] /= scores[turn]['count'] for level in levels: if scores[level]['count'] == 0: continue if etype in ["all", "exec"]: scores[level]['exec'] /= scores[level]['count'] if etype in ["all", "match"]: scores[level]['exact'] /= scores[level]['count'] for type_ in partial_types: if scores[level]['partial'][type_]['acc_count'] == 0: scores[level]['partial'][type_]['acc'] = 0 else: scores[level]['partial'][type_]['acc'] = scores[level]['partial'][type_]['acc'] / \ scores[level]['partial'][type_]['acc_count'] * 1.0 if scores[level]['partial'][type_]['rec_count'] == 0: scores[level]['partial'][type_]['rec'] = 0 else: scores[level]['partial'][type_]['rec'] = scores[level]['partial'][type_]['rec'] / \ scores[level]['partial'][type_]['rec_count'] * 1.0 if scores[level]['partial'][type_]['acc'] == 0 and scores[level]['partial'][type_]['rec'] == 0: scores[level]['partial'][type_]['f1'] = 1 else: scores[level]['partial'][type_]['f1'] = \ 2.0 * scores[level]['partial'][type_]['acc'] * scores[level]['partial'][type_]['rec'] / ( scores[level]['partial'][type_]['rec'] + scores[level]['partial'][type_]['acc']) print_scores(scores, etype)
null
163,457
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def build_foreign_key_map(entry): cols_orig = entry["column_names_original"] tables_orig = entry["table_names_original"] # rebuild cols corresponding to idmap in Schema cols = [] for col_orig in cols_orig: if col_orig[0] >= 0: t = tables_orig[col_orig[0]] c = col_orig[1] cols.append("__" + t.lower() + "." + c.lower() + "__") else: cols.append("__all__") def keyset_in_list(k1, k2, k_list): for k_set in k_list: if k1 in k_set or k2 in k_set: return k_set new_k_set = set() k_list.append(new_k_set) return new_k_set foreign_key_list = [] foreign_keys = entry["foreign_keys"] for fkey in foreign_keys: key1, key2 = fkey key_set = keyset_in_list(key1, key2, foreign_key_list) key_set.add(key1) key_set.add(key2) foreign_key_map = {} for key_set in foreign_key_list: sorted_list = sorted(list(key_set)) midx = sorted_list[0] for idx in sorted_list: foreign_key_map[cols[idx]] = cols[midx] return foreign_key_map def build_foreign_key_map_from_json(table): with open(table) as f: data = json.load(f) tables = {} for entry in data: tables[entry['db_id']] = build_foreign_key_map(entry) return tables
null
163,458
import json import sqlite3 from nltk import word_tokenize The provided code snippet includes necessary dependencies for implementing the `get_schema` function. Write a Python function `def get_schema(db)` to solve the following problem: Get database's schema, which is a dict with table name as key and list of column names as value :param db: database path :return: schema dict Here is the function: def get_schema(db): """ Get database's schema, which is a dict with table name as key and list of column names as value :param db: database path :return: schema dict """ schema = {} conn = sqlite3.connect(db) cursor = conn.cursor() # fetch table names cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = [str(table[0].lower()) for table in cursor.fetchall()] # fetch table info for table in tables: cursor.execute("PRAGMA table_info({})".format(table)) schema[table] = [str(col[1].lower()) for col in cursor.fetchall()] return schema
Get database's schema, which is a dict with table name as key and list of column names as value :param db: database path :return: schema dict
163,461
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 toks = [word.lower() for word in word_tokenize(string)] # 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 in ("=", ">")] 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]] + 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
163,462
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def condition_has_or(conds): return "or" in conds[1::2]
null
163,463
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql WHERE_OPS = ( "not", "between", "=", ">", "<", ">=", "<=", "!=", "in", "like", "is", "exists", ) def condition_has_like(conds): return WHERE_OPS.index("like") in [cond_unit[1] for cond_unit in conds[::2]]
null
163,465
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql UNIT_OPS = ("none", "-", "+", "*", "/") def val_has_op(val_unit): return val_unit[0] != UNIT_OPS.index("none")
null
163,468
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def F1(acc, rec): if (acc + rec) == 0: return 0 return (2.0 * acc * rec) / (acc + rec)
null
163,469
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def get_scores(count, pred_total, label_total): if pred_total != label_total: return 0, 0, 0 elif count == pred_total: return 1, 1, 1 return 0, 0, 0
null
163,470
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_sel(pred, label): pred_sel = pred["select"][1] label_sel = label["select"][1] label_wo_agg = [unit[1] for unit in label_sel] pred_total = len(pred_sel) label_total = len(label_sel) cnt = 0 cnt_wo_agg = 0 for unit in pred_sel: if unit in label_sel: cnt += 1 label_sel.remove(unit) if unit[1] in label_wo_agg: cnt_wo_agg += 1 label_wo_agg.remove(unit[1]) return label_total, pred_total, cnt, cnt_wo_agg
null
163,471
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_where(pred, label): pred_conds = [unit for unit in pred["where"][::2]] label_conds = [unit for unit in label["where"][::2]] label_wo_agg = [unit[2] for unit in label_conds] pred_total = len(pred_conds) label_total = len(label_conds) cnt = 0 cnt_wo_agg = 0 for unit in pred_conds: if unit in label_conds: cnt += 1 label_conds.remove(unit) if unit[2] in label_wo_agg: cnt_wo_agg += 1 label_wo_agg.remove(unit[2]) return label_total, pred_total, cnt, cnt_wo_agg
null
163,472
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_group(pred, label): pred_cols = [unit[1] for unit in pred["groupBy"]] label_cols = [unit[1] for unit in label["groupBy"]] pred_total = len(pred_cols) label_total = len(label_cols) cnt = 0 pred_cols = [pred.split(".")[1] if "." in pred else pred for pred in pred_cols] label_cols = [ label.split(".")[1] if "." in label else label for label in label_cols ] for col in pred_cols: if col in label_cols: cnt += 1 label_cols.remove(col) return label_total, pred_total, cnt
null
163,473
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_having(pred, label): pred_total = label_total = cnt = 0 if len(pred["groupBy"]) > 0: pred_total = 1 if len(label["groupBy"]) > 0: label_total = 1 pred_cols = [unit[1] for unit in pred["groupBy"]] label_cols = [unit[1] for unit in label["groupBy"]] if ( pred_total == label_total == 1 and pred_cols == label_cols and pred["having"] == label["having"] ): cnt = 1 return label_total, pred_total, cnt
null
163,474
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_order(pred, label): pred_total = label_total = cnt = 0 if len(pred["orderBy"]) > 0: pred_total = 1 if len(label["orderBy"]) > 0: label_total = 1 if ( len(label["orderBy"]) > 0 and pred["orderBy"] == label["orderBy"] and ( (pred["limit"] is None and label["limit"] is None) or (pred["limit"] is not None and label["limit"] is not None) ) ): cnt = 1 return label_total, pred_total, cnt
null
163,475
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_and_or(pred, label): pred_ao = pred["where"][1::2] label_ao = label["where"][1::2] pred_ao = set(pred_ao) label_ao = set(label_ao) if pred_ao == label_ao: return 1, 1, 1 return len(pred_ao), len(label_ao), 0
null
163,476
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_nested(pred, label): label_total = 0 pred_total = 0 cnt = 0 if pred is not None: pred_total += 1 if label is not None: label_total += 1 if pred is not None and label is not None: partial_scores = Evaluator.eval_partial_match(pred, label) cnt += Evaluator.eval_exact_match(pred, label, partial_scores) return label_total, pred_total, cnt def eval_IUEN(pred, label): lt1, pt1, cnt1 = eval_nested(pred["intersect"], label["intersect"]) lt2, pt2, cnt2 = eval_nested(pred["except"], label["except"]) lt3, pt3, cnt3 = eval_nested(pred["union"], label["union"]) label_total = lt1 + lt2 + lt3 pred_total = pt1 + pt2 + pt3 cnt = cnt1 + cnt2 + cnt3 return label_total, pred_total, cnt
null
163,477
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def get_keywords(sql): res = set() if len(sql["where"]) > 0: res.add("where") if len(sql["groupBy"]) > 0: res.add("group") if len(sql["having"]) > 0: res.add("having") if len(sql["orderBy"]) > 0: res.add(sql["orderBy"][0]) res.add("order") if sql["limit"] is not None: res.add("limit") if sql["except"] is not None: res.add("except") if sql["union"] is not None: res.add("union") if sql["intersect"] is not None: res.add("intersect") # or keyword ao = sql["from"]["conds"][1::2] + sql["where"][1::2] + sql["having"][1::2] if len([token for token in ao if token == "or"]) > 0: res.add("or") cond_units = sql["from"]["conds"][::2] + sql["where"][::2] + sql["having"][::2] # not keyword if len([cond_unit for cond_unit in cond_units if cond_unit[0]]) > 0: res.add("not") # in keyword if ( len( [ cond_unit for cond_unit in cond_units if cond_unit[1] == WHERE_OPS.index("in") ] ) > 0 ): res.add("in") # like keyword if ( len( [ cond_unit for cond_unit in cond_units if cond_unit[1] == WHERE_OPS.index("like") ] ) > 0 ): res.add("like") return res def eval_keywords(pred, label): pred_keywords = get_keywords(pred) label_keywords = get_keywords(label) pred_total = len(pred_keywords) label_total = len(label_keywords) cnt = 0 for k in pred_keywords: if k in label_keywords: cnt += 1 return label_total, pred_total, cnt
null
163,478
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql WHERE_OPS = ( "not", "between", "=", ">", "<", ">=", "<=", "!=", "in", "like", "is", "exists", ) def count_component1(sql): count = 0 if len(sql["where"]) > 0: count += 1 if len(sql["groupBy"]) > 0: count += 1 if len(sql["orderBy"]) > 0: count += 1 if sql["limit"] is not None: count += 1 if len(sql["from"]["table_units"]) > 0: # JOIN count += len(sql["from"]["table_units"]) - 1 ao = sql["from"]["conds"][1::2] + sql["where"][1::2] + sql["having"][1::2] count += len([token for token in ao if token == "or"]) cond_units = sql["from"]["conds"][::2] + sql["where"][::2] + sql["having"][::2] count += len( [ cond_unit for cond_unit in cond_units if cond_unit[1] == WHERE_OPS.index("like") ] ) return count
null
163,480
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def count_agg(units): return len([unit for unit in units if has_agg(unit)]) def count_others(sql): count = 0 # number of aggregation agg_count = count_agg(sql["select"][1]) agg_count += count_agg(sql["where"][::2]) agg_count += count_agg(sql["groupBy"]) if len(sql["orderBy"]) > 0: agg_count += count_agg( [unit[1] for unit in sql["orderBy"][1] if unit[1]] + [unit[2] for unit in sql["orderBy"][1] if unit[2]] ) agg_count += count_agg(sql["having"]) if agg_count > 1: count += 1 # number of select columns if len(sql["select"][1]) > 1: count += 1 # number of where conditions if len(sql["where"]) > 1: count += 1 # number of group by clauses if len(sql["groupBy"]) > 1: count += 1 return count
null
163,481
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def update_scores_match(scores, exact_score, hardness, partial_scores, partial_types): scores[hardness]["exact"] += exact_score scores["all"]["exact"] += exact_score for type_ in partial_types: if partial_scores[type_]["pred_total"] > 0: scores[hardness]["partial"][type_]["acc"] += partial_scores[ type_ ]["acc"] scores[hardness]["partial"][type_]["acc_count"] += 1 if partial_scores[type_]["label_total"] > 0: scores[hardness]["partial"][type_]["rec"] += partial_scores[ type_ ]["rec"] scores[hardness]["partial"][type_]["rec_count"] += 1 scores[hardness]["partial"][type_]["f1"] += partial_scores[type_][ "f1" ] if partial_scores[type_]["pred_total"] > 0: scores["all"]["partial"][type_]["acc"] += partial_scores[ type_ ]["acc"] scores["all"]["partial"][type_]["acc_count"] += 1 if partial_scores[type_]["label_total"] > 0: scores["all"]["partial"][type_]["rec"] += partial_scores[ type_ ]["rec"] scores["all"]["partial"][type_]["rec_count"] += 1 scores["all"]["partial"][type_]["f1"] += partial_scores[type_][ "f1" ]
null
163,483
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql class Evaluator: """A simple evaluator""" def __init__(self, db_dir, kmaps, etype): self.db_dir = db_dir self.kmaps = kmaps self.etype = etype self.db_paths = {} self.schemas = {} for db_name in self.kmaps.keys(): db_path = os.path.join(db_dir, db_name, db_name + ".sqlite") self.db_paths[db_name] = db_path self.schemas[db_name] = Schema(get_schema(db_path)) self.scores = { level: { "count": 0, "partial": { type_: { "acc": 0.0, "rec": 0.0, "f1": 0.0, "acc_count": 0, "rec_count": 0, } for type_ in PARTIAL_TYPES }, "exact": 0.0, "exec": 0, } for level in LEVELS } def eval_hardness(self, sql): count_comp1_ = count_component1(sql) count_comp2_ = count_component2(sql) count_others_ = count_others(sql) if count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ == 0: return "easy" elif (count_others_ <= 2 and count_comp1_ <= 1 and count_comp2_ == 0) or ( count_comp1_ <= 2 and count_others_ < 2 and count_comp2_ == 0 ): return "medium" elif ( (count_others_ > 2 and count_comp1_ <= 2 and count_comp2_ == 0) or (2 < count_comp1_ <= 3 and count_others_ <= 2 and count_comp2_ == 0) or (count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ <= 1) ): return "hard" else: return "extra" def eval_exact_match(cls, pred, label, partial_scores): for _, score in list(partial_scores.items()): if score["f1"] != 1: return 0 if len(label["from"]["table_units"]) > 0: label_tables = sorted(label["from"]["table_units"]) pred_tables = sorted(pred["from"]["table_units"]) return label_tables == pred_tables return 1 def eval_partial_match(cls, pred, label): res = {} label_total, pred_total, cnt, cnt_wo_agg = eval_sel(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["select"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } acc, rec, f1 = get_scores(cnt_wo_agg, pred_total, label_total) res["select(no AGG)"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } label_total, pred_total, cnt, cnt_wo_agg = eval_where(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["where"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } acc, rec, f1 = get_scores(cnt_wo_agg, pred_total, label_total) res["where(no OP)"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } label_total, pred_total, cnt = eval_group(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["group(no Having)"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } label_total, pred_total, cnt = eval_having(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["group"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } label_total, pred_total, cnt = eval_order(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["order"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } label_total, pred_total, cnt = eval_and_or(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["and/or"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } label_total, pred_total, cnt = eval_IUEN(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["IUEN"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } label_total, pred_total, cnt = eval_keywords(pred, label) acc, rec, f1 = get_scores(cnt, pred_total, label_total) res["keywords"] = { "acc": acc, "rec": rec, "f1": f1, "label_total": label_total, "pred_total": pred_total, } return res def evaluate_one(self, db_name, gold, predicted): schema = self.schemas[db_name] g_sql = get_sql(schema, gold) hardness = self.eval_hardness(g_sql) self.scores[hardness]["count"] += 1 self.scores["all"]["count"] += 1 parse_error = False try: p_sql = get_sql(schema, predicted) 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": [], } # TODO fix parse_error = True # rebuild sql for value evaluation 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) 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 self.etype in ["all", "exec"]: self.scores[hardness]["exec"] += eval_exec_match( self.db_paths[db_name], predicted, gold, p_sql, g_sql ) if self.etype in ["all", "match"]: partial_scores = self.eval_partial_match(p_sql, g_sql) exact_score = self.eval_exact_match(p_sql, g_sql, partial_scores) update_scores_match(self.scores, exact_score, hardness, partial_scores, PARTIAL_TYPES) return { "predicted": predicted, "gold": gold, "predicted_parse_error": parse_error, "hardness": hardness, "exact": exact_score, "partial": partial_scores, } def finalize(self): finalize(self.scores, self.etype, PARTIAL_TYPES) def finalize(scores, etype, partial_types): for level in LEVELS: if scores[level]["count"] == 0: continue if etype in ["all", "exec"]: scores[level]["exec"] /= scores[level]["count"] if etype in ["all", "match"]: scores[level]["exact"] /= scores[level]["count"] for type_ in partial_types: if scores[level]["partial"][type_]["acc_count"] == 0: scores[level]["partial"][type_]["acc"] = 0 else: scores[level]["partial"][type_]["acc"] = ( scores[level]["partial"][type_]["acc"] / scores[level]["partial"][type_]["acc_count"] * 1.0 ) if scores[level]["partial"][type_]["rec_count"] == 0: scores[level]["partial"][type_]["rec"] = 0 else: scores[level]["partial"][type_]["rec"] = ( scores[level]["partial"][type_]["rec"] / scores[level]["partial"][type_]["rec_count"] * 1.0 ) if ( scores[level]["partial"][type_]["acc"] == 0 and scores[level]["partial"][type_]["rec"] == 0 ): scores[level]["partial"][type_]["f1"] = 1 else: scores[level]["partial"][type_]["f1"] = ( 2.0 * scores[level]["partial"][type_]["acc"] * scores[level]["partial"][type_]["rec"] / ( scores[level]["partial"][type_]["rec"] + scores[level]["partial"][type_]["acc"] ) ) def print_scores(scores, etype): LEVELS = ["easy", "medium", "hard", "extra", "all"] PARTIAL_TYPES = [ "select", "select(no AGG)", "where", "where(no OP)", "group(no Having)", "group", "order", "and/or", "IUEN", "keywords", ] print("{:20} {:20} {:20} {:20} {:20} {:20}".format("", *LEVELS)) counts = [scores[level]["count"] for level in LEVELS] print("{:20} {:<20d} {:<20d} {:<20d} {:<20d} {:<20d}".format("count", *counts)) if etype in ["all", "exec"]: print("===================== EXECUTION ACCURACY =====================") this_scores = [scores[level]["exec"] for level in LEVELS] print( "{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format( "execution", *this_scores ) ) if etype in ["all", "match"]: print("\n====================== EXACT MATCHING ACCURACY =====================") exact_scores = [scores[level]["exact"] for level in LEVELS] print( "{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format( "exact match", *exact_scores ) ) print("\n---------------------PARTIAL MATCHING ACCURACY----------------------") for type_ in PARTIAL_TYPES: this_scores = [scores[level]["partial"][type_]["acc"] for level in LEVELS] print( "{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format( type_, *this_scores ) ) print("---------------------- PARTIAL MATCHING RECALL ----------------------") for type_ in PARTIAL_TYPES: this_scores = [scores[level]["partial"][type_]["rec"] for level in LEVELS] print( "{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format( type_, *this_scores ) ) print("---------------------- PARTIAL MATCHING F1 --------------------------") for type_ in PARTIAL_TYPES: this_scores = [scores[level]["partial"][type_]["f1"] for level in LEVELS] print( "{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format( type_, *this_scores ) ) def evaluate(gold, predict, db_dir, etype, kmaps): with open(gold) as f: glist = [l.strip().split("\t") for l in f.readlines() if len(l.strip()) > 0] with open(predict) as f: plist = [l.strip().split("\t") for l in f.readlines() if len(l.strip()) > 0] # plist = [("select max(Share),min(Share) from performance where Type != 'terminal'", "orchestra")] # glist = [("SELECT max(SHARE) , min(SHARE) FROM performance WHERE TYPE != 'Live final'", "orchestra")] evaluator = Evaluator(db_dir, kmaps, etype) results = [] for p, g in zip(plist, glist): predicted, db_name = p gold, db_name = g results.append(evaluator.evaluate_one(db_name, gold, predicted)) evaluator.finalize() print_scores(evaluator.scores, etype) return { "per_item": results, "total_scores": evaluator.scores, }
null
163,484
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql The provided code snippet includes necessary dependencies for implementing the `eval_exec_match` function. Write a Python function `def eval_exec_match(db, p_str, g_str, pred, gold)` to solve the following problem: return 1 if the values between prediction and gold are matching in the corresponding index. Currently not support multiple col_unit(pairs). Here is the function: def eval_exec_match(db, p_str, g_str, pred, gold): """ return 1 if the values between prediction and gold are matching in the corresponding index. Currently not support multiple col_unit(pairs). """ conn = sqlite3.connect(db) cursor = conn.cursor() try: cursor.execute(p_str) p_res = cursor.fetchall() except: return False cursor.execute(g_str) q_res = cursor.fetchall() def res_map(res, val_units): rmap = {} for idx, val_unit in enumerate(val_units): key = ( tuple(val_unit[1]) if not val_unit[2] else (val_unit[0], tuple(val_unit[1]), tuple(val_unit[2])) ) rmap[key] = [r[idx] for r in res] return rmap p_val_units = [unit[1] for unit in pred["select"][1]] q_val_units = [unit[1] for unit in gold["select"][1]] return res_map(p_res, p_val_units) == res_map(q_res, q_val_units)
return 1 if the values between prediction and gold are matching in the corresponding index. Currently not support multiple col_unit(pairs).
163,485
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql TABLE_TYPE = { "sql": "sql", "table_unit": "table_unit", } def build_valid_col_units(table_units, schema): col_ids = [ table_unit[1] for table_unit in table_units if table_unit[0] == TABLE_TYPE["table_unit"] ] prefixs = [col_id[:-2] for col_id in col_ids] valid_col_units = [] for value in list(schema.idMap.values()): if "." in value and value[: value.index(".")] in prefixs: valid_col_units.append(value) return valid_col_units
null
163,486
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def rebuild_condition_col(valid_col_units, condition, kmap): for idx in range(len(condition)): if idx % 2 == 0: condition[idx] = rebuild_cond_unit_col( valid_col_units, condition[idx], kmap ) return condition def rebuild_select_col(valid_col_units, sel, kmap): if sel is None: return sel distinct, _list = sel new_list = [] for it in _list: agg_id, val_unit = it new_list.append((agg_id, rebuild_val_unit_col(valid_col_units, val_unit, kmap))) if DISABLE_DISTINCT: distinct = None return distinct, new_list def rebuild_from_col(valid_col_units, from_, kmap): if from_ is None: return from_ from_["table_units"] = [ rebuild_table_unit_col(valid_col_units, table_unit, kmap) for table_unit in from_["table_units"] ] from_["conds"] = rebuild_condition_col(valid_col_units, from_["conds"], kmap) return from_ def rebuild_group_by_col(valid_col_units, group_by, kmap): if group_by is None: return group_by return [ rebuild_col_unit_col(valid_col_units, col_unit, kmap) for col_unit in group_by ] def rebuild_order_by_col(valid_col_units, order_by, kmap): if order_by is None or len(order_by) == 0: return order_by direction, val_units = order_by new_val_units = [ rebuild_val_unit_col(valid_col_units, val_unit, kmap) for val_unit in val_units ] return direction, new_val_units def rebuild_sql_col(valid_col_units, sql, kmap): if sql is None: return sql sql["select"] = rebuild_select_col(valid_col_units, sql["select"], kmap) sql["from"] = rebuild_from_col(valid_col_units, sql["from"], kmap) sql["where"] = rebuild_condition_col(valid_col_units, sql["where"], kmap) sql["groupBy"] = rebuild_group_by_col(valid_col_units, sql["groupBy"], kmap) sql["orderBy"] = rebuild_order_by_col(valid_col_units, sql["orderBy"], kmap) sql["having"] = rebuild_condition_col(valid_col_units, sql["having"], kmap) sql["intersect"] = rebuild_sql_col(valid_col_units, sql["intersect"], kmap) sql["except"] = rebuild_sql_col(valid_col_units, sql["except"], kmap) sql["union"] = rebuild_sql_col(valid_col_units, sql["union"], kmap) return sql
null
163,487
import os, sys import json import sqlite3 import traceback import argparse from .process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def build_foreign_key_map(entry): # print("entry in build_foreign_key_map: ", entry) cols_orig = entry["column_names_original"] tables_orig = entry["table_names_original"] # rebuild cols corresponding to idmap in Schema cols = [] for col_orig in cols_orig: if col_orig[0] >= 0: t = tables_orig[col_orig[0]] c = col_orig[1] cols.append("__" + t.lower() + "." + c.lower() + "__") else: cols.append("__all__") def keyset_in_list(k1, k2, k_list): for k_set in k_list: if k1 in k_set or k2 in k_set: return k_set new_k_set = set() k_list.append(new_k_set) return new_k_set foreign_key_list = [] foreign_keys = entry["foreign_keys"] for fkey in foreign_keys: key1, key2 = fkey key_set = keyset_in_list(key1, key2, foreign_key_list) key_set.add(key1) key_set.add(key2) foreign_key_map = {} for key_set in foreign_key_list: sorted_list = sorted(list(key_set)) midx = sorted_list[0] for idx in sorted_list: foreign_key_map[cols[idx]] = cols[midx] return foreign_key_map def build_foreign_key_map_from_json(table): with open(table) as f: data = json.load(f) tables = {} for entry in data: tables[entry["db_id"]] = build_foreign_key_map(entry) return tables
null
163,488
import json def _get_schemas_from_json(data: dict): 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 def get_schemas_from_json(fpath): with open(fpath) as f: data = json.load(f) return _get_schemas_from_json(data)
null
163,489
import copy import math import random import warnings from typing import Optional, Tuple import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.models.bart.configuration_bart import BartConfig from transformers.activations import ACT2FN from transformers.file_utils import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from transformers.modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions, Seq2SeqLMOutput, Seq2SeqModelOutput, Seq2SeqQuestionAnsweringModelOutput, Seq2SeqSequenceClassifierOutput, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging The provided code snippet includes necessary dependencies for implementing the `shift_tokens_right` function. Write a Python function `def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int)` to solve the following problem: Shift input ids one token to the right. Here is the function: def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): """ Shift input ids one token to the right. """ shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() shifted_input_ids[:, 0] = decoder_start_token_id assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." # replace possible -100 values in labels by `pad_token_id` shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) return shifted_input_ids
Shift input ids one token to the right.
163,490
import copy import math import random import warnings from typing import Optional, Tuple import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.models.bart.configuration_bart import BartConfig from transformers.activations import ACT2FN from transformers.file_utils import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from transformers.modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions, Seq2SeqLMOutput, Seq2SeqModelOutput, Seq2SeqQuestionAnsweringModelOutput, Seq2SeqSequenceClassifierOutput, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0)` to solve the following problem: Make causal mask used for bi-directional self-attention. Here is the function: def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), float("-inf")) mask_cond = torch.arange(mask.size(-1)) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
Make causal mask used for bi-directional self-attention.
163,491
import copy import math import random import warnings from typing import Optional, Tuple import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.models.bart.configuration_bart import BartConfig from transformers.activations import ACT2FN from transformers.file_utils import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from transformers.modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions, Seq2SeqLMOutput, Seq2SeqModelOutput, Seq2SeqQuestionAnsweringModelOutput, Seq2SeqSequenceClassifierOutput, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem: Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. Here is the function: def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
163,492
import copy import math import os import warnings import torch from torch import nn from torch.nn import CrossEntropyLoss from torch.utils.checkpoint import checkpoint from transformers.activations import ACT2FN from transformers.file_utils import ( DUMMY_INPUTS, DUMMY_MASK, add_start_docstrings, add_start_docstrings_to_model_forward, is_torch_fx_proxy, replace_return_docstrings, ) from transformers.modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, Seq2SeqLMOutput, Seq2SeqModelOutput, ) from transformers.modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer from transformers.utils import logging from transformers.utils.model_parallel_utils import assert_device_map, get_device_map from transformers.models.t5.configuration_t5 import T5Config logger = logging.get_logger(__name__) The provided code snippet includes necessary dependencies for implementing the `load_tf_weights_in_t5` function. Write a Python function `def load_tf_weights_in_t5(model, config, tf_checkpoint_path)` to solve the following problem: Load tf checkpoints in a pytorch model. Here is the function: def load_tf_weights_in_t5(model, config, tf_checkpoint_path): """Load tf checkpoints in a pytorch model.""" try: import re import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise tf_path = os.path.abspath(tf_checkpoint_path) logger.info(f"Converting TensorFlow checkpoint from {tf_path}") # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] tf_weights = {} for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) names.append(name) tf_weights[name] = array for txt_name in names: name = txt_name.split("/") # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any( n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name ): logger.info(f"Skipping {'/'.join(name)}") tf_weights.pop(txt_name, None) continue if "_slot_" in name[-1]: logger.info(f"Skipping {'/'.join(name)}") tf_weights.pop(txt_name, None) continue pointer = model array = tf_weights[txt_name] for m_name in name: if re.fullmatch(r"[A-Za-z]+_\d+", m_name): scope_names = re.split(r"_(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] in ["kernel", "scale", "embedding"]: pointer = getattr(pointer, "weight") elif scope_names[0] == "self_attention": pointer = getattr(pointer, "layer") pointer = pointer[0] elif scope_names[0] == "enc_dec_attention": pointer = getattr(pointer, "layer") pointer = pointer[1] elif scope_names[0] == "dense_relu_dense": pointer = getattr(pointer, "layer") pointer = pointer[2] elif scope_names[0] == "rms_norm": if hasattr(pointer, "layer_norm"): pointer = getattr(pointer, "layer_norm") elif hasattr(pointer, "final_layer_norm"): pointer = getattr(pointer, "final_layer_norm") elif scope_names[0] == "scale": pointer = getattr(pointer, "weight") elif scope_names[0] == "output_bias" or scope_names[0] == "beta": pointer = getattr(pointer, "bias") elif scope_names[0] == "squad": pointer = getattr(pointer, "classifier") elif scope_names[0] == "decoder" and name[1] == "logits": continue elif scope_names[0] == "logits": pointer = getattr(pointer, "lm_head") elif scope_names[0] == "wi" and len(scope_names) > 1 and scope_names[1].isdigit(): pointer = getattr(pointer, f"wi_{scope_names[1]}") continue else: try: pointer = getattr(pointer, scope_names[0]) except AttributeError: logger.info(f"Skipping {'/'.join(name)}") continue if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] if scope_names[0] not in ["kernel", "scale", "embedding"]: pointer = getattr(pointer, "weight") if scope_names[0] != "embedding": logger.info(f"Transposing numpy weight of shape {array.shape} for {name}") array = np.transpose(array) try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array.astype(np.float32)) tf_weights.pop(txt_name, None) logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}.") return model
Load tf checkpoints in a pytorch model.