id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
38,939 | from collections import OrderedDict
import argparse
huggingface_to_paddle = {
"embeddings.LayerNorm": "embeddings.layer_norm",
"encoder.layer": "encoder.layers",
"attention.self.query.": "self_attn.q_proj.",
"attention.self.key.": "self_attn.k_proj.",
"attention.self.value.": "self_attn.v_proj.",
... | null |
38,940 | import argparse
import logging
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from paddle.io import DataLoader
from paddle.metric import Accuracy
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import Acc... | null |
38,941 | import argparse
import logging
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from paddle.io import DataLoader
from paddle.metric import Accuracy
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import Acc... | null |
38,942 | import argparse
import logging
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from paddle.io import DataLoader
from paddle.metric import Accuracy
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import Acc... | print arguments |
38,943 | import argparse
import io
import logging
import os
import random
import time
import numpy as np
import paddle
from paddlenlp.transformers import (
ConvBertForTotalPretraining,
ConvBertGenerator,
ConvBertPretrainingCriterion,
ConvBertTokenizer,
LinearDecayWithWarmup,
)
MODEL_CLASSES = {
"convbert... | null |
38,944 | import argparse
import io
import logging
import os
import random
import time
import numpy as np
import paddle
from paddlenlp.transformers import (
ConvBertForTotalPretraining,
ConvBertGenerator,
ConvBertPretrainingCriterion,
ConvBertTokenizer,
LinearDecayWithWarmup,
)
MODEL_CLASSES = {
"convbert... | null |
38,945 | import argparse
import io
import logging
import os
import random
import time
import numpy as np
import paddle
from paddlenlp.transformers import (
ConvBertForTotalPretraining,
ConvBertGenerator,
ConvBertPretrainingCriterion,
ConvBertTokenizer,
LinearDecayWithWarmup,
)
The provided code snippet incl... | print arguments |
38,946 | import argparse
from tqdm.auto import tqdm
import os
import paddle
from dataset_cmrc2018 import get_dev_dataloader
from train_cmrc2018 import MODEL_CLASSES
from metric import compute_prediction
from utils import save_json
def save_json(data, file_name):
def evaluate(model, data_loader, args, output_dir="./"):
mod... | null |
38,947 | import argparse
from tqdm.auto import tqdm
import os
import paddle
from dataset_cmrc2018 import get_dev_dataloader
from train_cmrc2018 import MODEL_CLASSES
from metric import compute_prediction
from utils import save_json
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argume... | null |
38,948 | import json
import pickle
import random
from collections import OrderedDict
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import (
CosineDecayWithWarmup,
LinearDecayWithWarmup,
PolyDecayWithWarmu... | Have lower learning rates for layers closer to the input. |
38,949 | import json
import pickle
import random
from collections import OrderedDict
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import (
CosineDecayWithWarmup,
LinearDecayWithWarmup,
PolyDecayWithWarmu... | null |
38,950 | import json
import pickle
import random
from collections import OrderedDict
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import (
CosineDecayWithWarmup,
LinearDecayWithWarmup,
PolyDecayWithWarmu... | null |
38,951 | import json
import pickle
import random
from collections import OrderedDict
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import (
CosineDecayWithWarmup,
LinearDecayWithWarmup,
PolyDecayWithWarmu... | null |
38,952 | import json
import pickle
import random
from collections import OrderedDict
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import (
CosineDecayWithWarmup,
LinearDecayWithWarmup,
PolyDecayWithWarmu... | null |
38,953 | import json
import pickle
import random
from collections import OrderedDict
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import (
CosineDecayWithWarmup,
LinearDecayWithWarmup,
PolyDecayWithWarmu... | null |
38,954 | import os
from dataclasses import dataclass, field
from functools import partial
from typing import Optional
import numpy as np
import paddle
from paddle.metric import Accuracy
from utils import load_ds_xnli
from paddlenlp.data import Pad, Stack
from paddlenlp.trainer import PdArgumentParser, Trainer, TrainingArguments... | null |
38,955 | import os
from functools import partial
from typing import List, Optional
import numpy as np
import paddle
from paddle.io import DataLoader, Dataset
from utils import load_pickle, save_pickle
from paddlenlp.datasets import load_dataset
from paddlenlp.trainer import Trainer
from paddlenlp.trainer.trainer_utils import (
... | null |
38,956 | import logging
import os
from dataclasses import dataclass, field
from typing import Optional
import paddle
from cmrc_evaluate import get_result
from dataset_cmrc2018 import EvalTrainer, get_dev_dataset, get_train_dataset
from metric_cmrc import compute_prediction, squad_evaluate
from utils import CrossEntropyLossForSQ... | null |
38,957 | import os
from dataclasses import dataclass, field
from functools import partial
from typing import Optional
import numpy as np
import paddle
from paddle.metric import Accuracy
from utils import load_ds
from paddlenlp.data import Pad, Stack
from paddlenlp.trainer import PdArgumentParser, Trainer, TrainingArguments, set... | null |
38,958 | import os
import sys
import random
import numpy as np
import paddle
from data_util import atis_data
from logger import Logger
from model.schema_interaction_model import SchemaInteractionATISModel
from model_util import ( # noqa: E402
Metrics,
evaluate_interaction_sample,
evaluate_using_predicted_quer... | Trains a model. Args: model (ATISModel): The model to train. data (ATISData): The data that is used to train. params (namespace): Training parameters. |
38,959 | import os
import sys
import random
import numpy as np
import paddle
from data_util import atis_data
from logger import Logger
from model.schema_interaction_model import SchemaInteractionATISModel
from model_util import ( # noqa: E402
Metrics,
evaluate_interaction_sample,
evaluate_using_predicted_quer... | Evaluates a pretrained model on a dataset. Args: model (ATISModel): Model class. data (ATISData): All of the data. params (namespace): Parameters for the model. last_save_file (str): Location where the model save file is. |
38,960 | import argparse
import json
import os
import pickle
import shutil
import sqlparse
from postprocess_eval import get_candidate_tables
def write_interaction(interaction_list, split, output_dir):
json_split = os.path.join(output_dir, split + ".json")
pkl_split = os.path.join(output_dir, split + ".pkl")
with ope... | null |
38,961 | 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"]]
sch... | null |
38,962 | import json
import sqlite3
from nltk import word_tokenize
def load_data(fpath):
with open(fpath) as f:
data = json.load(f)
return data | null |
38,963 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def condition_has_or(conds):
return "or" in conds[1::2] | null |
38,964 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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 |
38,965 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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... | null |
38,966 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
UNIT_OPS = ("none", "-", "+", "*", "/")
def val_has_op(val_unit):
return val_unit[0] != UNIT_OPS.index("none") | null |
38,967 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def accuracy(count, total):
if count == total:
return 1
return 0 | null |
38,968 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def recall(count, total):
if count == total:
return 1
return 0 | null |
38,969 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def F1(acc, rec):
if (acc + rec) == 0:
return 0
return (2.0 * acc * rec) / (acc + rec) | null |
38,970 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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 |
38,971 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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)
... | null |
38,972 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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... | null |
38,973 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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 =... | null |
38,974 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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 u... | null |
38,975 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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["orde... | null |
38,976 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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
re... | null |
38,977 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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 ... | null |
38,978 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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 ... | null |
38,979 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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... | null |
38,980 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def get_nestedSQL(sql):
def count_component2(sql):
nested = get_nestedSQL(sql)
return len(nested) | null |
38,981 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def count_agg(units):
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["group... | null |
38,982 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def isValidSQL(sql, db):
conn = sqlite3.connect(db)
cursor = conn.cursor()
try:
cursor.execute(sql)
except Exception:
return False
return True | null |
38,983 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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_co... | null |
38,984 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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 ... | null |
39,003 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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_ag... | null |
39,005 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_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_co... | null |
39,006 | import argparse
import json
import os
import sqlite3
from process_sql import Schema, get_schema, get_sql
def build_foreign_key_map(entry):
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_for... | null |
39,007 | import argparse
import os
import sys
args = sys.argv
The provided code snippet includes necessary dependencies for implementing the `interpret_args` function. Write a Python function `def interpret_args()` to solve the following problem:
Interprets the command line arguments, and returns a dictionary.
Here is the fun... | Interprets the command line arguments, and returns a dictionary. |
39,008 | import copy
import random
import signal
import pymysql
import sqlparse
from sqlparse import sql as sql_types
from sqlparse import tokens as token_types
from . import util
from .snippets import Snippet
def get_all_in_parens(sequence):
def split_by_conj(sequence):
def get_sql_snippets(sequence):
# First, get all sub... | null |
39,009 | import copy
import random
import signal
import pymysql
import sqlparse
from sqlparse import sql as sql_types
from sqlparse import tokens as token_types
from . import util
from .snippets import Snippet
def add_snippets_to_query(snippets, ignored_entities, query, prob_align=1.0):
query_copy = copy.copy(query)
#... | null |
39,010 | import copy
import random
import signal
import pymysql
import sqlparse
from sqlparse import sql as sql_types
from sqlparse import tokens as token_types
from . import util
from .snippets import Snippet
def fix_parentheses(sequence):
num_left = sequence.count("(")
num_right = sequence.count(")")
if num_righ... | null |
39,011 | import nltk
import sqlparse
The provided code snippet includes necessary dependencies for implementing the `nl_tokenize` function. Write a Python function `def nl_tokenize(string)` to solve the following problem:
Tokenizes a natural language string into tokens. Assumes data is space-separated (this is true of ZC07 dat... | Tokenizes a natural language string into tokens. Assumes data is space-separated (this is true of ZC07 data in ATIS2/3). Args: string(`str`): the string to tokenize. Outputs: `list`: a list of tokens. |
39,012 | import nltk
import sqlparse
The provided code snippet includes necessary dependencies for implementing the `sql_tokenize` function. Write a Python function `def sql_tokenize(string)` to solve the following problem:
Tokenizes a SQL statement into tokens. Args: string(`str`): string to tokenize. Outputs: `list`: a list ... | Tokenizes a SQL statement into tokens. Args: string(`str`): string to tokenize. Outputs: `list`: a list of tokens. |
39,013 | import nltk
import sqlparse
The provided code snippet includes necessary dependencies for implementing the `lambda_tokenize` function. Write a Python function `def lambda_tokenize(string)` to solve the following problem:
Tokenizes a lambda-calculus statement into tokens. Args: string(`str`): a lambda-calculus string O... | Tokenizes a lambda-calculus statement into tokens. Args: string(`str`): a lambda-calculus string Outputs: `list`: a list of tokens. |
39,014 | import paddle
from . import anonymization as anon
from . import sql_util
from .snippets import expand_snippets
from .utterance import Utterance, OUTPUT_KEY, ANON_INPUT_KEY
class Schema:
def __init__(self, table_schema, simple=False):
if simple:
self.helper1(table_schema)
else:
... | null |
39,015 | import copy
import json
from . import util
The provided code snippet includes necessary dependencies for implementing the `timeval` function. Write a Python function `def timeval(string)` to solve the following problem:
Returns the numeric version of a time. Args: string (`str`): String representing a time. Returns: `... | Returns the numeric version of a time. Args: string (`str`): String representing a time. Returns: `str`: String representing the absolute time. |
39,016 | import copy
import json
from . import util
The provided code snippet includes necessary dependencies for implementing the `is_time` function. Write a Python function `def is_time(string)` to solve the following problem:
Returns whether a string represents a time. Args: string (str): String to check. Returns: `bool`: W... | Returns whether a string represents a time. Args: string (str): String to check. Returns: `bool`: Whether the string represents a time. |
39,017 | import copy
import json
from . import util
The provided code snippet includes necessary dependencies for implementing the `deanonymize` function. Write a Python function `def deanonymize(sequence, ent_dict, key)` to solve the following problem:
Deanonymizes a sequence. Args: sequence (`list`): List of tokens to deanon... | Deanonymizes a sequence. Args: sequence (`list`): List of tokens to deanonymize. ent_dict (`dict`): Maps from tokens to the entity dictionary. key (`str`): The key to use, in this case either natural language or SQL. Returns: `list`: Deanonymized sequence of tokens. |
39,018 | def is_snippet(token):
"""Determines whether a token is a snippet or not.
Args:
token (`str`): The token to check.
Returns:
`bool`: Indicating whether it's a snippet.
"""
return token.startswith(SNIPPET_PREFIX)
The provided code snippet includes necessary dependencies for implementi... | Given a sequence and a list of snippets, expand the snippets in the sequence. Args: sequence (`list`): Query containing snippet references. snippets (`list`): List of available snippets. Returns: `list`: The expanded sequence list. |
39,019 | def is_snippet(token):
"""Determines whether a token is a snippet or not.
Args:
token (`str`): The token to check.
Returns:
`bool`: Indicating whether it's a snippet.
"""
return token.startswith(SNIPPET_PREFIX)
The provided code snippet includes necessary dependencies for implementi... | Returns the index of a snippet. Args: token (`str`): The snippet to check. Returns: `int`: The index of the snippet. |
39,020 | import argparse
import json
import os
import subprocess
import traceback
from collections import defaultdict
import sqlparse
def postprocess_one(pred_sql, schema):
pred_sql = (
pred_sql.replace("group_by", "group by")
.replace("order_by", "order by")
.replace("limit_value", "limit 1")
... | null |
39,021 | import argparse
import json
import os
import subprocess
import traceback
from collections import defaultdict
import sqlparse
def read_prediction(pred_file):
print("Read prediction from", pred_file)
predictions = []
with open(pred_file) as f:
for line in f:
pred = json.loads(line)
... | null |
39,022 | import argparse
import json
import os
import subprocess
import traceback
from collections import defaultdict
import sqlparse
def read_schema(table_schema_path):
with open(table_schema_path) as f:
database_schema = json.load(f)
database_schema_dict = {}
for table_schema in database_schema:
... | null |
39,023 | import argparse
import json
import os
import subprocess
import traceback
from collections import defaultdict
import sqlparse
def write_and_evaluate(postprocess_sqls, db_path, table_schema_path, gold_path, dataset):
db_list = []
with open(gold_path) as f:
for line in f:
line_split = line.str... | null |
39,024 | from collections import namedtuple
import paddle
import paddle.nn.functional as F
from .attention import Attention, AttentionResult
def score_schema_tokens(input_schema, schema_states, scorer):
# schema_states: emd_dim x num_tokens
scores = paddle.t(paddle.mm(paddle.t(scorer), schema_states)) # num_tokens x 1... | null |
39,025 | from collections import namedtuple
import paddle
import paddle.nn.functional as F
from .attention import Attention, AttentionResult
def score_query_tokens(previous_query, previous_query_states, scorer):
scores = paddle.t(paddle.mm(paddle.t(scorer), previous_query_states)) # num_tokens x 1
if scores.shape[0] !... | null |
39,026 | from collections import namedtuple
import paddle
import paddle.nn.functional as F
from .attention import Attention, AttentionResult
class SchemaTokenPredictor(TokenPredictor):
"""Token predictor that also predicts snippets.
Attributes:
snippet_weights (`Parameter`): Weights for scoring snippets against ... | Constructs a token predictor given the parameters. Args: params (`dict`): Contains the command line parameters/hyperparameters. vocabulary (`Vocabulary`): Vocabulary object for output generation. attention_key_size (`int`): The size of the attention keys. anonymizer (`Anonymizer`): An anonymization object. |
39,027 | import data_util.snippets as snippet_handler
import data_util.vocabulary as vocabulary_handler
import paddle
The provided code snippet includes necessary dependencies for implementing the `bow_snippets` function. Write a Python function `def bow_snippets(token, snippets, output_embedder, input_schema)` to solve the fo... | Bag of words embedding for snippets |
39,028 | import paddle
from paddlenlp.transformers import BertModel, BertPretrainedModel, BertTokenizer
def get_bert(params):
model_bert = BertModel.from_pretrained("bert-base-uncased")
bert_config = BertPretrainedModel.pretrained_init_configuration["bert-base-uncased"]
tokenizer = BertTokenizer.from_pretrained("be... | null |
39,029 | import paddle
from paddlenlp.transformers import BertModel, BertPretrainedModel, BertTokenizer
def get_wemb_bert(
bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=1, num_out_layers_h=1
):
def prepare_input(tokenizer, input_sequence, input_schema, max_seq_length):
def prepare_input_v2... | null |
39,030 | import numpy as np
import paddle
from data_util.vocabulary import DEL_TOK, UNK_TOK
from . import bert_utils
from .embedder import Embedder
UNK_TOK = "_UNK"
The provided code snippet includes necessary dependencies for implementing the `get_token_indices` function. Write a Python function `def get_token_indices(token,... | Maps from a gold token (string) to a list of indices. Args: token (`string`): String to look up. index_to_token (`list`): Ordered list of tokens. Returns: `list`: Representing the indices of the token in the probability distribution. |
39,031 | import numpy as np
import paddle
from data_util.vocabulary import DEL_TOK, UNK_TOK
from . import bert_utils
from .embedder import Embedder
DEL_TOK = ";"
The provided code snippet includes necessary dependencies for implementing the `flatten_utterances` function. Write a Python function `def flatten_utterances(utteran... | Gets a flat sequence from a sequence of utterances. Args: utterances (`list`): Utterances to concatenate. Returns: `list`: Representing the flattened sequence with separating delimiter tokens. |
39,032 | import numpy as np
import paddle
from data_util.vocabulary import DEL_TOK, UNK_TOK
from . import bert_utils
from .embedder import Embedder
The provided code snippet includes necessary dependencies for implementing the `encode_snippets_with_states` function. Write a Python function `def encode_snippets_with_states(snip... | Encodes snippets by using previous query states instead. Args: snippets (`list`): Input snippets. states (`list`): Previous hidden states to use. |
39,033 | import numpy as np
import paddle
from data_util.vocabulary import DEL_TOK, UNK_TOK
from . import bert_utils
from .embedder import Embedder
def load_word_embeddings(input_vocabulary, output_vocabulary, output_vocabulary_schema, params):
print(output_vocabulary.inorder_tokens)
print()
if params.reload_embed... | null |
39,034 | import numpy as np
import paddle
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `compute_loss` function. Write a Python function `def compute_loss(gold_seq, scores, index_to_token_maps, gold_tok_to_id, noise=0.00000001)` to solve the following problem:
C... | Computes the loss of a gold sequence given scores. Args: gold_seq (`list`): A sequence of gold tokens. scores (`list`): Expressions representing the scores of potential output tokens for each token in gold_seq. index_to_token_maps (`list`): Maps from index in the sequence to a dictionary mapping from a string to a set ... |
39,035 | import numpy as np
import paddle
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `get_seq_from_scores` function. Write a Python function `def get_seq_from_scores(scores, index_to_token_maps)` to solve the following problem:
Gets the argmax sequence from a... | Gets the argmax sequence from a set of scores. Args: scores (`list`): Sequences of output scores. index_to_token_maps (`list`): For each output token, maps the index in the probability distribution to a string. Returns: `list`: Representing the argmax sequence. |
39,036 | import numpy as np
import paddle
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `per_token_accuracy` function. Write a Python function `def per_token_accuracy(gold_seq, pred_seq)` to solve the following problem:
Returns the per-token accuracy comparing t... | Returns the per-token accuracy comparing two strings (recall). Args: gold_seq (`list`): A list of gold tokens. pred_seq (`list`): A list of predicted tokens. Returns: `float`: Representing the accuracy. |
39,037 | import numpy as np
import paddle
import paddle.nn.functional as F
def forward_one_multilayer(rnns, lstm_input, layer_states, dropout_amount=0.0):
"""Goes forward for one multilayer RNN cell step.
Args:
lstm_input (`Tensor`): Some input to the step.
layer_states (`list`): The states of each layer... | Encodes a sequence given RNN cells and an embedding function. Args: seq (`list`): The sequence to encode. rnns (`list`): The RNNs to use. emb_fn (`func`): Function that embeds strings to word vectors. size (`int`): The size of the RNN. dropout_amount (`float`, optional): The amount of dropout to apply. Returns: (`list`... |
39,038 | import numpy as np
import paddle
import paddle.nn.functional as F
def mask_fill(input, mask, value):
return input * paddle.cast(paddle.logical_not(mask), input.dtype) + paddle.cast(mask, input.dtype) * value | null |
39,039 | import numpy as np
import paddle
import paddle.nn.functional as F
def LSTM_output_transfer(utterance_states, final_utterance_state):
if len(utterance_states) != 0:
utterance_states = utterance_states.squeeze(0)
utterance_states = paddle.split(utterance_states, utterance_states.shape[0])
fo... | null |
39,040 | from collections import namedtuple
import data_util.snippets as snippet_handler
import numpy as np
import paddle
import paddle.nn.functional as F
from data_util.vocabulary import EOS_TOK, UNK_TOK
from . import embedder
from .token_predictor import PredictionInputWithSchema
np.random.seed(0)
The provided code snippet i... | Flattens a probability distribution given a map of "unique" values. All values in distribution_map with the same value should get the sum of the probabilities. Arguments: distribution_map (`list`): List of values to get the probability for. probabilities (`np.ndarray`): Probabilities corresponding to the values in dist... |
39,041 | import logging
import random
import sys
from functools import partial
from pathlib import Path
import numpy as np
import paddle
import paddle.distributed as dist
import text2sql
from text2sql import dataproc, global_config, launch
from text2sql.grammars.cspider_v2 import CSpiderLanguageV2
from text2sql.grammars.dusql_v... | null |
39,042 | import logging
import random
import sys
from functools import partial
from pathlib import Path
import numpy as np
import paddle
import paddle.distributed as dist
import text2sql
from text2sql import dataproc, global_config, launch
from text2sql.grammars.cspider_v2 import CSpiderLanguageV2
from text2sql.grammars.dusql_v... | null |
39,043 | import logging
import random
import sys
from functools import partial
from pathlib import Path
import numpy as np
import paddle
import paddle.distributed as dist
import text2sql
from text2sql import dataproc, global_config, launch
from text2sql.grammars.cspider_v2 import CSpiderLanguageV2
from text2sql.grammars.dusql_v... | null |
39,044 | import logging
import random
import sys
from functools import partial
from pathlib import Path
import numpy as np
import paddle
import paddle.distributed as dist
import text2sql
from text2sql import dataproc, global_config, launch
from text2sql.grammars.cspider_v2 import CSpiderLanguageV2
from text2sql.grammars.dusql_v... | null |
39,045 | import logging
import random
import sys
from functools import partial
from pathlib import Path
import numpy as np
import paddle
import paddle.distributed as dist
import text2sql
from text2sql import dataproc, global_config, launch
from text2sql.grammars.cspider_v2 import CSpiderLanguageV2
from text2sql.grammars.dusql_v... | set process name on local machine |
39,046 | import json
import logging
import re
import sys
import traceback
from collections import defaultdict
from text2sql.dataproc.dusql_dataset_v2 import load_tables
_build(cells):
dct_index = defaultdict(set)
for cell in set(cells):
if type(cell) is not str:
continue
cell = cell.strip()
... | null |
39,047 | import json
import logging
import re
import sys
import traceback
from collections import defaultdict
from text2sql.dataproc.dusql_dataset_v2 import load_tables
def extract_value_from_sql(sql_json, sql_format="dusql"):
dct_col_values = defaultdict(list)
if sql_format == "nl2sql":
for col, _, val in item... | null |
39,048 | import json
import logging
import re
import sys
import traceback
from collections import defaultdict
from text2sql.dataproc.dusql_dataset_v2 import load_tables
_char_list(sentence):
def is_ascii(s):
"""check if s is English album or number
Args:
s (str): NULL
Returns: bool
... | null |
39,049 | import copy
import json
import logging
import re
op_sql_dict = {0: ">", 1: "<", 2: "==", 3: "!="}
agg_sql_dict = {0: "", 1: "AVG", 2: "MAX", 3: "MIN", 4: "COUNT", 5: "SUM"}
conn_sql_dict = {0: "", 1: "and", 2: "or"}
The provided code snippet includes necessary dependencies for implementing the `sql2query` function. Wr... | transform sql json to sql query, this is only for NL2SQL, eg. select a, b where a op val1 |
39,050 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
The provided code snippet includes necessary dependencies for implementing the `load_data` function. Write a Python function `def load_data(fpath)` to solve the following... | Args: Returns: |
39,051 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
The provided code snippet includes necessary dependencies for implementing the `get_scores` function. Write a Python function `def get_scores(count, pred_total, gold_tota... | Args: Returns: |
39,052 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
The provided code snippet includes necessary dependencies for implementing the `eval_sel` function. Write a Python function `def eval_sel(pred, gold)` to solve the follow... | Args: Returns: |
39,053 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
def eval_cond(pred, gold, value_match=True):
"""
Args:
pred (TYPE): NULL
gold (TYPE): NULL
Returns: TODO
Raises: NULL
"""
def _equa... | Args: Returns: |
39,054 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
The provided code snippet includes necessary dependencies for implementing the `eval_group` function. Write a Python function `def eval_group(pred, gold)` to solve the fo... | Args: Returns: |
39,055 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
def eval_cond(pred, gold, value_match=True):
"""
Args:
pred (TYPE): NULL
gold (TYPE): NULL
Returns: TODO
Raises: NULL
"""
def _equa... | 不评估and/or,在其它分支专门评估 Args: Returns: |
39,056 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
The provided code snippet includes necessary dependencies for implementing the `eval_order` function. Write a Python function `def eval_order(pred, gold, value_match=True... | Args: Returns: |
39,057 | import copy
import json
import logging
import re
from collections import defaultdict
from io import open
from utils import evaluate_NL2SQL, is_float
The provided code snippet includes necessary dependencies for implementing the `eval_and_or` function. Write a Python function `def eval_and_or(pred, gold)` to solve the ... | Args: Returns: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.