id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
39,738
import logging import numbers import numpy as np from paddlenlp.datasets import MapDataset from pipelines.utils.common_utils import flatten_list logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `convert_features_to_dataset` function. Write a Python fun...
Converts a list of feature dictionaries (one for each sample) into a Paddle Dataset. :param features: A list of dictionaries. Each dictionary corresponds to one sample. Its keys are the names of the type of feature and the keys are the features themselves. :Return: a Paddle dataset and a list of tensor names.
39,739
import time import logging import subprocess import requests from pathlib import Path logger = logging.getLogger(__name__) ELASTICSEARCH_CONTAINER_NAME = "elasticsearch" def launch_es(sleep=15, delete_existing=False): # Start an Elasticsearch server via Docker logger.debug("Starting Elasticsearch ...") if...
null
39,740
import time import logging import subprocess import requests from pathlib import Path logger = logging.getLogger(__name__) OPENSEARCH_CONTAINER_NAME = "opensearch" def launch_opensearch(sleep=15, delete_existing=False): # Start an OpenSearch server via docker logger.debug("Starting OpenSearch...") # This ...
null
39,741
import time import logging import subprocess import requests from pathlib import Path logger = logging.getLogger(__name__) def launch_weaviate(sleep=15): # Start a Weaviate server via Docker logger.debug("Starting Weaviate ...") status = subprocess.run( [ "docker run -d -p 8080:8080 --...
null
39,742
import time import logging import subprocess import requests from pathlib import Path logger = logging.getLogger(__name__) def stop_opensearch(delete_container=False): stop_container(OPENSEARCH_CONTAINER_NAME, delete_container) def stop_elasticsearch(delete_container=False): stop_container(ELASTICSEARCH_CONTAIN...
null
39,743
import time import logging import subprocess import requests from pathlib import Path logger = logging.getLogger(__name__) def launch_milvus(sleep=15, delete_existing=False): # Start a Milvus server via docker logger.debug("Starting Milvus ...") milvus_dir = Path.home() / "milvus" milvus_dir.mkdir(ex...
null
39,744
import time import logging import subprocess import requests from pathlib import Path logger = logging.getLogger(__name__) MILVUS1_CONTAINER_NAME = "milvus1" def launch_milvus1(sleep=15): # Start a Milvus (version <2.0.0) server via docker logger.debug("Starting Milvus ...") logger.warning( "Autom...
null
39,745
from typing import Optional import io import tarfile import zipfile import requests import logging import importlib from pathlib import Path def _missing_dependency_stub_factory(classname: str, dep_group: str, import_error: Exception): """ Create custom versions of MissingDependency using the given parameters. ...
Method that allows the import of nodes that depend on missing dependencies. These nodes can be installed one by one with extras_require (see setup.cfg) but they need to be all imported in their respective package's __init__() Therefore, in case of an ImportError, the class to import is replaced by a hollow MissingDepen...
39,746
from typing import Optional import io import tarfile import zipfile import requests import logging import importlib from pathlib import Path logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `fetch_archive_from_http` function. Write a Python function `d...
Fetch an archive (zip or tar.gz) from a url via http and extract content to an output directory. :param url: http address :param output_dir: local path :param proxies: proxies details as required by requests library :return: if anything got fetched
39,747
import re The provided code snippet includes necessary dependencies for implementing the `clean_wiki_text` function. Write a Python function `def clean_wiki_text(text: str) -> str` to solve the following problem: Clean wikipedia text by removing multiple new lines, removing extremely short lines, adding paragraph brea...
Clean wikipedia text by removing multiple new lines, removing extremely short lines, adding paragraph breaks and removing empty paragraphs
39,748
import logging import os import random from copy import deepcopy from typing import List, Tuple import numpy as np import paddle import paddle paddle.framework.io.EagerParamBase.to = to The provided code snippet includes necessary dependencies for implementing the `set_all_seeds` function. Write a Python function `...
Setting multiple seeds to make runs reproducible. Important: Enabling `deterministic_cudnn` gives you full reproducibility with CUDA, :param seed:number to use as seed :param deterministic_paddle: Enable for full reproducibility when using CUDA. Caution: might slow down training.
39,749
import logging import os import random from copy import deepcopy from typing import List, Tuple import numpy as np import paddle logger = logging.getLogger(__name__) import paddle paddle.framework.io.EagerParamBase.to = to The provided code snippet includes necessary dependencies for implementing the `initialize_de...
Returns a list of available devices. :param use_cuda: Whether to make use of CUDA GPUs (if available). :param local_rank: Ordinal of device to be used. If -1 and multi_gpu is True, all devices will be used. :param multi_gpu: Whether to make use of all GPUs (if available).
39,750
import logging import os import random from copy import deepcopy from typing import List, Tuple import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `flatten_list` function. Write a Python function `def flatten_list(nested_list)` to solve the following problem...
Flatten an arbitrarily nested list, without recursion (to avoid stack overflows). Returns a new list, the original list is unchanged. >> list(flatten_list([1, 2, 3, [4], [], [[[[[[[[[5]]]]]]]]]])) [1, 2, 3, 4, 5] >> list(flatten_list([[1, 2], 3])) [1, 2, 3]
39,751
import logging import os import random from copy import deepcopy from typing import List, Tuple import numpy as np import paddle logger = logging.getLogger(__name__) def try_get(keys, dictionary): try: for key in keys: if key in dictionary: ret = dictionary[key] ...
null
39,752
import functools import logging import multiprocessing import os import re from pathlib import Path from typing import Callable, Dict, List, Optional from pipelines.nodes.base import BaseComponent from pipelines.nodes.file_converter import ( BaseConverter, DocxToTextConverter, ImageToTextConverter, Mark...
Convert all files(.txt, .pdf, .docx) in the sub-directories of the given path to Python dicts that can be written to a Document Store. :param dir_path: path for the documents to be written to the DocumentStore :param clean_func: a custom cleaning function that gets applied to each doc (input: str, output:str) :param sp...
39,753
import functools import logging import multiprocessing import os import re from pathlib import Path from typing import Callable, Dict, List, Optional from pipelines.nodes.base import BaseComponent from pipelines.nodes.file_converter import ( BaseConverter, DocxToTextConverter, ImageToTextConverter, Mark...
Convert all files(.txt, .pdf, .docx) in the sub-directories of the given path to Python dicts that can be written to a Document Store. :param dir_path: path for the documents to be written to the DocumentStore :param clean_func: a custom cleaning function that gets applied to each doc (input: str, output:str) :param sp...
39,754
import functools import logging import multiprocessing import os import re from pathlib import Path from typing import Callable, Dict, List, Optional from pipelines.nodes.base import BaseComponent from pipelines.nodes.file_converter import ( BaseConverter, DocxToTextConverter, ImageToTextConverter, Mark...
Convert all files(.txt, .pdf) in the sub-directories of the given path to Python dicts that can be written to a Document Store. :param merge_lowercase: allow conversion of merged paragraph to lowercase :param merge_short: allow merging of short paragraphs :param dir_path: path for the documents to be written to the Doc...
39,755
import json import logging import pprint from collections import defaultdict from typing import Optional import pandas as pd from pipelines.document_stores.sql import DocumentORM from pipelines.schema import Answer, Document import logging logging.getLogger().setLevel(logging.INFO) The provided code snippet includ...
Utility function to print results of pipelines pipelines :param results: Results from a pipeline :param details: One of "minimum", "medium", "all". Defining the level of details to print. :param max_text_lenght: shorten lengthy text fields to the maximum allowed length. Set to None to not cut long text. :return: None
39,756
import json import logging import pprint from collections import defaultdict from typing import Optional import pandas as pd from pipelines.document_stores.sql import DocumentORM from pipelines.schema import Answer, Document The provided code snippet includes necessary dependencies for implementing the `print_document...
Utility that prints a compressed representation of the documents returned by a pipeline. :param max_text_lenght: shorten the document's content to a maximum number of chars. if None, does not cut. :param print_name: whether to print the document's name (from the metadata) or not. :param print_meta: whether to print the...
39,757
import json import logging import pprint from collections import defaultdict from typing import Optional import pandas as pd from pipelines.document_stores.sql import DocumentORM from pipelines.schema import Answer, Document The provided code snippet includes necessary dependencies for implementing the `print_question...
Utility to print the output of a question generating pipeline in a readable format.
39,758
import json import logging import pprint from collections import defaultdict from typing import Optional import pandas as pd from pipelines.document_stores.sql import DocumentORM from pipelines.schema import Answer, Document The provided code snippet includes necessary dependencies for implementing the `export_answers...
Exports answers coming from finder.get_answers() to a CSV file :param agg_results: list of predictions coming from finder.get_answers() :param output_file: filename of output file :return: None
39,759
import json import logging import pprint from collections import defaultdict from typing import Optional import pandas as pd from pipelines.document_stores.sql import DocumentORM from pipelines.schema import Answer, Document The provided code snippet includes necessary dependencies for implementing the `convert_labels...
Convert the export from the labeling UI to SQuAD format for training. :param labels_file: path for export file from the labeling tool :return:
39,760
from __future__ import absolute_import, division, print_function, unicode_literals import logging import numpy as np from paddlenlp.transformers.tokenizer_utils_base import TruncationStrategy from pipelines.data_handler.samples import SampleBasket class TruncationStrategy(ExplicitEnum): """ Possible values for...
Tokenizes text data for question answering tasks. Tokenization means splitting words into subwords, depending on the tokenizer's vocabulary. - We first tokenize all documents in batch mode. (When using FastTokenizer Rust multithreading can be enabled by TODO add how to enable rust mt) - Then we tokenize each question i...
39,761
from __future__ import absolute_import, division, print_function, unicode_literals import logging import numpy as np from paddlenlp.transformers.tokenizer_utils_base import TruncationStrategy from pipelines.data_handler.samples import SampleBasket def _get_start_of_word_QA(word_ids): words = np.array(word_ids) ...
null
39,762
import argparse import os from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import MultiModalRetriever from pipelines.schema import Document from pipelines.utils import convert_files_to_dicts, fetch_archive_from_http, launch_es args = parser.parse_args() def off...
null
39,763
import argparse import os from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import MultiModalRetriever from pipelines.schema import Document from pipelines.utils import convert_files_to_dicts, fetch_archive_from_http, launch_es args = parser.parse_args() def del...
null
39,764
import argparse from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, MilvusDocumentStore, ) from pipelines.nodes import DensePassageRetriever from pipelines.utils import convert_files_to_dicts, fetch_archive_from_http, launch_es from pipelines.utils.preprocess...
null
39,765
import argparse from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, MilvusDocumentStore, ) from pipelines.nodes import DensePassageRetriever from pipelines.utils import convert_files_to_dicts, fetch_archive_from_http, launch_es from pipelines.utils.preprocess...
null
39,766
import json import os import sys from functools import partial import paddle from argument import ( DataArgument, GenerateArgument, ModelArgument, QuantArgument, TrainingArguments, ) from data import get_convert_example from utils import ( CausalLMTrainer, InTokensIterDatasetCallback, co...
null
39,767
import importlib import os import paddle from paddlenlp.transformers import AutoConfig from paddlenlp.transformers.auto.modeling import MAPPING_NAMES from paddlenlp.utils.log import logger def parse_arguments(): import argparse parser = argparse.ArgumentParser() parser.add_argument("--model_name_or_path",...
null
39,768
import importlib import os import paddle from paddlenlp.transformers import AutoConfig from paddlenlp.transformers.auto.modeling import MAPPING_NAMES from paddlenlp.utils.log import logger def load_tp_params(tp_degree, path): tp_state_dict_list = [] for tp in range(tp_degree): tp_state_dict = {} ...
null
39,769
import importlib import os import paddle from paddlenlp.transformers import AutoConfig from paddlenlp.transformers.auto.modeling import MAPPING_NAMES from paddlenlp.utils.log import logger def load_tp_and_pp_params(tp_degree, pp_degree, path): tp_state_dict_list = [] for tp in range(tp_degree): tp_stat...
null
39,770
import importlib import os import paddle from paddlenlp.transformers import AutoConfig from paddlenlp.transformers.auto.modeling import MAPPING_NAMES from paddlenlp.utils.log import logger def load_pp_params(pp_degree, path): pp_state_dict = {} for pp in range(pp_degree): tmp = paddle.load(os.path.join...
null
39,771
import importlib import os import paddle from paddlenlp.transformers import AutoConfig from paddlenlp.transformers.auto.modeling import MAPPING_NAMES from paddlenlp.utils.log import logger logger = Logger() The provided code snippet includes necessary dependencies for implementing the `merge_tensor_parallel` function...
the entry of converting config and converting model file Args: input_dir (str | None): the input dir which contains `pytorch_model.bin` and `config.json` file config (PretrainedConfig): the PretrainedConfig instance of model
39,772
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,773
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,774
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,775
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,776
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,777
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,778
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
Pre-process generation inputs.
39,779
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,780
from __future__ import annotations import glob import math import os import struct from typing import Dict, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.incubate.multiprocessing as mp from paddle.distributed import fleet from paddle.io import BatchSampler, DataLoader, Distri...
null
39,785
import argparse import copy import os import paddle from paddlenlp.peft import LoRAConfig, LoRAModel try: from paddle.nn.quant import weight_dequantize, weight_quantize except: weight_dequantize = None weight_quantize = None from paddlenlp.quantization.quantization_config import QuantizationConfig from padd...
null
39,786
from __future__ import annotations import os from dataclasses import dataclass, field import paddle from paddle.distributed import fleet from predictor import ModelArgument, PredictorArgument, create_predictor from tqdm import tqdm from utils import generate_rank_mapping, get_infer_model_path from paddlenlp.trainer imp...
null
39,787
from __future__ import annotations import json import os import socket from contextlib import closing from dataclasses import asdict, dataclass, field from time import sleep import requests from filelock import FileLock from predictor import BasePredictor, ModelArgument, PredictorArgument, create_predictor from paddlen...
null
39,788
from __future__ import annotations import numpy as np from paddlenlp.peft import LoRAModel, PrefixModelForCausalLM def convert_example_common(example, tokenizer, data_args, is_test=True, intokens=False): if tokenizer.chat_template is not None: return convert_rounds_example_common(example, tokenizer, data_ar...
null
39,805
import contextlib import os import random import sys import time import types from dataclasses import dataclass, field from typing import List, Optional import numpy as np import paddle import paddle.distributed as dist import paddle.distributed.auto_parallel as auto from paddle.base.data_feeder import convert_uint16_t...
null
39,823
import os import random import sys import types from collections import OrderedDict from dataclasses import dataclass, field from typing import List, Optional import numpy as np import paddle import paddle.distributed as dist from paddle.autograd import PyLayer from paddle.distributed import fleet from paddle.io import...
null
39,826
import re def regitser_extract_layer_name_func(func): global _GLOBAL_EXTRACT_LAYER_NAME_FUNC _GLOBAL_EXTRACT_LAYER_NAME_FUNC = func def register_index_layer_func(func): global _GLOBAL_INDEX_LAYER_FUNC _GLOBAL_INDEX_LAYER_FUNC = func def register_layername_prefix(layer_name): LayerNameSc...
null
39,830
import json import os import paddle from paddle import nn from paddle.distributed.fleet.meta_parallel import ( ColumnParallelLinear, RowParallelLinear, ) from paddle.quantization import PTQ, QAT, QuantConfig from paddleslim.quant.advanced import ( GPTQ, AutoClip, AWQSearch, EMASampler, Multi...
null
39,831
import json import os import paddle from paddle import nn from paddle.distributed.fleet.meta_parallel import ( ColumnParallelLinear, RowParallelLinear, ) from paddle.quantization import PTQ, QAT, QuantConfig from paddleslim.quant.advanced import ( GPTQ, AutoClip, AWQSearch, EMASampler, Multi...
null
39,832
import json import os import paddle from paddle import nn from paddle.distributed.fleet.meta_parallel import ( ColumnParallelLinear, RowParallelLinear, ) from paddle.quantization import PTQ, QAT, QuantConfig from paddleslim.quant.advanced import ( GPTQ, AutoClip, AWQSearch, EMASampler, Multi...
null
39,833
import json import os import paddle from paddle import nn from paddle.distributed.fleet.meta_parallel import ( ColumnParallelLinear, RowParallelLinear, ) from paddle.quantization import PTQ, QAT, QuantConfig from paddleslim.quant.advanced import ( GPTQ, AutoClip, AWQSearch, EMASampler, Multi...
AutoClip
39,834
import json import os import paddle from paddle import nn from paddle.distributed.fleet.meta_parallel import ( ColumnParallelLinear, RowParallelLinear, ) from paddle.quantization import PTQ, QAT, QuantConfig from paddleslim.quant.advanced import ( GPTQ, AutoClip, AWQSearch, EMASampler, Multi...
null
39,835
import json import os import paddle from paddle import nn from paddle.distributed.fleet.meta_parallel import ( ColumnParallelLinear, RowParallelLinear, ) from paddle.quantization import PTQ, QAT, QuantConfig from paddleslim.quant.advanced import ( GPTQ, AutoClip, AWQSearch, EMASampler, Multi...
null
39,836
import json import os import paddle from paddle import nn from paddle.distributed.fleet.meta_parallel import ( ColumnParallelLinear, RowParallelLinear, ) from paddle.quantization import PTQ, QAT, QuantConfig from paddleslim.quant.advanced import ( GPTQ, AutoClip, AWQSearch, EMASampler, Multi...
null
39,837
import json import requests def send_request(query, history=None): data = { "context": query, "history": history, "top_k": 0, "top_p": 0.7, # 0.0 为 greedy_search "temperature": 0.95, "repetition_penalty": 1.3, "max_length": 100, "src_length": 100, ...
null
39,838
from __future__ import annotations import json import os import sys import time from abc import abstractmethod from dataclasses import dataclass, field from threading import Thread from typing import List, Optional import numpy as np import paddle import paddle.distributed.fleet.base.topology as tp import paddle.incuba...
get eos_token_id from generation_config or tokenizer Returns: int | List[int]: eos_token_id to stop the generation
39,839
from __future__ import annotations import argparse import copy import json import gradio as gr import requests The provided code snippet includes necessary dependencies for implementing the `setup_args` function. Write a Python function `def setup_args()` to solve the following problem: Setup arguments. Here is the f...
Setup arguments.
39,840
from __future__ import annotations import argparse import copy import json import gradio as gr import requests def create_src_slider(value, maximum): return gr.Slider( minimum=1, maximum=maximum, value=value, step=1, label="Max Src Length", info="最大输入长度。", ) def c...
Launch characters dialogue demo.
39,844
import copy import random import re from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.distributed as dist import paddle.nn as nn from paddle.distributed import fleet from paddle.distributed.fleet.meta_parallel import get_rng_state_tracker from paddle.optimizer.lr ...
Convert an example into necessary features.
39,845
import copy import random import re from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.distributed as dist import paddle.nn as nn from paddle.distributed import fleet from paddle.distributed.fleet.meta_parallel import get_rng_state_tracker from paddle.optimizer.lr ...
null
39,846
from __future__ import annotations import paddle from utils import get_hcg, init_dist_env, set_seed from paddlenlp.transformers import ( GPTChineseTokenizer, GPTConfig, GPTForCausalLM, GPTTokenizer, ) def parse_arguments(): import argparse parser = argparse.ArgumentParser() parser.add_argume...
null
39,850
import os from setuptools import Distribution, setup from setuptools.command.install import install if os.name != "nt": package_data = {"fast_tokenizer": ["core_tokenizers.so", "commit.log"]} package_data["fast_tokenizer.libs"] = [] else: package_data = {"fast_tokenizer": ["core_tokenizers.pyd", "core_token...
null
39,851
from typing import Dict, List, Tuple, Union from . import core_tokenizers as C The provided code snippet includes necessary dependencies for implementing the `set_thread_num` function. Write a Python function `def set_thread_num(thread_num)` to solve the following problem: Set the number of threads for accelerating ba...
Set the number of threads for accelerating batch tokenization :param thread_num: (int) The number of threads :return None
39,852
from typing import Dict, List, Tuple, Union from . import core_tokenizers as C The provided code snippet includes necessary dependencies for implementing the `get_thread_num` function. Write a Python function `def get_thread_num()` to solve the following problem: Get the number of tokenization threads :return int Her...
Get the number of tokenization threads :return int
39,853
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import paddle class MaxLengthCriteria(StoppingCriteria): """ This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. Keep in mind for decoder-only type o...
null
39,854
from __future__ import annotations import copy import inspect from typing import Optional, Union import paddle import paddle.distributed as dist import paddle.nn as nn import paddle.nn.functional as F from paddle import Tensor from paddle.common_ops_import import convert_dtype from paddle.utils import map_structure fro...
get unfinished flag for generation step Args: input_ids (Tensor): the input_ids eos_token_id (Union[int, list[int], list[list[int]]]): the end os sentence flag, which can be: * single token id, eg: 10 * multiple token ids to stop generation, eg: [10, 10] * some more tokens to stop generations, eg: [[10], [20, 20], [30,...
39,855
from __future__ import annotations import inspect from abc import ABC from collections import OrderedDict from typing import Callable, Dict, List, Tuple, Union import numpy as np import paddle from paddle.nn.layer.layers import in_declarative_mode def _get_ngrams(ngram_size: int, prev_input_ids: paddle.Tensor, num_hypo...
Copied from fairseq for no_repeat_ngram in beam_search
39,856
from __future__ import annotations import inspect from abc import ABC from collections import OrderedDict from typing import Callable, Dict, List, Tuple, Union import numpy as np import paddle from paddle.nn.layer.layers import in_declarative_mode def TopKProcess(probs: paddle.Tensor, top_k: int, min_tokens_to_keep: i...
null
39,857
from __future__ import annotations import inspect from abc import ABC from collections import OrderedDict from typing import Callable, Dict, List, Tuple, Union import numpy as np import paddle from paddle.nn.layer.layers import in_declarative_mode def TopPProcess(probs: paddle.Tensor, top_p: float, min_tokens_to_keep:...
null
39,858
import copy import json import os import warnings from typing import Any, Dict, Optional, Union from huggingface_hub import hf_hub_download from paddle.common_ops_import import convert_dtype from paddlenlp import __version__ from paddlenlp.transformers.configuration_utils import PretrainedConfig from paddlenlp.utils.do...
resolve config file from hf hub Args: repo_id (str): the repo name from huggingface hub cache_dir (str): the cachedir subfolder (str, optional) An optional value corresponding to a folder inside the repo. Returns: str: the downloaded config file
39,859
import inspect from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import paddle from paddle import Tensor from ..transformers.model_outputs import MaskedLMOutput, SequenceClassifierOutput from ..transformers.tokenizer_utils_base import PaddingStrategy, Pretra...
Obtain the input arguments of the given function.
39,860
import inspect from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import paddle from paddle import Tensor from ..transformers.model_outputs import MaskedLMOutput, SequenceClassifierOutput from ..transformers.tokenizer_utils_base import PaddingStrategy, Pretra...
null
39,861
import inspect from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import paddle from paddle import Tensor from ..transformers.model_outputs import MaskedLMOutput, SequenceClassifierOutput from ..transformers.tokenizer_utils_base import PaddingStrategy, Pretra...
null
39,862
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
Download the file from the url to specified directory. Check md5 value when the file is exists, if the md5 value is the same as the existed file, just use the older file, if not, will download the file from the url. Args: save_dir(string): The specified directory saving the file. filename(string): The specified filenam...
39,863
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
Check the resource status in the specified task. Args: task(string): The name of specified task.
39,864
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
The function that add the doc string to doc of class.
39,865
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,866
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,867
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
Cut the Chinese sentences more precisely, reference to "https://blog.csdn.net/blmoistawinde/article/details/82379256".
39,868
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
Calculate minimal Levenstein distance between s1 and s2. Args: s1 (str): string s2 (str): string Returns: int: the minimal distance.
39,869
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
Return text id and probability of predicted spans Args: span_set (set): set of predicted spans. offset_mapping (list[int]): list of pair preserving the index of start and end char in original text pair (prompt + text) for each token. Returns: sentence_id (list[tuple]): index of start and end char in original text. prob...
39,870
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,871
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,872
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,873
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
Pad the instances to the max sequence length in batch, and generate the corresponding position data and attention bias.
39,874
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,875
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,876
import contextlib import copy import csv import json import math import os import pickle import re import traceback import warnings from collections import OrderedDict, namedtuple from dataclasses import dataclass from datetime import datetime from functools import cmp_to_key from typing import Any, Dict, List, Optiona...
null
39,877
import copy import os import numpy as np import paddle from ..data import Pad, Vocab from .models import BiAffineParser from .task import Task from .utils import download_file def pad_sequence(sequences, padding_value=0, fix_len=None): def convert_example(example, vocabs, fix_len=20): word_vocab, rel_vocab = vocab...
null
39,878
import copy import os import numpy as np import paddle from ..data import Pad, Vocab from .models import BiAffineParser from .task import Task from .utils import download_file def flat_words(words, pad_index=0): mask = words != pad_index lens = np.sum(mask.astype(np.int64), axis=-1) position = np.cumsum(le...
null
39,879
import copy import os import numpy as np import paddle from ..data import Pad, Vocab from .models import BiAffineParser from .task import Task from .utils import download_file def probability(s_arc, arc_preds): s_arc = s_arc - s_arc.max(axis=-1).reshape(list(s_arc.shape)[:-1] + [1]) s_arc = np.exp(s_arc) / np....
null
39,880
import copy import os import numpy as np import paddle from ..data import Pad, Vocab from .models import BiAffineParser from .task import Task from .utils import download_file def eisner(scores, mask): """ Eisner algorithm is a general dynamic programming decoding algorithm for bilexical grammar. Args: ...
decode
39,881
import os import paddle from ..data import Pad, Stack, Tuple from ..datasets import load_dataset from .models import BiGruCrf from .task import Task from .utils import Customization The provided code snippet includes necessary dependencies for implementing the `load_vocab` function. Write a Python function `def load_v...
Load vocab from file
39,882
from typing import Optional import numpy as np import paddle from paddlenlp.data import DataCollatorWithPadding from paddlenlp.transformers import AutoModel, AutoTokenizer, ErnieDualEncoder from ..utils.log import logger from .task import Task from .utils import dygraph_mode_guard, static_mode_guard def text_length(te...
null
39,883
import json import os from typing import Any, Dict, List, Union import numpy as np import paddle import paddle.nn.functional as F from scipy.special import expit as np_sigmoid from scipy.special import softmax as np_softmax from ..data import DataCollatorWithPadding from ..prompt import ( AutoTemplate, PromptDa...
null
39,884
import base64 import json import os import re from typing import List import numpy as np import paddle from huggingface_hub import hf_hub_download from ..datasets import load_dataset from ..layers import GlobalPointerForEntityExtraction, GPLinkerForRelationExtraction from ..transformers import UIE, UIEM, UIEX, AutoMode...
get max_length by examples which you can change it by examples in batch
39,885
import paddle import paddle.nn as nn from paddlenlp.transformers import AutoModel The provided code snippet includes necessary dependencies for implementing the `index_sample` function. Write a Python function `def index_sample(x, index)` to solve the following problem: Select input value according to index Arags: inp...
Select input value according to index Arags: input: input matrix index: index matrix Returns: output >>> input [ [1, 2, 3], [4, 5, 6] ] >>> index [ [1, 2], [0, 1] ] >>> index_sample(input, index) [ [2, 3], [4, 5] ]