id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
39,162 | import os
import random
import time
import numpy as np
from functools import partial
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from paddle.io import DataLoader, DistributedBatchSampler, BatchSampler
from paddle.optimizer import AdamW
from paddle.metric impor... | null |
39,163 | import os
import random
import time
import numpy as np
from functools import partial
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from paddle.io import DataLoader, DistributedBatchSampler, BatchSampler
from paddle.optimizer import AdamW
from paddle.metric impor... | null |
39,164 | import argparse
def parse_args():
parser = argparse.ArgumentParser(__doc__)
parser.add_argument("--task_name", default=None, type=str, required=True, help="The name of the task to train.")
parser.add_argument("--model_name_or_path", default='bert-base-uncased', type=str, help="Path to pre-trained bert mode... | null |
39,165 | import argparse
def set_default_args(args):
args.task_name = args.task_name.lower()
if args.task_name == "udc":
if not args.save_steps:
args.save_steps = 1000
if not args.logging_steps:
args.logging_steps = 100
if not args.epochs:
args.epochs = 2
... | null |
39,166 | import os
import numpy as np
from typing import List
from paddle.io import Dataset
The provided code snippet includes necessary dependencies for implementing the `get_label_map` function. Write a Python function `def get_label_map(label_list)` to solve the following problem:
Create label maps
Here is the function:
d... | Create label maps |
39,167 | import os
import numpy as np
from typing import List
from paddle.io import Dataset
def read_da_data(data_dir, mode):
def _concat_dialogues(examples):
"""concat multi turns dialogues"""
new_examples = []
for i in range(len(examples)):
label, caller, text = examples[i]
... | null |
39,168 | import os
import numpy as np
from typing import List
from paddle.io import Dataset
INNER_SEP = "[unused0]"
def truncate_and_concat(
pre_txt: List[str], cur_txt: str, suf_txt: List[str], tokenizer, max_seq_length, max_len_of_cur_text
):
cur_tokens = tokenizer.tokenize(cur_txt)
cur_tokens = cur_tokens[: min(... | null |
39,169 | import argparse
from collections import namedtuple
import paddle
from model import Plato2InferModel
from readers.nsp_reader import NSPReader
from readers.plato_reader import PlatoReader
from termcolor import colored, cprint
from utils import gen_inputs
from utils.args import parse_args
from paddlenlp.trainer.argparser ... | Setup arguments. |
39,170 | import argparse
from collections import namedtuple
import paddle
from model import Plato2InferModel
from readers.nsp_reader import NSPReader
from readers.plato_reader import PlatoReader
from termcolor import colored, cprint
from utils import gen_inputs
from utils.args import parse_args
from paddlenlp.trainer.argparser ... | Inference main function. |
39,171 | from collections import namedtuple
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `post_process_context` function. Write a Python function `def post_process_context(token_ids, reader, merge=True)` to solve the followi... | Post-process the context sequence. |
39,172 | from collections import namedtuple
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `post_process_response` function. Write a Python function `def post_process_response(token_ids, reader, merge=True)` to solve the follo... | Post-process the decoded sequence. Truncate from the first <eos> and remove the <bos> and <eos> tokens currently. |
39,173 | from collections import namedtuple
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `get_cross_turn_repetition` function. Write a Python function `def get_cross_turn_repetition(context, pred_tokens, eos_idx, is_cn=False... | Get cross-turn repetition. |
39,174 | from collections import namedtuple
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `get_in_turn_repetition` function. Write a Python function `def get_in_turn_repetition(pred, is_cn=False)` to solve the following probl... | Get in-turn repetition. |
39,175 | import csv
import gzip
from collections import namedtuple
from contextlib import contextmanager
import numpy as np
import utils.tokenization as tokenization
from utils import pad_batch_data
from utils.masking import mask
from paddlenlp.trainer.argparser import strtobool
The provided code snippet includes necessary dep... | Open file. |
39,176 | import collections
import sentencepiece as spm
import unicodedata
from utils.args import str2bool
The provided code snippet includes necessary dependencies for implementing the `preprocess_text` function. Write a Python function `def preprocess_text(inputs, remove_space=True, lower=False)` to solve the following probl... | preprocess data by removing extra space and normalize data. |
39,177 | import collections
import sentencepiece as spm
import unicodedata
from utils.args import str2bool
def encode_pieces(spm_model, text, return_unicode=True, sample=False):
"""turn sentences into word pieces."""
# liujiaxiang: add for ernie-albert, mainly consider for “/”/‘/’/— causing too many unk
text = clean... | turn sentences into word pieces. |
39,178 | import collections
import sentencepiece as spm
import unicodedata
from utils.args import str2bool
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode... | Loads a vocabulary file into a dictionary. |
39,179 | import collections
import sentencepiece as spm
import unicodedata
from utils.args import str2bool
The provided code snippet includes necessary dependencies for implementing the `convert_by_vocab` function. Write a Python function `def convert_by_vocab(vocab, items)` to solve the following problem:
Converts a sequence ... | Converts a sequence of [tokens|ids] using the vocab. |
39,180 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `mask` function. Write a Python function `def mask( batch_tokens, vocab_size, bos_id=1, eos_id=2, mask_id=3, sent_b_starts=None, labels=None, is_unidirectional=False, use_latent=False, ... | Add mask for batch_tokens, return out, mask_label, mask_pos; Note: mask_pos responding the batch_tokens after padded; |
39,185 | import argparse
import math
import os
import time
import paddle
import paddle.distributed as dist
import paddle.nn as nn
import paddle.nn.functional as F
from datasets import load_dataset
from paddle.optimizer import AdamW
from paddle.optimizer.lr import NoamDecay
from utils import create_data_loader, print_args, set_s... | null |
39,186 | import argparse
import paddle
from termcolor import colored, cprint
from utils import print_args, select_response, set_seed
from paddlenlp.transformers import (
UnifiedTransformerLMHeadModel,
UnifiedTransformerTokenizer,
)
def parse_args():
parser = argparse.ArgumentParser(__doc__)
parser.add_argument(... | null |
39,187 | import argparse
import paddle
from termcolor import colored, cprint
from utils import print_args, select_response, set_seed
from paddlenlp.transformers import (
UnifiedTransformerLMHeadModel,
UnifiedTransformerTokenizer,
)
def select_response(ids, scores, tokenizer, max_dec_len=None, num_return_sequences=1, ke... | null |
39,188 | import argparse
import time
import paddle
from datasets import load_dataset
from utils import create_data_loader, print_args, select_response, set_seed
from paddlenlp.metrics import BLEU, Distinct
from paddlenlp.transformers import (
UnifiedTransformerLMHeadModel,
UnifiedTransformerTokenizer,
)
def parse_args(... | null |
39,189 | import argparse
import time
import paddle
from datasets import load_dataset
from utils import create_data_loader, print_args, select_response, set_seed
from paddlenlp.metrics import BLEU, Distinct
from paddlenlp.transformers import (
UnifiedTransformerLMHeadModel,
UnifiedTransformerTokenizer,
)
def calc_bleu_an... | null |
39,190 | import math
import os
import time
import paddle
import paddle.distributed as dist
import paddle.nn as nn
import paddle.nn.functional as F
from args import parse_args, print_args
from data import DialogueDataset
from paddle.io import DataLoader
from paddle.optimizer import AdamW
from paddle.optimizer.lr import NoamDecay... | null |
39,191 | import math
import os
import time
import paddle
import paddle.distributed as dist
import paddle.nn as nn
import paddle.nn.functional as F
from args import parse_args, print_args
from data import DialogueDataset
from paddle.io import DataLoader
from paddle.optimizer import AdamW
from paddle.optimizer.lr import NoamDecay... | null |
39,192 | import argparse
def parse_args():
parser = argparse.ArgumentParser(__doc__)
parser.add_argument('--model_name_or_path', type=str, default='unified_transformer-12L-cn', help='The path or shortcut name of the pre-trained model.')
parser.add_argument('--save_dir', type=str, default='./checkpoints', help='The ... | null |
39,194 | import time
import paddle
from args import parse_args, print_args
from data import DialogueDataset, select_response
from paddle.io import DataLoader
from paddlenlp.transformers import (
UnifiedTransformerLMHeadModel,
UnifiedTransformerTokenizer,
)
def select_response(ids, scores, tokenizer, max_dec_len=None, n... | null |
39,195 | import argparse
import os
from functools import partial
import paddle
from model import SimNet
from utils import convert_example
from paddlenlp.data import JiebaTokenizer, Pad, Stack, Tuple, Vocab
from paddlenlp.datasets import load_dataset
The provided code snippet includes necessary dependencies for implementing the... | Creats dataloader. Args: dataset(obj:`paddle.io.Dataset`): Dataset instance. trans_fn(obj:`callable`, optional, defaults to `None`): function to convert a data sample to input ids, etc. mode(obj:`str`, optional, defaults to obj:`train`): If mode is 'train', it will shuffle the dataset randomly. batch_size(obj:`int`, op... |
39,196 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example(example, tokenizer, is_test=False)` to solve the following problem:
Builds model inputs from a sequence for sequence classification tasks. It use `j... | Builds model inputs from a sequence for sequence classification tasks. It use `jieba.cut` to tokenize text. Args: example(obj:`list[str]`): List of input data, containing text and label if it have label. tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string. is_test(obj:`False`, defaults... |
39,199 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from data import convert_pairwise_example as convert_example
from data import create_dataloader, gen_pair
from model import PairwiseMatching
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.data... | null |
39,201 | import argparse
import os
import numpy as np
import paddle
from paddle import inference
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import AutoTokenizer
from paddlenlp.utils.log import logger
def convert_example(example, tokenizer, max_seq_length=512, i... | null |
39,202 | import paddle
import numpy as np
from paddlenlp.datasets import MapDataset
def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None):
if trans_fn:
dataset = dataset.map(trans_fn)
shuffle = True if mode == "train" else False
if mode == "train":
batch_sample... | null |
39,203 | import paddle
import numpy as np
from paddlenlp.datasets import MapDataset
The provided code snippet includes necessary dependencies for implementing the `read_text_pair` function. Write a Python function `def read_text_pair(data_path)` to solve the following problem:
Reads data.
Here is the function:
def read_text_... | Reads data. |
39,204 | import paddle
import numpy as np
from paddlenlp.datasets import MapDataset
def convert_pointwise_example(example, tokenizer, max_seq_length=512, is_test=False):
query, title = example["query"], example["title"]
encoded_inputs = tokenizer(text=query, text_pair=title, max_seq_len=max_seq_length)
input_ids... | null |
39,206 | import paddle
import numpy as np
from paddlenlp.datasets import MapDataset
The provided code snippet includes necessary dependencies for implementing the `gen_pair` function. Write a Python function `def gen_pair(dataset, pool_size=100)` to solve the following problem:
Generate triplet randomly based on dataset Args: ... | Generate triplet randomly based on dataset Args: dataset: A `MapDataset` or `IterDataset` or a tuple of those. Each example is composed of 2 texts: example["query"], example["title"] pool_size: the number of example to sample negative example randomly Return: dataset: A `MapDataset` or `IterDataset` or a tuple of those... |
39,207 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from data import convert_pointwise_example as convert_example
from data import create_dataloader
from model import PointwiseMatching
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets imp... | null |
39,208 | import argparse
import os
from functools import partial
import numpy as np
import paddle
from data import convert_pairwise_example as convert_example
from data import create_dataloader, read_text_pair
from model import PairwiseMatching
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
fr... | Predicts the data labels. Args: model (obj:`SemanticIndexBase`): A model to extract text embedding or calculate similarity of text pair. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): co... |
39,209 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from data import (
convert_example,
create_dataloader,
read_simcse_text,
read_text_pair,
word_repetition,
)
from model import SimCSE
from scipy import stats
from paddlenlp.data import P... | null |
39,210 | import argparse
import os
from functools import partial
import numpy as np
import paddle
from data import convert_example, create_dataloader, read_text_pair
from model import SimCSE
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import AutoModel, AutoTokeni... | Predicts the data labels. Args: model (obj:`SimCSE`): A model to extract text embedding or calculate similarity of text pair. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): cosine simila... |
39,211 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from model import SentenceTransformer
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import AutoModel, AutoTokenizer, LinearDecayWithWa... | null |
39,212 | import argparse
import os
import paddle
from model import SentenceTransformer
from paddlenlp.data import Pad, Tuple
from paddlenlp.transformers import AutoModel, AutoTokenizer
args = parser.parse_args()
def convert_example(example, tokenizer, max_seq_length=512):
"""
Builds model inputs from a sequence or a pai... | Predicts the data labels. Args: model (obj:`paddle.nn.Layer`): A model to classify texts. data (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object. A Example object contains `text`(word_ids) and `se_len`(sequence length). tokenizer(obj:`PretrainedTokenizer`): This tokenizer inh... |
39,213 | import paddle
def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None):
if trans_fn:
dataset = dataset.map(trans_fn)
shuffle = True if mode == "train" else False
if mode == "train":
batch_sampler = paddle.io.DistributedBatchSampler(dataset, batch_size=bat... | null |
39,214 | import paddle
The provided code snippet includes necessary dependencies for implementing the `read_text_pair` function. Write a Python function `def read_text_pair(data_path)` to solve the following problem:
Reads data.
Here is the function:
def read_text_pair(data_path):
"""Reads data."""
with open(data_pat... | Reads data. |
39,215 | import paddle
def convert_example(example, tokenizer, max_seq_length=512, phase="train"):
query, title = example["query"], example["title"]
query_encoded_inputs = tokenizer(text=query, max_seq_len=max_seq_length)
query_input_ids = query_encoded_inputs["input_ids"]
query_token_type_ids = query_encoded... | null |
39,216 | import argparse
from functools import partial
import paddle
from data import convert_example, create_dataloader, read_text_pair
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import AutoModel, AutoTokenizer
The provided code snippet includes necessary depe... | Predicts the similarity. Args: model (obj:`SemanticIndexBase`): A model to extract text embedding or calculate similarity of text pair. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): cos... |
39,217 | import random
import numpy as np
import paddle
from scipy import stats
def set_seed(seed=0):
random.seed(seed)
np.random.seed(seed)
paddle.seed(seed) | null |
39,218 | import random
import numpy as np
import paddle
from scipy import stats
def masked_fill(x, mask, value):
y = paddle.full(x.shape, value, x.dtype)
return paddle.where(mask, y, x) | null |
39,219 | import argparse
import os
import time
from functools import partial
import numpy as np
import paddle
from data import convert_example, create_dataloader, read_text_pair, read_text_single
from model import DiffCSE, Encoder
from utils import eval_metric, set_seed
from visualdl import LogWriter
import paddlenlp as ppnlp
f... | null |
39,220 | import argparse
import os
import time
from functools import partial
import numpy as np
import paddle
from data import convert_example, create_dataloader, read_text_pair, read_text_single
from model import DiffCSE, Encoder
from utils import eval_metric, set_seed
from visualdl import LogWriter
import paddlenlp as ppnlp
f... | null |
39,221 | import paddle
def get_special_tokens():
return ["[PAD]", "[CLS]", "[SEP]", "[MASK]", "[UNK]"] | null |
39,222 | import paddle
def get_special_token_dict(tokenizer):
special_tokens = ["[PAD]", "[CLS]", "[SEP]", "[MASK]", "[UNK]"]
special_token_dict = dict(zip(special_tokens, tokenizer.convert_tokens_to_ids(special_tokens)))
return special_token_dict | null |
39,224 | import paddle
def convert_example(example, tokenizer, max_seq_length=512, do_evalute=False):
result = []
for key, text in example.items():
if "label" in key:
# do_evaluate
result += [example["label"]]
else:
# do_train
encoded_inputs = tokenizer(te... | null |
39,225 | import paddle
def read_text_single(data_path):
with open(data_path, "r", encoding="utf-8") as f:
for line in f:
data = line.rstrip()
yield {"text_a": data, "text_b": data} | null |
39,226 | import paddle
def get_special_token_ids(tokenizer):
special_tokens = ["[PAD]", "[CLS]", "[SEP]", "[MASK]", "[UNK]"]
return tokenizer.convert_tokens_to_ids(special_tokens)
def masked_fill(x, mask, value):
y = paddle.full(x.shape, value, x.dtype)
return paddle.where(mask, y, x)
The provided code snippet ... | Description: Mask input_ids for masked language modeling: 80% MASK, 10% random, 10% original |
39,227 | import paddle
def read_text_pair(data_path, is_infer=False):
with open(data_path, "r", encoding="utf-8") as f:
for line in f:
data = line.rstrip().split("\t")
if is_infer:
if len(data[0]) == 0 or len(data[1]) == 0:
continue
yield {... | null |
39,228 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from data import convert_example, create_dataloader, read_text_pair
from model import QuestionMatching
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load_dataset
from paddlenl... | null |
39,229 | import numpy as np
import paddle
def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None):
if trans_fn:
dataset = dataset.map(trans_fn)
shuffle = True if mode == "train" else False
if mode == "train":
batch_sampler = paddle.io.DistributedBatchSampler(data... | null |
39,230 | import numpy as np
import paddle
The provided code snippet includes necessary dependencies for implementing the `read_text_pair` function. Write a Python function `def read_text_pair(data_path, is_test=False)` to solve the following problem:
Reads data.
Here is the function:
def read_text_pair(data_path, is_test=Fal... | Reads data. |
39,231 | import numpy as np
import paddle
def convert_example(example, tokenizer, max_seq_length=512, is_test=False):
query, title = example["query1"], example["query2"]
encoded_inputs = tokenizer(text=query, text_pair=title, max_seq_len=max_seq_length)
input_ids = encoded_inputs["input_ids"]
token_type_ids ... | null |
39,232 | import argparse
import os
from functools import partial
import numpy as np
import paddle
from data import convert_example, create_dataloader, read_text_pair
from model import QuestionMatching
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import AutoModel, ... | Predicts the data labels. Args: model (obj:`QuestionMatching`): A model to calculate whether the question pair is semantic similar or not. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): ... |
39,233 | import argparse
import functools
import os
import random
import time
import numpy as np
import paddle
from metric import MetricReport
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from utils import evaluate, preprocess_function, read_local_dataset
from paddlenlp.data import DataCollatorWithPad... | Training a hierarchical classification model |
39,234 | import os
import time
import numpy as np
import onnxruntime as ort
import paddle2onnx
from sklearn.metrics import f1_score
from paddlenlp.transformers import AutoTokenizer
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `sigmoid_` function. Write a ... | compute sigmoid |
39,235 | import argparse
import os
import psutil
from predictor import Predictor
from paddlenlp.datasets import load_dataset
def read_local_dataset(path, label_list):
label_list_dict = {label_list[i]: i for i in range(len(label_list))}
with open(path, "r", encoding="utf-8") as f:
for line in f:
item... | null |
39,236 | import os
from paddlenlp.datasets import load_dataset
The provided code snippet includes necessary dependencies for implementing the `load_local_dataset` function. Write a Python function `def load_local_dataset(data_path, splits, label_list)` to solve the following problem:
Load dataset for hierachical classification... | Load dataset for hierachical classification from files, where there is one example per line. Text and label are separated by '\t', and multiple labels are delimited by ','. Args: data_path (str): Path to the dataset directory, including label.txt, train.txt, dev.txt (and data.txt). splits (list): Which file(s) to load,... |
39,237 | import argparse
import functools
import os
import paddle
import paddle.nn.functional as F
from paddle.io import BatchSampler, DataLoader
from utils import preprocess_function, read_local_dataset
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers im... | Predicts the data labels. |
39,238 | import os
import functools
import paddle
import paddle.nn.functional as F
from paddleslim.nas.ofa import OFA
from paddlenlp.utils.log import logger
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_dataset
from paddlenlp.trainer import PdArgumentParser, Trainer, CompressionArguments... | null |
39,239 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
import paddle.nn as nn
from data import (
build_index,
convert_example,
create_dataloader,
gen_id2corpus,
gen_text_file,
read_text_pair,
)
from model import SemanticIndexBatchNeg
fr... | null |
39,240 | from paddle_serving_server.web_service import Op, WebService
def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False):
result = []
for text in example:
encoded_inputs = tokenizer(
text=text["sentence"], max_seq_len=max_seq_length, pad_to_max_seq_len=pad_to_max_s... | null |
39,241 | import argparse
import os
import sys
import paddle
from paddle import inference
from scipy import spatial
from paddlenlp.data import Pad, Tuple
from paddlenlp.transformers import AutoTokenizer
The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python func... | Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta... |
39,242 | import argparse
import os
import sys
import paddle
from paddle import inference
from scipy import spatial
from paddlenlp.data import Pad, Tuple
from paddlenlp.transformers import AutoTokenizer
The provided code snippet includes necessary dependencies for implementing the `convert_query_example` function. Write a Pytho... | Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta... |
39,243 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `convert_corpus_example` function. Write a Python function `def convert_corpus_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_l... | Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta... |
39,244 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `convert_label_example` function. Write a Python function `def convert_label_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len... | Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta... |
39,245 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `get_latest_checkpoint` function. Write a Python function `def get_latest_checkpoint(args)` to solve the following problem:
Return: (latest_che... | Return: (latest_checkpint_path, global_step) |
39,246 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
logger = Logger()
def get_latest_ann_data(ann_data_dir):
if not os.path.exists(ann_data_dir):
return None, -1
subdirectories = list(next(os.walk(ann_data_dir))[1])
def valid_checkpoint(step):
... | null |
39,247 | import argparse
import os
from functools import partial
import numpy as np
import paddle
from base_model import SemanticIndexBase
from data import convert_example, create_dataloader, read_text_pair
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import AutoM... | Predicts the data labels. Args: model (obj:`SemanticIndexBase`): A model to extract text embedding or calculate similarity of text pair. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): co... |
39,248 | import sys
import time
import numpy as np
import pandas as pd
from data import gen_id2corpus
from paddle_serving_server.pipeline import PipelineClient
from utils.milvus_util import RecallByMilvus
def gen_id2corpus(corpus_file):
id2corpus = {}
with open(corpus_file, "r", encoding="utf-8") as f:
for idx,... | null |
39,249 | import argparse
import time
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `recall` function. Write a Python function `def recall(rs, N=10)` to solve the following problem:
Ratio of recalled Ground Truth at topN Recalled Docs >>> rs = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]... | Ratio of recalled Ground Truth at topN Recalled Docs >>> rs = [[0, 0, 1], [0, 1, 0], [1, 0, 0]] >>> recall(rs, N=1) 0.333333 >>> recall(rs, N=2) >>> 0.6666667 >>> recall(rs, N=3) >>> 1.0 Args: rs: Iterator of recalled flag() Returns: Recall@N |
39,250 | import argparse
import os
import numpy as np
import paddle
from paddle import inference
from tqdm import tqdm
import paddlenlp as ppnlp
from paddlenlp.data import Pad, Tuple
The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_e... | Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta... |
39,251 | import argparse
import os
import numpy as np
import paddle
from paddle import inference
from tqdm import tqdm
import paddlenlp as ppnlp
from paddlenlp.data import Pad, Tuple
def read_text(file_path):
file = open(file_path)
id2corpus = {}
for idx, line in enumerate(file.readlines()):
id2corpus[idx] ... | null |
39,252 | import argparse
import numpy as np
from milvus_util import VecToMilvus
from tqdm import tqdm
class VecToMilvus:
def __init__(self):
self.client = Milvus(host=MILVUS_HOST, port=MILVUS_PORT)
def has_collection(self, collection_name):
try:
status, ok = self.client.has_collection(colle... | null |
39,253 | import argparse
import functools
import os
import random
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from trustai.interpretation import FeatureSimilarityModel
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers im... | null |
39,254 | import argparse
import paddle
from paddlenlp.dataaug import WordDelete, WordInsert, WordSubstitute, WordSwap
args = parser.parse_args()
The provided code snippet includes necessary dependencies for implementing the `aug` function. Write a Python function `def aug()` to solve the following problem:
Do data augmentation... | Do data augmentation |
39,255 | import argparse
import functools
import os
import random
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from trustai.interpretation import RepresenterPointModel
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers imp... | Get dirty data |
39,256 | import argparse
import functools
import os
import random
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from trustai.interpretation import FeatureSimilarityModel
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.dataaug import WordDelete, WordInsert, WordSubstitute, Word... | Find sparse data (lack of supports in train dataset) in dev dataset |
39,257 | import argparse
import functools
import os
import random
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from trustai.interpretation import FeatureSimilarityModel
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.dataaug import WordDelete, WordInsert, WordSubstitute, Word... | Find support data (which supports sparse data) from candidate dataset |
39,258 | import argparse
import functools
import os
import numpy as np
import paddle
import paddle.nn.functional as F
from paddle.io import BatchSampler, DataLoader
from sklearn.metrics import accuracy_score, classification_report, f1_score
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_d... | Evaluate the model performance |
39,259 | import argparse
import functools
import os
import random
import time
import numpy as np
import paddle
from metric import MetricReport
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from utils import evaluate, preprocess_function, read_local_dataset
from paddlenlp.data import DataCollatorWithPad... | Training a multi label classification model |
39,260 | import numpy as np
import paddle
import paddle.nn.functional as F
from paddlenlp.utils.log import logger
logger = Logger()
The provided code snippet includes necessary dependencies for implementing the `evaluate` function. Write a Python function `def evaluate(model, criterion, metric, data_loader)` to solve the foll... | Given a dataset, it evaluates model and computes the metric. Args: model(obj:`paddle.nn.Layer`): A model to classify texts. criterion(obj:`paddle.nn.Layer`): It can compute the loss. metric(obj:`paddle.metric.Metric`): The evaluation metric. data_loader(obj:`paddle.io.DataLoader`): The dataset loader which generates ba... |
39,261 | import numpy as np
import paddle
import paddle.nn.functional as F
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `preprocess_function` function. Write a Python function `def preprocess_function(examples, tokenizer, max_seq_length, label_nums, is_te... | Builds model inputs from a sequence for sequence classification tasks by concatenating and adding special tokens. Args: examples(obj:`list[str]`): List of input data, containing text and label if it have label. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.Pretrained... |
39,262 | import numpy as np
import paddle
import paddle.nn.functional as F
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `read_local_dataset` function. Write a Python function `def read_local_dataset(path, label_list=None, is_test=False)` to solve the foll... | Read dataset |
39,265 | import os
from paddlenlp.datasets import load_dataset
The provided code snippet includes necessary dependencies for implementing the `load_local_dataset` function. Write a Python function `def load_local_dataset(data_path, splits, label_list)` to solve the following problem:
Load dataset for multi-label classification... | Load dataset for multi-label classification from files, where there is one example per line. Text and label are separated by '\t', and multiple labels are delimited by ','. Args: data_path (str): Path to the dataset directory, including label.txt, train.txt, dev.txt (and data.txt). splits (list): Which file(s) to load,... |
39,266 | import argparse
import functools
import os
import paddle
import paddle.nn.functional as F
from paddle.io import BatchSampler, DataLoader
from utils import preprocess_function, read_local_dataset
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers im... | Predicts the data labels. |
39,267 | import functools
import os
from dataclasses import dataclass, field
import paddle
import paddle.nn.functional as F
from metric import MetricReport
from paddleslim.nas.ofa import OFA
from utils import preprocess_function, read_local_dataset
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets impor... | null |
39,268 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
import paddle.nn as nn
from data import (
build_index,
convert_example,
create_dataloader,
gen_id2corpus,
gen_text_file,
label2ids,
read_text_pair,
)
from metric import MetricRe... | null |
39,277 | import sys
import time
import numpy as np
import pandas as pd
from data import gen_id2corpus
from paddle_serving_server.pipeline import PipelineClient
from utils.config import collection_name, partition_tag
from utils.milvus_util import RecallByMilvus
def gen_id2corpus(corpus_file):
collection_name = "multi_label"
p... | null |
39,278 | import argparse
import numpy as np
from data import label2ids
from metric import MetricReport
from tqdm import tqdm
args = parser.parse_args()
class MetricReport(Metric):
"""
F1 score for hierarchical text classification task.
"""
def __init__(self, name="MetricReport", average="micro"):
super... | null |
39,280 | import argparse
import os
import numpy as np
import paddle
from paddle import inference
from tqdm import tqdm
import paddlenlp as ppnlp
from paddlenlp.data import Pad, Tuple
def read_text(file_path):
file = open(file_path)
id2corpus = {}
for idx, line in enumerate(file.readlines()):
id2corpus[idx] ... | null |
39,281 | import argparse
import numpy as np
from config import collection_name, partition_tag
from milvus_util import VecToMilvus
from tqdm import tqdm
collection_name = "multi_label"
partition_tag = "partition_2"
class VecToMilvus:
def __init__(self):
self.client = Milvus(host=MILVUS_HOST, port=MILVUS_PORT)
... | null |
39,287 | import argparse
import functools
import os
import numpy as np
import paddle
import paddle.nn.functional as F
from paddle.io import BatchSampler, DataLoader
from sklearn.metrics import accuracy_score, classification_report
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_dataset
fro... | Evaluate the model performance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.