id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
39,288 | import numpy as np
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_length, is_test=False)` to solve the following problem:
Builds model inputs ... | Builds model inputs from a sequence for sequence classification tasks by concatenating and adding special tokens. |
39,289 | import numpy as np
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, label2id=None, is_test=False)` to solve the following problem:
Read dataset.
Here is the functio... | Read dataset. |
39,290 | import numpy as np
from paddlenlp.utils.log import logger
logger = Logger()
The provided code snippet includes necessary dependencies for implementing the `log_metrics_debug` function. Write a Python function `def log_metrics_debug(output, id2label, dev_ds, bad_case_path)` to solve the following problem:
Log metrics ... | Log metrics in debug mode. |
39,291 | 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:
Read datasets from files. Args: data_path (... | Read datasets from files. Args: data_path (str): Path to the dataset directory, including label.txt, train.txt, dev.txt, test.txt (and data.txt). splits (list): Which file(s) to load, such as ['train', 'dev', 'test']. label_list(dict): A dictionary to encode labels as ids, which should be compatible with that of verbal... |
39,292 | 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,296 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
logger = Logger()
def build_index(corpus_data_loader, model, output_emb_size, hnsw_max_elements, hnsw_ef, hnsw_m):
index = hnswlib.Index(space="ip", dim=output_emb_size if output_emb_size > 0 else 768)
# Initial... | null |
39,297 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
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":... | null |
39,298 | 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_example` function. Write a Python function `def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False)` to ... | 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,301 | 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 `read_text_pair` function. Write a Python function `def read_text_pair(data_path)` to solve the following problem:
Reads data.
Here is the fun... | Reads data. |
39,303 | 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,304 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
def gen_id2corpus(corpus_file):
id2corpus = {}
with open(corpus_file, "r", encoding="utf-8") as f:
for idx, line in enumerate(f):
id2corpus[idx] = line.rstrip()
return id2corpus | null |
39,305 | import os
import hnswlib
import numpy as np
import paddle
from paddlenlp.utils.log import logger
def gen_text_file(similar_text_pair_file):
text2similar_text = {}
texts = []
with open(similar_text_pair_file, "r", encoding="utf-8") as f:
for idx, line in enumerate(f):
splited_line = line... | null |
39,307 | 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):
id2corpus = {}
with open(c... | null |
39,313 | 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,315 | 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,316 | 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,317 | import argparse
import json
import os
import random
import time
from decimal import Decimal
import numpy as np
import paddle
from tqdm import tqdm
from paddlenlp.utils.log import logger
args = parser.parse_args()
def set_seed(seed):
"""
Set random seed
"""
paddle.seed(seed)
random.seed(seed)
np.... | Convert doccano jsonl to fixed format |
39,318 | from dataclasses import dataclass, field
from functools import partial
from typing import Optional
import numpy as np
import paddle
from datasets import load_dataset
from utils import PegasusTrainer, compute_metrics, convert_example, main_process_first
from paddlenlp.data import DataCollatorForSeq2Seq
from paddlenlp.tr... | null |
39,319 | import contextlib
import random
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from paddle.io import DataLoader
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.u... | null |
39,320 | import contextlib
import random
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from paddle.io import DataLoader
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.u... | null |
39,321 | import contextlib
import random
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from paddle.io import DataLoader
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.u... | null |
39,322 | import contextlib
import random
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from paddle.io import DataLoader
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.u... | null |
39,323 | import contextlib
import random
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from paddle.io import DataLoader
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.u... | null |
39,324 | import contextlib
import random
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from paddle.io import DataLoader
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.u... | null |
39,325 | import contextlib
import random
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from paddle.io import DataLoader
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.u... | null |
39,326 | from dataclasses import dataclass, field
from functools import partial
from typing import Optional
import numpy as np
import paddle
from datasets import load_dataset
from utils import PegasusTrainer, compute_metrics, convert_example, main_process_first
from paddlenlp.data import DataCollatorForSeq2Seq
from paddlenlp.tr... | null |
39,327 | import contextlib
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.utils.log import logger
The provided code snippet includes necessary... | Convert a example into necessary features. |
39,328 | import contextlib
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.utils.log import logger
def compute_metrics(preds, targets):
ass... | null |
39,329 | import contextlib
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import paddle
from paddle import nn
from rouge import Rouge
from paddlenlp.metrics import BLEU
from paddlenlp.trainer import Seq2SeqTrainer
from paddlenlp.utils.log import logger
logger = Logger()
def main_process_first(de... | null |
39,330 | import argparse
import os
from pprint import pprint
import numpy as np
from paddle import inference
from paddlenlp.ops.ext_utils import load
from paddlenlp.transformers import PegasusChineseTokenizer
The provided code snippet includes necessary dependencies for implementing the `setup_args` function. Write a Python fu... | Setup arguments. |
39,331 | import argparse
import os
from pprint import pprint
import numpy as np
from paddle import inference
from paddlenlp.ops.ext_utils import load
from paddlenlp.transformers import PegasusChineseTokenizer
def load(name, build_dir=None, force=False, verbose=False, **kwargs):
# TODO(guosheng): Need better way to resolve ... | Setup inference predictor. |
39,332 | import argparse
import os
from pprint import pprint
import numpy as np
from paddle import inference
from paddlenlp.ops.ext_utils import load
from paddlenlp.transformers import PegasusChineseTokenizer
def convert_example(example, tokenizer, max_seq_len=512):
"""Convert all examples into necessary features."""
to... | Use predictor to inference. |
39,333 | import argparse
import os
from pprint import pprint
import paddle
from paddlenlp.ops import FasterPegasus
from paddlenlp.transformers import (
PegasusChineseTokenizer,
PegasusForConditionalGeneration,
)
from paddlenlp.utils.log import logger
def parse_args():
parser = argparse.ArgumentParser()
parser.a... | null |
39,334 | import argparse
import os
from pprint import pprint
import paddle
from paddlenlp.ops import FasterPegasus
from paddlenlp.transformers import (
PegasusChineseTokenizer,
PegasusForConditionalGeneration,
)
from paddlenlp.utils.log import logger
logger = Logger()
def do_predict(args):
place = "gpu"
place ... | null |
39,335 | import argparse
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from datasets import load_dataset
from paddle.io import BatchSampler, DataLoader
from utils import compute_metrics, convert_example
from paddlenlp.data import DataCollatorForSeq2Seq
from pa... | null |
39,336 | import argparse
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from datasets import load_dataset
from paddle.io import BatchSampler, DataLoader
from utils import compute_metrics, convert_example
from paddlenlp.data import DataCollatorForSeq2Seq
from pa... | null |
39,337 | import os
def prepare():
bos_link_train = "https://paddlenlp.bj.bcebos.com/datasets/tiny_summary_dataset/train.json"
bos_link_valid = "https://paddlenlp.bj.bcebos.com/datasets/tiny_summary_dataset/valid.json"
bos_link_test = "https://paddlenlp.bj.bcebos.com/datasets/tiny_summary_dataset/test.json"
os.... | null |
39,338 | import json
import os
import numpy as np
import paddle
from paddlenlp.utils.log import logger
logger = Logger()
The provided code snippet includes necessary dependencies for implementing the `read_local_dataset` function. Write a Python function `def read_local_dataset(data_path, data_file=None, is_test=False)` to so... | Load datasets with one example per line, formated as: {"text_a": X, "text_b": X, "question": X, "choices": [A, B], "labels": [0, 1]} |
39,339 | import distutils.util
import os
from typing import Any, Dict, List, Union
import fastdeploy as fd
import numpy as np
from paddlenlp.prompt import PromptDataCollatorWithPadding, UTCTemplate
from paddlenlp.transformers import AutoTokenizer
def parse_arguments():
import argparse
parser = argparse.ArgumentParser(... | null |
39,340 | import argparse
import json
import os
import random
import time
from decimal import Decimal
import numpy as np
import paddle
from paddlenlp.utils.log import logger
def set_seed(seed):
paddle.seed(seed)
random.seed(seed)
np.random.seed(seed)
class LabelStudioDataConverter(object):
"""
DataConverter t... | null |
39,341 | import json
import os
import re
from paddleocr import PaddleOCR
from paddlenlp.transformers import LayoutXLMTokenizer
def xlm_parse(ocr_res, tokenizer):
doc_bboxes = []
all_chr = get_all_chars(tokenizer)
try:
new_tokens, new_token_boxes = [], []
for item in ocr_res:
new_tokens.ex... | null |
39,342 | import json
import os
import re
from paddleocr import PaddleOCR
from paddlenlp.transformers import LayoutXLMTokenizer
def ocr_preprocess(img_dir):
ocr = PaddleOCR(use_angle_cls=True, lang="ch", use_gpu=True)
ocr_reses = []
img_names = sorted(os.listdir(img_dir), key=lambda x: int(x.split("_")[1].split(".")... | null |
39,343 | import cv2
import json
import numpy as np
def view_ocr_result(img_path, bboxes, opath):
image = cv2.imread(img_path)
for char_bbox in bboxes:
x_min, x_max, y_min, y_max = char_bbox
cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 0, 255), 1)
cv2.imwrite(opath, image) | null |
39,344 | import cv2
import json
import numpy as np
def _highlight_bbox(img, bbox):
x = bbox[0]
w = bbox[1] - x
y = bbox[2]
h = bbox[3] - y
sub_img = img[y : y + h, x : x + w]
colored_rect = np.zeros(sub_img.shape, dtype=np.uint8)
colored_rect[:, :, 2] = 255
colored_rect[:, :, 1] = 255
res = c... | null |
39,345 | import cv2
import json
import numpy as np
def _highlight_bbox(img, bbox):
x = bbox[0]
w = bbox[1] - x
y = bbox[2]
h = bbox[3] - y
sub_img = img[y : y + h, x : x + w]
colored_rect = np.zeros(sub_img.shape, dtype=np.uint8)
colored_rect[:, :, 2] = 255
colored_rect[:, :, 1] = 255
res = c... | null |
39,346 | import argparse
import json
import logging
import os
import random
import warnings
from collections import Counter
import numpy as np
import paddle
from docvqa import DocVQA
from model import LayoutXLMForTokenClassification_with_CRF
from paddlenlp.transformers import LayoutXLMModel, LayoutXLMTokenizer
def parse_args()... | null |
39,347 | import argparse
import json
import logging
import os
import random
import warnings
from collections import Counter
import numpy as np
import paddle
from docvqa import DocVQA
from model import LayoutXLMForTokenClassification_with_CRF
from paddlenlp.transformers import LayoutXLMModel, LayoutXLMTokenizer
def set_seed(arg... | null |
39,348 | import argparse
import json
import logging
import os
import random
import warnings
from collections import Counter
import numpy as np
import paddle
from docvqa import DocVQA
from model import LayoutXLMForTokenClassification_with_CRF
from paddlenlp.transformers import LayoutXLMModel, LayoutXLMTokenizer
def get_label_ma... | null |
39,349 | import argparse
import json
import logging
import os
import random
import warnings
from collections import Counter
import numpy as np
import paddle
from docvqa import DocVQA
from model import LayoutXLMForTokenClassification_with_CRF
from paddlenlp.transformers import LayoutXLMModel, LayoutXLMTokenizer
logger = logging.... | null |
39,350 | import argparse
import json
import logging
import os
import random
import warnings
from collections import Counter
import numpy as np
import paddle
from docvqa import DocVQA
from model import LayoutXLMForTokenClassification_with_CRF
from paddlenlp.transformers import LayoutXLMModel, LayoutXLMTokenizer
The provided cod... | print arguments |
39,351 | import sys
import json
import numpy as np
def get_top1_from_ranker(path):
with open(path, "r", encoding="utf-8") as f:
scores = [float(line.strip()) for line in f.readlines()]
top_id = np.argmax(scores)
return top_id | null |
39,352 | import sys
import json
import numpy as np
def get_ocr_result_by_id(path, top_id):
with open(path, "r", encoding="utf-8") as f:
reses = f.readlines()
res = reses[top_id]
return json.loads(res) | null |
39,353 | import sys
import json
import numpy as np
def write_to_file(doc, path):
with open(path, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False)
f.write("\n") | null |
39,354 | import sys
import faiss
import numpy as np
def load_qid(file_name):
qid_list = []
with open(file_name) as inp:
for line in inp:
line = line.strip()
qid = line.split("\t")[0]
qid_list.append(qid)
return qid_list | null |
39,355 | import sys
import faiss
import numpy as np
def read_embed(file_name, dim=768, bs=3000):
if file_name.endswith("npy"):
i = 0
emb_np = np.load(file_name)
while i < len(emb_np):
vec_list = emb_np[i : i + bs]
i += bs
yield vec_list
else:
vec_list =... | null |
39,356 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import multiprocessing
import os
import time
import warnings
import paddle
import paddle.fluid as fluid
import paddle.fluid.incubate.fleet.base.role_maker as role_maker
import reader_ce as reader_ce
from cross_encoder ... | null |
39,357 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import multiprocessing
import os
import time
import warnings
os.environ["FLAGS_eager_delete_tensor_gb"] = "0"
import paddle
import paddle.fluid as fluid
import paddle.fluid.incubate.fleet.base.role_maker as role_maker
... | null |
39,358 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `pad_batch_data` function. Write a Python function `def pad_batch_data( insts, pad_idx=0, return_pos=False, return_input_mask=False, return_max_len=False, return_num_token=False, return_seq_len... | Pad the instances to the max sequence length in batch, and generate the corresponding position data and attention bias. |
39,359 | import paddle.fluid as fluid
from paddle.fluid.incubate.fleet.collective import fleet
def linear_warmup_decay(learning_rate, warmup_steps, num_train_steps):
"""Applies linear warmup of learning rate from 0 and decay to 0."""
with fluid.default_main_program()._lr_schedule_guard():
lr = fluid.layers.tenso... | null |
39,360 | import json
import logging
import sys
from collections import namedtuple
from io import open
import numpy as np
import six
import tokenization
from batching import pad_batch_data
def csv_reader(fd, delimiter="\t", trainer_id=0, trainer_num=1):
def gen():
for i, line in enumerate(fd):
if i % tra... | null |
39,361 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
The provided code snippet includes necessary dependencies for implementin... | Returns text encoded in a way suitable for print or `tf.logging`. |
39,362 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's n... | Loads a vocabulary file into a dictionary. |
39,363 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
def convert_by_vocab(vocab, items):
"""Converts a sequence of [tokens|... | null |
39,364 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
def convert_by_vocab(vocab, items):
"""Converts a sequence of [tokens|... | null |
39,365 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
The provided code snippet includes necessary dependencies for implementin... | Runs basic whitespace cleaning and splitting on a piece of text. |
39,366 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
The provided code snippet includes necessary dependencies for implementin... | Checks whether `chars` is a control character. |
39,367 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
The provided code snippet includes necessary dependencies for implementin... | Checks whether `chars` is a punctuation character. |
39,368 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace ch... | Adds whitespace around any CJK character. |
39,369 | import logging
import time
import numpy as np
import paddle.fluid as fluid
from model.ernie import ErnieModel
from scipy.stats import pearsonr, spearmanr
class ErnieModel(object):
def __init__(
self,
src_ids,
position_ids,
sentence_ids,
task_ids,
input_mask,
... | null |
39,370 | from __future__ import absolute_import, division, print_function
from functools import partial
import paddle
import paddle.fluid as fluid
import paddle.fluid.layers as layers
The provided code snippet includes necessary dependencies for implementing the `pre_post_process_layer` function. Write a Python function `def p... | Add residual connection, layer normalization and dropout to the out tensor optionally according to the value of process_cmd. This will be used before or after multi-head attention and position-wise feed-forward networks. |
39,371 | from __future__ import absolute_import, division, print_function
from functools import partial
import paddle
import paddle.fluid as fluid
import paddle.fluid.layers as layers
pre_process_layer = partial(pre_post_process_layer, None)
def encoder_layer(
enc_input,
attn_bias,
n_head,
d_key,
d_value,
... | The encoder is composed of a stack of identical layers returned by calling encoder_layer. |
39,372 | import logging
import os
import paddle.fluid as fluid
log = logging.getLogger(__name__)
def init_checkpoint(exe, init_checkpoint_path, main_program):
assert os.path.exists(init_checkpoint_path), "[%s] cann't be found." % init_checkpoint_path
def existed_persitables(var):
if not fluid.io.is_persistable... | null |
39,373 | import logging
import os
import paddle.fluid as fluid
log = logging.getLogger(__name__)
def init_pretraining_params(exe, pretraining_params_path, main_program):
assert os.path.exists(pretraining_params_path), "[%s] cann't be found." % pretraining_params_path
def existed_params(var):
if not isinstance(... | null |
39,374 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import sys
import paddle.fluid as fluid
import six
from paddlenlp.trainer.argparser import strtobool
import logging
logging.getLogger().setLevel(logging.INFO)
def prepare_logger(logger, debug=False, save_to_... | null |
39,375 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import sys
import paddle.fluid as fluid
import six
from paddlenlp.trainer.argparser import strtobool
log = logging.getLogger(__name__)
def print_arguments(args):
log.info("----------- Configuration Argument... | null |
39,376 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import sys
import paddle.fluid as fluid
import six
from paddlenlp.trainer.argparser import strtobool
log = logging.getLogger(__name__)
def check_cuda(
use_cuda,
err="\nYou can not set use_cuda = True in ... | null |
39,377 | import base64
import json
from typing import List, Optional
import numpy as np
from paddlenlp.utils.ie_utils import map_offset, pad_image_data
from paddlenlp.utils.log import logger
logger = Logger()
The provided code snippet includes necessary dependencies for implementing the `reader` function. Write a Python funct... | read json |
39,378 | import base64
import json
from typing import List, Optional
import numpy as np
from paddlenlp.utils.ie_utils import map_offset, pad_image_data
from paddlenlp.utils.log import logger
def get_dynamic_max_len(examples, default_max_len: int, dynamic_max_length: List[int]) -> int:
"""get max_length by examples which you... | null |
39,379 | from dataclasses import dataclass, field
from functools import partial
from typing import Optional
import paddle
from utils import convert_example, reader
from paddlenlp.datasets import MapDataset, load_dataset
from paddlenlp.trainer import PdArgumentParser, Trainer, TrainingArguments
from paddlenlp.transformers import... | null |
39,380 | import json
import random
from typing import List, Optional
import numpy as np
import paddle
from paddlenlp.utils.log import logger
def set_seed(seed):
paddle.seed(seed)
random.seed(seed)
np.random.seed(seed) | null |
39,381 | import json
import random
from typing import List, Optional
import numpy as np
import paddle
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `create_data_loader` function. Write a Python function `def create_data_loader(dataset, mode="train", batch_... | Create dataloader. Args: dataset(obj:`paddle.io.Dataset`): Dataset instance. mode(obj:`str`, optional, defaults to obj:`train`): If mode is 'train', it will shuffle the dataset randomly. batch_size(obj:`int`, optional, defaults to 1): The sample number of a mini-batch. trans_fn(obj:`callable`, optional, defaults to `No... |
39,382 | import json
import random
from typing import List, Optional
import numpy as np
import paddle
from paddlenlp.utils.log import logger
logger = Logger()
The provided code snippet includes necessary dependencies for implementing the `reader` function. Write a Python function `def reader(data_path, max_seq_len=512)` to so... | read json |
39,383 | import json
import random
from typing import List, Optional
import numpy as np
import paddle
from paddlenlp.utils.log import logger
def map_offset(ori_offset, offset_mapping):
"""
map ori offset to token offset
"""
for index, span in enumerate(offset_mapping):
if span[0] <= ori_offset < span[1]:... | example: { title prompt content result_list } |
39,384 | import argparse
import os
import time
import paddle
from criterion import Criterion
from evaluate import evaluate
from utils import (
create_dataloader,
criteria_map,
get_label_maps,
reader,
save_model_config,
set_seed,
)
from paddlenlp.datasets import load_dataset
from paddlenlp.layers import (... | null |
39,385 | import argparse
import json
import math
import os
import random
from tqdm import tqdm
from utils import anno2distill, schema2label_maps, set_seed, synthetic2distill
from paddlenlp import Taskflow
from paddlenlp.utils.log import logger
def schema2label_maps(task_type, schema=None):
def anno2distill(json_lines, task_t... | null |
39,386 | import argparse
import paddle
from metric import get_eval
from tqdm import tqdm
from utils import create_dataloader, get_label_maps, reader, synthetic2distill
from paddlenlp import Taskflow
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import AutoTokenizer
from paddlenlp.utils.log import logge... | null |
39,387 | import argparse
import os
import paddle
from metric import get_eval
from tqdm import tqdm
from utils import create_dataloader, get_label_maps, postprocess, reader
from paddlenlp.datasets import load_dataset
from paddlenlp.layers import (
GlobalPointerForEntityExtraction,
GPLinkerForRelationExtraction,
)
from pa... | null |
39,388 | import argparse
from functools import partial
import paddle
from utils import convert_example, create_data_loader, reader
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import MapDataset, load_dataset
from paddlenlp.metrics import SpanEvaluator
from paddlenlp.transformers import UIE, UIEM, A... | null |
39,389 | import argparse
import json
import os
import random
import time
from decimal import Decimal
import numpy as np
import paddle
from paddlenlp.trainer.argparser import strtobool
from paddlenlp.utils.log import logger
from paddlenlp.utils.tools import DataConverter
def set_seed(seed):
paddle.seed(seed)
random.seed(... | null |
39,390 | import argparse
import json
import random
import re
import numpy as np
import paddle
def load_json_file(path):
exmaples = []
with open(path, "r", encoding="utf-8") as f:
for line in f.readlines():
example = json.loads(line)
exmaples.append(example)
return exmaples | null |
39,391 | import argparse
import json
import random
import re
import numpy as np
import paddle
def write_json_file(examples, save_path):
with open(save_path, "w", encoding="utf-8") as f:
for example in examples:
line = json.dumps(example, ensure_ascii=False)
f.write(line + "\n") | null |
39,392 | import argparse
import json
import random
import re
import numpy as np
import paddle
The provided code snippet includes necessary dependencies for implementing the `str2bool` function. Write a Python function `def str2bool(v)` to solve the following problem:
Support bool type for argparse.
Here is the function:
def ... | Support bool type for argparse. |
39,393 | import argparse
import json
import random
import re
import numpy as np
import paddle
The provided code snippet includes necessary dependencies for implementing the `create_data_loader` function. Write a Python function `def create_data_loader(dataset, mode="train", batch_size=1, trans_fn=None)` to solve the following ... | Create dataloader. Args: dataset(obj:`paddle.io.Dataset`): Dataset instance. mode(obj:`str`, optional, defaults to obj:`train`): If mode is 'train', it will shuffle the dataset randomly. batch_size(obj:`int`, optional, defaults to 1): The sample number of a mini-batch. trans_fn(obj:`callable`, optional, defaults to `No... |
39,394 | import argparse
import json
import random
import re
import numpy as np
import paddle
def map_offset(ori_offset, offset_mapping):
"""
map ori offset to token offset
"""
for index, span in enumerate(offset_mapping):
if span[0] <= ori_offset < span[1]:
return index
return -1
The pr... | example: { title prompt content result_list } |
39,395 | import argparse
import json
import random
import re
import numpy as np
import paddle
The provided code snippet includes necessary dependencies for implementing the `reader` function. Write a Python function `def reader(data_path, max_seq_len=512)` to solve the following problem:
read json
Here is the function:
def r... | read json |
39,396 | import argparse
import json
import random
import re
import numpy as np
import paddle
def unify_prompt_name(prompt):
# The classification labels are shuffled during finetuning, so they need
# to be unified during evaluation.
if re.search(r"\[.*?\]$", prompt):
prompt_prefix = prompt[: prompt.find("[",... | null |
39,397 | import argparse
import os
import time
from functools import partial
import paddle
from evaluate import evaluate
from utils import convert_example, create_data_loader, reader, set_seed
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import SpanEvaluator
from paddlenlp.transformers import UIE, AutoToke... | null |
39,398 | import argparse
import os
import random
import shutil
from collections import defaultdict
from operator import itemgetter
import matplotlib.pyplot as plt
import wordcloud
from utils import load_json_file
from paddlenlp.taskflow.utils import download_file
from paddlenlp.utils.log import logger
PROMPT_ITEMS = {
"aspe... | null |
39,399 | import argparse
import copy
import json
import os
import random
import time
from decimal import Decimal
import numpy as np
import paddle
from utils import load_txt
from paddlenlp.trainer.argparser import strtobool
from paddlenlp.utils.log import logger
def set_seed(seed):
paddle.seed(seed)
random.seed(seed)
... | null |
39,400 | import argparse
import re
from functools import partial
import paddle
from tqdm import tqdm
from utils import (
convert_example,
create_data_loader,
get_relation_type_dict,
reader,
unify_prompt_name,
)
from paddlenlp.datasets import MapDataset, load_dataset
from paddlenlp.metrics import SpanEvaluato... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.