id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
38,293 | import argparse
import os
import sys
from pprint import pprint
import numpy as np
import paddle
import yaml
from easydict import EasyDict as AttrDict
from paddlenlp.ops import FasterTransformer
from paddlenlp.utils.log import logger
import reader
def post_process_seq(seq, bos_idx, eos_idx, output_bos=False, output_eos... | null |
38,294 | import argparse
import os
import sys
import time
from pprint import pprint
import numpy as np
import paddle
import paddle.distributed as dist
import paddle.distributed.fleet as fleet
import yaml
from easydict import EasyDict as AttrDict
from paddlenlp.transformers import CrossEntropyCriterion, TransformerModel
from pad... | null |
38,295 | import argparse
import os
import sys
import time
from pprint import pprint
import numpy as np
import paddle
import paddle.distributed as dist
import paddle.distributed.fleet as fleet
import yaml
from easydict import EasyDict as AttrDict
from paddlenlp.transformers import CrossEntropyCriterion, TransformerModel
from pad... | null |
38,296 | import argparse
import os
import sys
from pprint import pprint
import numpy as np
import paddle
import yaml
from easydict import EasyDict as AttrDict
from paddlenlp.transformers import InferTransformerModel
import reader
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--confi... | null |
38,297 | import argparse
import os
import sys
from pprint import pprint
import numpy as np
import paddle
import yaml
from easydict import EasyDict as AttrDict
from paddlenlp.transformers import InferTransformerModel
import reader
def cast_parameters_to_fp32(place, program, scope=None):
all_parameters = []
for block in ... | null |
38,298 | import paddle
import paddle.distributed as dist
The provided code snippet includes necessary dependencies for implementing the `all_gather_tokens` function. Write a Python function `def all_gather_tokens(data)` to solve the following problem:
Gathers num of tokens from all nodes. `data` should be a tensor of num of to... | Gathers num of tokens from all nodes. `data` should be a tensor of num of tokens. |
38,299 | import argparse
import random
from functools import partial
import numpy as np
import paddle
from model import (
BiLSTMAttentionModel,
BoWModel,
CNNModel,
GRUModel,
LSTMModel,
RNNModel,
SelfInteractiveAttention,
)
from utils import build_vocab, convert_example
from paddlenlp.data import Jieb... | sets random seed |
38,300 | import argparse
import random
from functools import partial
import numpy as np
import paddle
from model import (
BiLSTMAttentionModel,
BoWModel,
CNNModel,
GRUModel,
LSTMModel,
RNNModel,
SelfInteractiveAttention,
)
from utils import build_vocab, convert_example
from paddlenlp.data import Jieb... | 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... |
38,301 | from collections import defaultdict
import numpy as np
from paddlenlp import Taskflow
The provided code snippet includes necessary dependencies for implementing the `preprocess_prediction_data` function. Write a Python function `def preprocess_prediction_data(data, tokenizer)` to solve the following problem:
It proces... | It process the prediction data as the format used as training. Args: data (obj:`List[str]`): The prediction data whose each element is a tokenized text. tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string. Returns: examples (obj:`List(Example)`): The processed data whose each element i... |
38,302 | from collections import defaultdict
import numpy as np
from paddlenlp import Taskflow
word_segmenter = Taskflow("word_segmentation", mode="fast")
The provided code snippet includes necessary dependencies for implementing the `build_vocab` function. Write a Python function `def build_vocab(texts, stopwords=[], num_word... | According to the texts, it is to build vocabulary. Args: texts (obj:`List[str]`): The raw corpus data. num_words (obj:`int`): the maximum size of vocabulary. stopwords (obj:`List[str]`): The list where each element is a word that will be filtered from the texts. min_freq (obj:`int`): the minimum word frequency of words... |
38,303 | import argparse
import numpy as np
import paddle
from scipy.special import softmax
from paddlenlp.data import JiebaTokenizer, Pad, Stack, Tuple, Vocab
The provided code snippet includes necessary dependencies for implementing the `preprocess_prediction_data` function. Write a Python function `def preprocess_prediction... | It process the prediction data as the format used as training. Args: text (obj:`str`): The input text. tokenizer(obj: `paddlenlp.data.JiebaTokenizer`): It use jieba to cut the chinese string. Returns: input_ids (obj: `list[int]`): The word ids of the `text`. seq_len (obj: `int`): The length of words. |
38,304 | import argparse
import paddle
import paddle.nn.functional as F
from model import (
BiLSTMAttentionModel,
BoWModel,
CNNModel,
GRUModel,
LSTMModel,
RNNModel,
SelfInteractiveAttention,
)
from utils import preprocess_prediction_data
from paddlenlp.data import JiebaTokenizer, Pad, Stack, Tuple, V... | 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). label_map(obj:`dict`): The label id (key) to label str (... |
38,305 | import argparse
import os
import random
import time
from collections import defaultdict
from functools import partial
import numpy as np
import paddle
import paddle.nn as nn
from data import (
ClassifierIterator,
HYPTextPreprocessor,
ImdbTextPreprocessor,
to_json_file,
)
from metrics import F1
from mode... | null |
38,306 | import itertools
import json
from collections import namedtuple
import numpy as np
from paddle.utils import try_import
from paddlenlp.transformers import tokenize_chinese_chars
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `get_related_pos` functi... | generate relative postion ids |
38,307 | import itertools
import json
from collections import namedtuple
import numpy as np
from paddle.utils import try_import
from paddlenlp.transformers import tokenize_chinese_chars
from paddlenlp.utils.log import logger
The provided code snippet includes necessary dependencies for implementing the `pad_batch_data` functio... | Pad the instances to the max sequence length in batch, and generate the corresponding position data and attention bias. |
38,308 | import argparse
import os
from functools import partial
import numpy as np
import paddle
import paddle.nn as nn
from data import (
ClassifierIterator,
HYPTextPreprocessor,
ImdbTextPreprocessor,
to_json_file,
)
from modeling import ErnieDocForSequenceClassification
from train import init_memory
from padd... | null |
38,309 | import argparse
import os
from functools import partial
import numpy as np
import paddle
import paddle.nn as nn
from data import (
ClassifierIterator,
HYPTextPreprocessor,
ImdbTextPreprocessor,
to_json_file,
)
from modeling import ErnieDocForSequenceClassification
from train import init_memory
from padd... | null |
38,310 | import collections
import sys
import numpy as np
import paddle
from paddle.utils import try_import
from paddlenlp.metrics.dureader import (
_compute_softmax,
_get_best_indexes,
get_final_text,
)
def get_final_text(pred_text, orig_text, tokenizer, verbose):
"""Project the tokenized prediction back to th... | Write final predictions to the json file and log-odds of null if needed. |
38,311 | import argparse
import os
import time
import paddle
from paddlenlp.data import Pad, Stack, Tuple
def convert_tokens_to_ids(tokens, vocab, oov_replace_token=None, normlize_vocab=None):
"""Convert tokens to token indexs"""
token_ids = []
oov_replace_token = vocab.get(oov_replace_token) if oov_replace_token el... | Convert tokens of sequences to token ids |
38,312 | import argparse
import os
import time
import paddle
from paddlenlp.data import Pad, Stack, Tuple
The provided code snippet includes necessary dependencies for implementing the `load_vocab` function. Write a Python function `def load_vocab(dict_path)` to solve the following problem:
Load vocab from file
Here is the fu... | Load vocab from file |
38,313 | import argparse
import os
import time
import paddle
from paddlenlp.data import Pad, Stack, Tuple
The provided code snippet includes necessary dependencies for implementing the `parse_result` function. Write a Python function `def parse_result(words, preds, lengths, word_vocab, label_vocab)` to solve the following prob... | Parse padding result |
38,314 | import argparse
import os
from functools import partial
import paddle
from data import convert_example, load_dataset, load_vocab, parse_result
from model import BiGruCrf
from paddlenlp.data import Pad, Stack, Tuple
def convert_example(example, label_list, tokenizer=None, is_test=False, max_seq_length=512, **kwargs):
... | null |
38,315 | import argparse
import os
from functools import partial
import paddle
from data import convert_example, load_dataset, load_vocab
from model import BiGruCrf
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.metrics import ChunkEvaluator
def convert_example(example, label_list, tokenizer=None, is_test=False, m... | null |
38,316 | import os
import time
import argparse
from pprint import pprint
import numpy as np
import yaml
from attrdict import AttrDict
import paddle
import paddle.distributed as dist
from paddlenlp.utils.log import logger
import reader
from model import SimultaneousTransformer, CrossEntropyCriterion
from utils.record import Aver... | null |
38,317 | import os
import time
import argparse
from pprint import pprint
import numpy as np
import yaml
from attrdict import AttrDict
import paddle
import paddle.distributed as dist
from paddlenlp.utils.log import logger
import reader
from model import SimultaneousTransformer, CrossEntropyCriterion
from utils.record import Aver... | null |
38,318 | import os
import argparse
from pprint import pprint
import yaml
from attrdict import AttrDict
import paddle
from paddlenlp.transformers import position_encoding_init
import reader
from model import SimultaneousTransformer
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--config", defa... | null |
38,319 | import os
import argparse
from pprint import pprint
import yaml
from attrdict import AttrDict
import paddle
from paddlenlp.transformers import position_encoding_init
import reader
from model import SimultaneousTransformer
def post_process_seq(seq, bos_idx, eos_idx, output_bos=False, output_eos=False):
"""
Post-... | null |
38,320 | import argparse
import json
import os
import threading
import time
import uuid
from tkinter import END, LEFT, Button, E, Entry, Label, PhotoImage, Tk, W
import _locale
import jieba
import paddle
import websocket
import yaml
from attrdict import AttrDict
from subword_nmt import subword_nmt
from paddlenlp.data import Voc... | null |
38,321 | import argparse
import json
import os
import threading
import time
import uuid
from tkinter import END, LEFT, Button, E, Entry, Label, PhotoImage, Tk, W
import _locale
import jieba
import paddle
import websocket
import yaml
from attrdict import AttrDict
from subword_nmt import subword_nmt
from paddlenlp.data import Voc... | GUI and main waitk program :param args: :param tokenizer: :param transformers: :param waitks: :return: |
38,322 | import argparse
import json
import os
import threading
import time
import uuid
from tkinter import END, LEFT, Button, E, Entry, Label, PhotoImage, Tk, W
import _locale
import jieba
import paddle
import websocket
import yaml
from attrdict import AttrDict
from subword_nmt import subword_nmt
from paddlenlp.data import Voc... | null |
38,323 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from model import ErnieForCSC
from utils import convert_example, create_dataloader, read_train_ds
from paddlenlp.data import Pad, Stack, Tuple, Vocab
from paddlenlp.datasets import MapDataset, load_dataset... | null |
38,324 | import argparse
from functools import partial
import paddle
from model import ErnieForCSC
from utils import convert_example, create_dataloader, parse_decode, read_test_ds
from paddlenlp.data import Pad, Stack, Tuple, Vocab
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import ErnieModel, ErnieT... | null |
38,325 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
import paddle.nn.functional as F
from data import convert_example, create_dataloader, read_custom_data
from metric import NPTagAccuracy
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import ... | null |
38,326 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
import paddle.nn.functional as F
from data import convert_example, create_dataloader, read_custom_data
from metric import NPTagAccuracy
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import ... | null |
38,327 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
import paddle.nn.functional as F
from data import convert_example, create_dataloader, read_custom_data
from metric import NPTagAccuracy
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import ... | print arguments |
38,328 | import json
from collections import OrderedDict
from typing import List
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `levenstein_distance` function. Write a Python function `def levenstein_distance(s1: str, s2: str) -> int` to solve the following problem:
Calculate ... | Calculate minimal Levenstein distance between s1 and s2. Args: s1 (str): string s2 (str): string Returns: int: the minimal distance. |
38,329 | import argparse
import os
import paddle
from data import convert_example
from utils import construct_dict_map, decode, find_topk, search
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.transformers import ErnieCtmNptagModel, ErnieCtmTokenizer
args = parser.parse_args()
def convert_example(example, label_li... | null |
38,330 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from data_process import convert_example, create_dataloader, load_dict, read_custom_data
from metric import SequenceAccuracy
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load... | null |
38,331 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from data_process import convert_example, create_dataloader, load_dict, read_custom_data
from metric import SequenceAccuracy
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load... | null |
38,332 | import argparse
import os
import random
import time
from functools import partial
import numpy as np
import paddle
from data_process import convert_example, create_dataloader, load_dict, read_custom_data
from metric import SequenceAccuracy
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.datasets import load... | print arguments |
38,333 | def reset_offset(pred_words):
for i in range(0, len(pred_words)):
if i > 0:
pred_words[i]["offset"] = pred_words[i - 1]["offset"] + len(pred_words[i - 1]["item"])
pred_words[i]["length"] = len(pred_words[i]["item"])
return pred_words
def decode(texts, all_pred_tags, summary_num, idx... | null |
38,334 | import argparse
import os
import paddle
from data_process import convert_example, load_dict
from utils import decode
from paddlenlp.data import Pad, Stack, Tuple
from paddlenlp.transformers import ErnieCtmTokenizer, ErnieCtmWordtagModel
args = parser.parse_args()
def convert_example(example, tokenizer, max_seq_len, ta... | null |
38,335 | from typing import List, Tuple
import paddle
The provided code snippet includes necessary dependencies for implementing the `wordseg_hard_acc` function. Write a Python function `def wordseg_hard_acc(list_a: List[Tuple[str, str]], list_b: List[Tuple[str, str]]) -> float` to solve the following problem:
Calculate extra ... | Calculate extra metrics of word-seg Args: list_a: prediction list list_b: real list Returns: acc: the extra accuracy |
38,336 | from typing import List, Tuple
import paddle
The provided code snippet includes necessary dependencies for implementing the `wordtag_hard_acc` function. Write a Python function `def wordtag_hard_acc(list_a: List[Tuple[str, str]], list_b: List[Tuple[str, str]]) -> float` to solve the following problem:
Calculate extra ... | Calculate extra metrics of word-tag Args: list_a: prediction list list_b: real list Returns: acc: the extra accuracy |
38,337 | from typing import List, Tuple
import paddle
The provided code snippet includes necessary dependencies for implementing the `wordtag_soft_acc` function. Write a Python function `def wordtag_soft_acc(list_a: List[Tuple[str, str]], list_b: List[Tuple[str, str]]) -> float` to solve the following problem:
Calculate extra ... | Calculate extra metrics of word-tag Args: list_a: prediction list list_b: real list Returns: acc: the extra accuracy |
38,338 | from typing import List, Tuple
import paddle
The provided code snippet includes necessary dependencies for implementing the `wordseg_soft_acc` function. Write a Python function `def wordseg_soft_acc(list_a: List[Tuple[str, str]], list_b: List[Tuple[str, str]]) -> float` to solve the following problem:
Calculate extra ... | Calculate extra metrics of word-seg Args: list_a: prediction list list_b: real list Returns: acc: the extra accuracy |
38,339 | import argparse
import paddle
from paddlenlp import Taskflow
def parse_args():
parser = argparse.ArgumentParser()
# fmt: off
parser.add_argument("--max_seq_len", default=128, type=int, help="The maximum total input sequence length after tokenization. Sequences longer than this will be truncated, sequences... | null |
38,340 | import argparse
import paddle
from paddlenlp import Taskflow
def do_predict(args):
paddle.set_device(args.device)
wordtag = Taskflow(
"knowledge_mining", model="wordtag", batch_size=args.batch_size, max_seq_length=args.max_seq_len, linking=True
)
txts = ["《孤女》是2010年九州出版社出版的小说,作者是余兼羽。", "热梅茶是一道以... | null |
38,341 | import argparse
import paddle
from paddlenlp import Taskflow
The provided code snippet includes necessary dependencies for implementing the `print_arguments` function. Write a Python function `def print_arguments(args)` to solve the following problem:
print arguments
Here is the function:
def print_arguments(args):
... | print arguments |
38,342 | import argparse
import paddle
from decode import beam_search_infilling, post_process
from encode import after_padding, convert_example
from paddle.io import DataLoader
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import (
BertTokenizer,
ElectraTok... | null |
38,346 | import re
from collections import namedtuple
import numpy as np
import paddle
import paddle.nn as nn
def gen_bias(encoder_inputs, decoder_inputs, step):
BeamSearchState = namedtuple("BeamSearchState", ["log_probs", "lengths", "finished"])
def beam_search_step(state, logits, eos_id, beam_width, is_first_step, length_pen... | null |
38,347 | import re
from collections import namedtuple
import numpy as np
import paddle
import paddle.nn as nn
en_patten = re.compile(r"^[a-zA-Z0-9]*$")
def post_process(token):
if token.startswith("##"):
ret = token[2:]
elif token in ["[CLS]", "[SEP]", "[PAD]"]:
ret = ""
else:
if en_patten.m... | null |
38,348 | from copy import deepcopy
import numpy as np
def convert_example(
tokenizer,
attn_id,
tgt_type_id=3,
max_encode_len=512,
max_decode_len=128,
is_test=False,
noise_prob=0.0,
use_random_noice=False,
):
def warpper(example):
"""convert an example into necessary features"""
... | null |
38,349 | from copy import deepcopy
import numpy as np
def gen_mask(batch_ids, mask_type="bidi", query_len=None, pad_value=0):
if query_len is None:
query_len = batch_ids.shape[1]
if mask_type != "empty":
mask = (batch_ids != pad_value).astype(np.float32)
mask = np.tile(np.expand_dims(mask, 1), [1... | attention mask: *** src, tgt, attn src 00, 01, 11 tgt 10, 11, 12 attn 20, 21, 22 *** s1, s2 | t1 t2 t3| attn1 attn2 attn3 s1 1, 1 | 0, 0, 0,| 0, 0, 0, s2 1, 1 | 0, 0, 0,| 0, 0, 0, - t1 1, 1, | 1, 0, 0,| 0, 0, 0, t2 1, 1, | 1, 1, 0,| 0, 0, 0, t3 1, 1, | 1, 1, 1,| 0, 0, 0, - attn1 1, 1, | 0, 0, 0,| 1, 0, 0, attn2 1, 1, |... |
38,350 | import paddle
from args import parse_args
from data import create_data_loader
from model import (
CrossEntropyWithKL,
NegativeLogLoss,
Perplexity,
TrainCallback,
VAESeq2SeqModel,
)
def create_data_loader(args):
class CrossEntropyWithKL(nn.Layer):
def __init__(self, base_kl_weight, anneal_r):
... | null |
38,351 | import argparse
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", type=str, help="Dataset name. Now ptb|yahoo is supported.")
parser.add_argument("--learning_rate", type=float, default=0.001, help="Learning rate of optimizer.")
parser.add_argume... | null |
38,352 | import io
import numpy as np
import paddle
from args import parse_args
from data import create_data_loader
from model import VAESeq2SeqInferModel
def create_data_loader(args):
batch_size = args.batch_size
max_len = args.max_len
if args.dataset == "yahoo":
train_ds, dev_ds, test_ds = load_dataset("y... | null |
38,353 | import argparse
import os
import time
import paddle
import paddle.distributed as dist
import paddle.nn.functional as F
from gen_utils import create_data_loader, print_args, select_sum, set_seed
from paddle.optimizer import AdamW
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import BLEU
from paddlen... | null |
38,354 | import argparse
import os
import time
import paddle
import paddle.distributed as dist
import paddle.nn.functional as F
from gen_utils import create_data_loader, print_args, select_sum, set_seed
from paddle.optimizer import AdamW
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import BLEU
from paddlen... | null |
38,355 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import DataLoader, DistributedBatchSampler, BatchSampler
from paddlenlp.data import Pad
def print_args(args):
print("----------- Configuration Arguments -----------")
for arg, value in... | null |
38,356 | import paddle
from paddlenlp.transformers import ReformerModelWithLMHead
def encode(list_of_strings, pad_token_id=0):
max_length = max([len(string) for string in list_of_strings])
# create emtpy tensors
attention_masks = paddle.zeros((len(list_of_strings), max_length), dtype="int64")
input_ids = paddl... | null |
38,357 | import paddle
from paddlenlp.transformers import ReformerModelWithLMHead
def decode(outputs_ids):
decoded_outputs = []
for output_ids in outputs_ids.tolist():
# transform id back to char IDs < 2 are simply transformed to ""
decoded_outputs.append("".join([chr(x - 2) if x > 1 else "" for x in ou... | null |
38,358 | import paddle
from args import parse_args
from data import create_train_loader
from model import CrossEntropyCriterion, Seq2SeqAttnModel
from paddlenlp.metrics import Perplexity
def create_train_loader(args):
batch_size = args.batch_size
max_len = args.max_len
train_ds, dev_ds = load_dataset("iwslt15", sp... | null |
38,359 | import argparse
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--learning_rate", type=float, default=0.001, help="learning rate for optimizer")
parser.add_argument("--num_layers", type=int, default=1, help="layers number of encoder and decoder")
parser.a... | null |
38,360 | from functools import partial
import numpy as np
import paddle
from paddlenlp.data import Pad, SamplerHelper, Vocab
from paddlenlp.datasets import load_dataset
def convert_example(example, vocab):
bos_id = vocab[vocab.bos_token]
eos_id = vocab[vocab.eos_token]
source = [bos_id] + vocab.to_indices(example["f... | null |
38,361 | from functools import partial
import numpy as np
import paddle
from paddlenlp.data import Pad, SamplerHelper, Vocab
from paddlenlp.datasets import load_dataset
def convert_example(example, vocab):
bos_id = vocab[vocab.bos_token]
eos_id = vocab[vocab.eos_token]
source = [bos_id] + vocab.to_indices(example["f... | null |
38,362 | import io
import numpy as np
import paddle
from args import parse_args
from data import create_infer_loader
from model import Seq2SeqAttnInferModel
def post_process_seq(seq, bos_idx, eos_idx, output_bos=False, output_eos=False):
"""
Post-process the decoded sequence.
"""
eos_pos = len(seq) - 1
for i... | null |
38,363 | import argparse
import os
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from tqdm import tqdm
from utils import compute_metrics, convert_example
from paddlenlp.data import Pad, Tu... | null |
38,364 | import argparse
import os
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from tqdm import tqdm
from utils import compute_metrics, convert_example
from paddlenlp.data import Pad, Tu... | null |
38,365 | import evaluate
import nltk
import numpy as np
from paddlenlp.metrics import BLEU
The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example( example, tokenizer, decoder_start_token_id, max_source_length, m... | Convert an example into necessary features. |
38,366 | import evaluate
import nltk
import numpy as np
from paddlenlp.metrics import BLEU
def compute_metrics(preds, labels, tokenizer, ignore_pad_token_for_loss=True):
def compute_bleu(predictions, references, rouge_types=None, use_stemmer=True):
bleu1 = BLEU(n_size=1)
bleu2 = BLEU(n_size=2)
bleu3... | null |
38,367 | import argparse
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from utils import compute_metrics, convert_example
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from padd... | null |
38,368 | import argparse
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from utils import compute_metrics, convert_example
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import load_dataset
from padd... | null |
38,369 | import argparse
import json
import os
import time
import paddle
import paddle.distributed as dist
import paddle.nn.functional as F
from gen_utils import create_data_loader, print_args, select_sum, set_seed
from paddle.optimizer import AdamW
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import BLEU
... | null |
38,370 | import argparse
import json
import os
import time
import paddle
import paddle.distributed as dist
import paddle.nn.functional as F
from gen_utils import create_data_loader, print_args, select_sum, set_seed
from paddle.optimizer import AdamW
from paddlenlp.datasets import load_dataset
from paddlenlp.metrics import BLEU
... | null |
38,371 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from paddlenlp.data import Pad
def print_args(args):
print("----------- Configuration Arguments -----------")
for arg, value in... | null |
38,372 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from paddlenlp.data import Pad
def set_seed(seed):
# Use the same data seed(for data shuffle) for all procs to guarantee data
# ... | null |
38,373 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from paddlenlp.data import Pad
def convert_example(
example, tokenizer, max_seq_len=512, max_target_len=128, max_title_len=256, mode=... | null |
38,374 | import argparse
import os
import time
from pprint import pprint
import numpy as np
import paddle
from infer_utils import create_data_loader, postprocess_response, select_sum
from paddle import inference
from paddlenlp.datasets import load_dataset
from paddlenlp.ops.ext_utils import load
from paddlenlp.transformers impo... | Setup arguments. |
38,375 | import argparse
import os
import time
from pprint import pprint
import numpy as np
import paddle
from infer_utils import create_data_loader, postprocess_response, select_sum
from paddle import inference
from paddlenlp.datasets import load_dataset
from paddlenlp.ops.ext_utils import load
from paddlenlp.transformers impo... | Setup inference predictor. |
38,376 | import argparse
import os
import time
from pprint import pprint
import numpy as np
import paddle
from infer_utils import create_data_loader, postprocess_response, select_sum
from paddle import inference
from paddlenlp.datasets import load_dataset
from paddlenlp.ops.ext_utils import load
from paddlenlp.transformers impo... | Use predictor to inference. |
38,377 | import argparse
import os
import time
from pprint import pprint
import numpy as np
import paddle
from infer_utils import create_data_loader, postprocess_response, select_sum
from paddle import inference
from paddlenlp.datasets import load_dataset
from paddlenlp.ops.ext_utils import load
from paddlenlp.transformers impo... | null |
38,378 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from paddlenlp.data import Pad
The provided code snippet includes necessary dependencies for implementing the `postprocess_response` fun... | Post-process the decoded sequence. Truncate from the first <eos>. |
38,382 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler
from paddlenlp.data import Pad
def post_process_sum(token_ids, tokenizer):
"""Post-process the decoded sequence. Truncate from the fi... | null |
38,383 | import argparse
import os
from pprint import pprint
import paddle
from paddlenlp.ops import FasterUNIMOText
from paddlenlp.transformers import UNIMOLMHeadModel, UNIMOTokenizer
from paddlenlp.utils.log import logger
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model_name_or_path",... | null |
38,384 | import argparse
import os
from pprint import pprint
import paddle
from paddlenlp.ops import FasterUNIMOText
from paddlenlp.transformers import UNIMOLMHeadModel, UNIMOTokenizer
from paddlenlp.utils.log import logger
logger = Logger()
def do_predict(args):
place = "gpu"
place = paddle.set_device(place)
mod... | null |
38,385 | import argparse
import json
import time
import paddle
import paddle.distributed as dist
from gen_utils import create_data_loader, print_args, select_sum, set_seed
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import UNIMOLMHeadModel, UNIMOTokenizer
def parse_args():
parser = argparse.Argu... | null |
38,386 | import argparse
import json
import time
import paddle
import paddle.distributed as dist
from gen_utils import create_data_loader, print_args, select_sum, set_seed
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import UNIMOLMHeadModel, UNIMOTokenizer
def read_file(file):
with open(file, "r",... | null |
38,388 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import DataLoader, DistributedBatchSampler, BatchSampler
from paddlenlp.data import Pad
def set_seed(seed):
# Use the same data seed(for data shuffle) for all procs to guarantee data
# ... | null |
38,389 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import DataLoader, DistributedBatchSampler, BatchSampler
from paddlenlp.data import Pad
def convert_example(
example, tokenizer, max_seq_len=512, max_target_len=128, max_title_len=256, mode=... | null |
38,390 | import random
from functools import partial
import numpy as np
import paddle
import paddle.distributed as dist
from paddle.io import DataLoader, DistributedBatchSampler, BatchSampler
from paddlenlp.data import Pad
def post_process_sum(token_ids, tokenizer):
"""Post-process the decoded sequence. Truncate from the fi... | null |
38,391 | import numpy as np
import nltk
from rouge_score import rouge_scorer, scoring
The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example( example, text_column, summary_column, tokenizer, decoder_start_token_... | Convert a example into necessary features. |
38,392 | import numpy as np
import nltk
from rouge_score import rouge_scorer, scoring
def compute_metrics(preds, labels, tokenizer, ignore_pad_token_for_loss=True):
def compute_rouge(predictions, references, rouge_types=None, use_stemmer=True):
if rouge_types is None:
rouge_types = ["rouge1", "rouge2", ... | null |
38,393 | import os
import argparse
import random
import time
import distutils.util
from pprint import pprint
from functools import partial
from tqdm import tqdm
import numpy as np
import paddle
import paddle.nn as nn
from paddle.io import BatchSampler, DistributedBatchSampler, DataLoader
from paddlenlp.transformers import BartF... | null |
38,394 | import os
import argparse
import random
import time
import distutils.util
from pprint import pprint
from functools import partial
from tqdm import tqdm
import numpy as np
import paddle
import paddle.nn as nn
from paddle.io import BatchSampler, DistributedBatchSampler, DataLoader
from paddlenlp.transformers import BartF... | null |
38,395 | import argparse
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from utils import compute_metrics, convert_example
from paddlenlp.data import Stack, Tuple
from paddlenlp.datasets import load_dataset
from pa... | null |
38,396 | import argparse
import random
import time
from functools import partial
from pprint import pprint
import numpy as np
import paddle
from paddle.io import BatchSampler, DataLoader
from utils import compute_metrics, convert_example
from paddlenlp.data import Stack, Tuple
from paddlenlp.datasets import load_dataset
from pa... | null |
38,397 | import argparse
import os
import shutil
import string
import tempfile
import time
from bs_pyrouge import Rouge155
_tok_dict = {"(": "-LRB-", ")": "-RRB-", "[": "-LSB-", "]": "-RSB-", "{": "-LCB-", "}": "-RCB-"}
def _is_digit(w):
for ch in w:
if not (ch.isdigit() or ch == ","):
return False
r... | null |
38,398 | import argparse
import os
import shutil
import string
import tempfile
import time
from bs_pyrouge import Rouge155
def remove_duplicate(l_list, duplicate_rate):
tk_list = [l.lower().split() for l in l_list]
r_list = []
history_set = set()
for i, w_list in enumerate(tk_list):
w_set = set(w_list)
... | null |
38,399 | import argparse
import os
import shutil
import string
import tempfile
import time
from bs_pyrouge import Rouge155
print(rouge_results_to_str(scores))
class Rouge155(object):
"""
This is a wrapper for the ROUGE 1.5.5 summary evaluation package.
This class is designed to simplify the evaluation process by:
... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.