id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
39,886
import paddle import paddle.nn as nn from ..utils.log import logger from .sequence import sequence_mask def log_sum_exp(vec, dim=0): # Avoid underflow and overflow max_num = paddle.max(vec, dim) max_exp = max_num.unsqueeze(-1) return max_num + paddle.log(paddle.sum(paddle.exp(vec - max_exp), dim))
null
39,887
The provided code snippet includes necessary dependencies for implementing the `sequence_mask` function. Write a Python function `def sequence_mask(seq_ids, valid_lengths)` to solve the following problem: To boost the performance, this sequence_mask is different with paddle.nn.functional.sequence_mask Args: seq_ids (...
To boost the performance, this sequence_mask is different with paddle.nn.functional.sequence_mask Args: seq_ids (Tensor): The whole sequence index, a tensor with a shape of [batch_size, sequence_length]. valid_lengths (Tensor): The valid length of every sequence, a tensor with a shape of [batch_size]. Returns: Tensor: ...
39,888
from collections import defaultdict import numpy as np import paddle from paddlenlp.utils.log import logger from seqeval.metrics.sequence_labeling import get_entities def extract_tp_actual_correct(y_true, y_pred, suffix, *args): entities_true = defaultdict(set) entities_pred = defaultdict(set) for type_nam...
null
39,889
import numpy as np def default_trans_func(output, label, seq_mask, vocab): seq_mask = np.expand_dims(seq_mask, axis=2).repeat(output.shape[2], axis=2) output = output * seq_mask idx = np.argmax(output, axis=2) cand, ref_list = [], [] for i in range(idx.shape[0]): token_list = [] for...
null
39,890
import math import sys from collections import defaultdict import paddle from .utils import default_trans_func def get_match_size(cand_ngram, refs_ngram): ref_set = defaultdict(int) for ref_ngram in refs_ngram: tmp_ref_set = defaultdict(int) for ngram in ref_ngram: tmp_ref_set[tuple...
null
39,891
import math import sys from collections import defaultdict import paddle from .utils import default_trans_func def get_ngram(sent, n_size, label=None): def _ngram(sent, n_size): ngram_list = [] for left in range(len(sent) - n_size): ngram_list.append(sent[left : left + n_size + 1]) ...
null
39,892
import collections import json import math from paddlenlp.metrics.bleu import BLEU from paddlenlp.metrics.rouge import RougeL def get_final_text(pred_text, orig_text, tokenizer, verbose): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment...
Write final predictions to the json file and log-odds of null if needed.
39,893
import collections import json import math from paddlenlp.metrics.bleu import BLEU from paddlenlp.metrics.rouge import RougeL def normalize(s): """ Normalize strings to space joined chars. Args: s: a list of strings. Returns: A list of normalized strings. """ if not s: re...
null
39,894
import importlib import json import numbers import os import tempfile from pathlib import Path from ..peft import LoRAModel, PrefixModelForCausalLM from ..transformers import PretrainedModel from ..utils.log import logger from .trainer_callback import TrainerCallback def is_ray_available(): return importlib.util.f...
null
39,895
import importlib import json import numbers import os import tempfile from pathlib import Path from ..peft import LoRAModel, PrefixModelForCausalLM from ..transformers import PretrainedModel from ..utils.log import logger from .trainer_callback import TrainerCallback def is_visualdl_available(): return importlib.ut...
null
39,896
import importlib import json import numbers import os import tempfile from pathlib import Path from ..peft import LoRAModel, PrefixModelForCausalLM from ..transformers import PretrainedModel from ..utils.log import logger from .trainer_callback import TrainerCallback def rewrite_logs(d): new_d = {} eval_prefix...
null
39,897
import importlib import json import numbers import os import tempfile from pathlib import Path from ..peft import LoRAModel, PrefixModelForCausalLM from ..transformers import PretrainedModel from ..utils.log import logger from .trainer_callback import TrainerCallback INTEGRATION_TO_CALLBACK = { "visualdl": VisualDL...
null
39,898
import copy import inspect import json import math import os import time import paddle import paddle.nn as nn import paddle.nn.functional as F from paddle.metric import Accuracy from paddle.utils import try_import from ..data import Pad from ..metrics import ChunkEvaluator from ..metrics.squad import compute_prediction...
Supports pruning DynaBERT and post-training quantization. If both are needed, pruning DynaBERT would be performed before quantizaton.
39,899
import copy import inspect import json import math import os import time import paddle import paddle.nn as nn import paddle.nn.functional as F from paddle.metric import Accuracy from paddle.utils import try_import from ..data import Pad from ..metrics import ChunkEvaluator from ..metrics.squad import compute_prediction...
null
39,900
import contextlib import json import math import os import types import warnings from dataclasses import asdict, dataclass, field from enum import Enum from typing import Any, Dict, List, Optional import paddle import paddle.distributed as dist from paddle.distributed import fleet from ..utils.log import logger from .t...
Same default
39,901
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
null
39,902
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
null
39,903
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Whether or not the current process is the local process, based on `xm.get_ordinal()` (for TPUs) first, then on `local_rank`.
39,904
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Return the number of processes launched in parallel. Works with `paddle.distributed` and TPUs.
39,905
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be measured has completed. Args: - split: name to prefix metric (like train, eval, test...) - start_time: operat...
39,906
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Create a schedule with a constant learning rate, using the learning rate set in optimizer. Args: learning_rate (float) The initial learning rate. It is a python float number. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `paddle.optimizer.lr.LambdaDecay` wit...
39,907
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between 0 and the initial lr set in the optimizer. Args: learning_rate (float) The initial learning rate. It is a python float number. num_warmup_steps (`int`): The number of steps for the warmu...
39,908
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: learning_rate (float) The initial learning rate. It is a python float number. num_warmup_steps (`int...
39,909
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: learning_rate (float) The initial learning rate. It is a p...
39,910
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: learning_rate (`float`): The base learning rate. It is a pytho...
39,911
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Unified API to get any scheduler from its name. Args: name (`str` or `SchedulerType`): The name of the scheduler to use. learning_rate (float) The initial learning rate. It is a python float number. num_warmup_steps (`int`, *optional*): The number of warmup steps to do. This is not required by all schedulers (hence the...
39,912
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Checks if the dataset implements __len__() and it doesn't raise an error
39,913
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
Find the first dimension of a tensor in a nested list/tuple/dict of tensors.
39,914
import datetime import gc import inspect import json import math import os import random import re import threading import time from contextlib import contextmanager from enum import Enum from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import paddle from paddle.distributed import fl...
null
39,915
import copy import gc import json import multiprocessing import os import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from tqdm.auto import tqdm from paddlenlp.peft import LoRAModel, PrefixModelForCausalLM from paddlenlp.trainer.trainer_utils import ExplicitEnum from...
save unified checkpoint Args: args (TrainingArguments): Training Arguments model (PretrainedModel): model to save output_dir (str): save dir safe_serialization (bool, optional): use safetensors. Defaults to False. Raises: ValueError: if model is not an instance of `PretrainedModel` and the model cannot be saved
39,916
import copy import gc import json import multiprocessing import os import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from tqdm.auto import tqdm from paddlenlp.peft import LoRAModel, PrefixModelForCausalLM from paddlenlp.trainer.trainer_utils import ExplicitEnum from...
Load potential model checkpoint Args: model (PretrainedModel): Your model to load resume_from_checkpoint (str): path of the checkpoint to load Returns: None
39,917
import copy import gc import json import multiprocessing import os import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from tqdm.auto import tqdm from paddlenlp.peft import LoRAModel, PrefixModelForCausalLM from paddlenlp.trainer.trainer_utils import ExplicitEnum from...
save unified optimizer Args: args (TrainingArguments): Training Arguments optimizer (Optimizer): optimizer to save output_dir (str): Save directory. safe_serialization (bool, optional): Whether to use safetensors. Defaults to False.
39,918
import copy import gc import json import multiprocessing import os import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from tqdm.auto import tqdm from paddlenlp.peft import LoRAModel, PrefixModelForCausalLM from paddlenlp.trainer.trainer_utils import ExplicitEnum from...
Load potential model checkpoint Args: model (PretrainedModel): Your model to load resume_from_checkpoint (str): path of the checkpoint to load Returns: None
39,919
import time import paddle from paddlenlp.utils.log import logger _GLOBAL_TIMERS = None def get_timers(): global _GLOBAL_TIMERS return _GLOBAL_TIMERS
null
39,920
import time import paddle from paddlenlp.utils.log import logger class Timers: """Group of timers.""" def __init__(self): self.timers = {} def __call__(self, name): if name not in self.timers: self.timers[name] = _Timer(name) return self.timers[name] def write(self, n...
null
39,921
import time import paddle from paddlenlp.utils.log import logger _GLOBAL_TIMERS = None logger = Logger() def disable_timers(): global _GLOBAL_TIMERS logger.info("disable PaddleNLP timer") _GLOBAL_TIMERS = None
null
39,922
import types import numpy as np import paddle from paddle.common_ops_import import LayerHelper from ...utils.log import logger def _optimizer_step_with_flatten_param_grads(optimizer): if not isinstance(optimizer._param_groups[0], dict): params_grads = [] for param in optimizer._param_groups: ...
npu_accelerate_plugin uses the flatten_param_grads method to speed up the performance of the model on NPU devices. flatten_param_grads method will be added to `step` function of optimizer. Args: optimizer (`paddle.optimizer.Optimizer`): The Optimizer whose `step` method will be modified.
39,923
import copy import json import os from collections import OrderedDict import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer import ( DygraphShardingOptimizer, ) from paddlenlp.transformers.model_utils import ( _add_va...
null
39,924
import copy import json import os from collections import OrderedDict import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer import ( DygraphShardingOptimizer, ) try: from paddle.distributed.fleet.meta_optimizers.dygra...
null
39,925
def add_start_docstrings(*docstr): def docstring_decorator(fn): fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "") return fn return docstring_decorator
null
39,926
def add_start_docstrings_to_model_forward(*docstr): def docstring_decorator(fn): docstring = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "") class_name = f"[`{fn.__qualname__.split('.')[0]}`]" intro = f" The {class_name} forward method, overrides the `__call__` special m...
null
39,927
def add_end_docstrings(*docstr): def docstring_decorator(fn): fn.__doc__ = (fn.__doc__ if fn.__doc__ is not None else "") + "".join(docstr) return fn return docstring_decorator
null
39,928
from collections import OrderedDict from paddle.distributed.fleet.model import PipelineParallel from paddle.distributed.fleet.utils.log_util import logger _GLOBAL_INDEX_LAYER_FUNC = None def get_index_layer_func(): global _GLOBAL_INDEX_LAYER_FUNC assert _GLOBAL_INDEX_LAYER_FUNC is not None, "index layer func i...
null
39,929
from collections import OrderedDict from paddle.distributed.fleet.model import PipelineParallel from paddle.distributed.fleet.utils.log_util import logger def extract_param_names_groupby_layer( meta, mp_rank=0, ): param_names_by_layer = OrderedDict() assert "parallel_config" in meta parallel_config ...
null
39,930
from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer.dygraph_sharding_optimizer import ( DygraphShardingOptimizer, ) from ....transformers.model_utils import unwrap_optimizer def shard(node_model_state, model, optimizer, hcg): group = hcg.get_sharding_parallel_group() cur_rank = group.rank o...
null
39,931
from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer.dygraph_sharding_optimizer import ( DygraphShardingOptimizer, ) from ....transformers.model_utils import unwrap_optimizer def restore(node_model_state, model, optimizer, hcg): node_model_state.drop_rank() return node_model_state
null
39,932
import numpy as np import paddle from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer import ( HybridParallelOptimizer, ) from paddle.distributed.fleet.model import PipelineParallel from ....transformers.model_utils import unwrap_optimizer def pad_tensor(k, tensor, padded_size): def slice_tensor(tensor, ...
null
39,933
import numpy as np import paddle from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer import ( HybridParallelOptimizer, ) from paddle.distributed.fleet.model import PipelineParallel from ....transformers.model_utils import unwrap_optimizer def merge_tensors(k, tensor_list, shape): assert len(tensor_l...
null
39,934
from collections import OrderedDict import numpy as np import paddle from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer.dygraph_sharding_optimizer import ( DygraphShardingOptimizer, ) from paddle.distributed.fleet.utils.log_util import logger from ....transformers.model_utils import unwrap_optimizer d...
null
39,935
from collections import OrderedDict import numpy as np import paddle from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer.dygraph_sharding_optimizer import ( DygraphShardingOptimizer, ) from paddle.distributed.fleet.utils.log_util import logger from ....transformers.model_utils import unwrap_optimizer SH...
null
39,936
from collections import OrderedDict import numpy as np import paddle from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer.dygraph_sharding_optimizer import ( DygraphShardingOptimizer, ) from paddle.distributed.fleet.utils.log_util import logger from ....transformers.model_utils import unwrap_optimizer de...
null
39,937
import collections import copy import os from typing import Any, Optional import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddlenlp.utils.log import logger import paddle paddle.framework.io.EagerParamBase.to = to def distributed_concat(tensor: Any, num_to...
null
39,938
import collections import copy import os from typing import Any, Optional import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddlenlp.utils.log import logger def paddle_pad_and_concatenate(tensor1, tensor2, padding_index=-100): """Concatenates `tensor1` and...
Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or nested list/tuples of tensors.
39,939
import collections import copy import os from typing import Any, Optional import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `nested_detach` functio...
Detach `tensors` (even if it's a nested list/tuple of tensors).
39,940
import collections import copy import os from typing import Any, Optional import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddlenlp.utils.log import logger import paddle paddle.framework.io.EagerParamBase.to = to The provided code snippet includes necessa...
Numpify `tensors` (even if it's a nested list/tuple of tensors).
39,941
import collections import copy import os from typing import Any, Optional import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `nested_truncate` funct...
Truncate `tensors` at `limit` (even if it's a nested list/tuple of tensors).
39,942
import collections import copy import os from typing import Any, Optional import numpy as np import paddle import paddle.distributed as dist from paddle.distributed import fleet from paddlenlp.utils.log import logger def nested_reduce_tensor(tensor): if isinstance(tensor, dict): # copy tensor since it will ...
null
39,943
import hashlib import math import os import time import numpy as np import paddle from paddlenlp.data.blendable_dataset import BlendableDataset from paddlenlp.data.indexed_dataset import make_dataset as make_indexed_dataset local_rank = int(os.getenv("PADDLE_RANK_IN_NODE", 0)) def print_rank_0(*args, **kwargs): if ...
Build doc-idx, sample-idx, and shuffle-idx. doc-idx: is an array (ordered) of documents to be used in training. sample-idx: is the start document index and document offset for each training sample. shuffle-idx: maps the sample index into a random index into sample-idx.
39,944
import hashlib import math import os import time import numpy as np import paddle from paddlenlp.data.blendable_dataset import BlendableDataset from paddlenlp.data.indexed_dataset import make_dataset as make_indexed_dataset The provided code snippet includes necessary dependencies for implementing the `_build_sample_i...
Sample index mapping is a 2D array with sizes [number-of-samples + 1, 2] where [..., 0] contains the index into `doc_idx` and [..., 1] is the starting offset in that document.
39,945
import jieba def get_idx_from_word(word, word_to_idx, unk_word): if word in word_to_idx: return word_to_idx[word] return word_to_idx[unk_word]
null
39,946
import numpy as np import paddle from paddle.distributed import fleet from paddlenlp.utils.log import logger _MAX_DATA_DIM = 64 The provided code snippet includes necessary dependencies for implementing the `broadcast_data_list` function. Write a Python function `def broadcast_data_list(data_list, datatype, comm_rank=...
Broadcast data from src_rank to all ranks in comm_group.
39,947
import copy import random import warnings from collections.abc import Mapping from dataclasses import dataclass from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np import paddle from ..transformers import BertTokenizer from ..transformers.tokenizer_utils_base import ( Ba...
Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - `label`: handles a single value (int or float) per object - `label_ids`: handles a list of values per object Does not do any additional preprocessing: property names of the input object ...
39,948
import copy import random import warnings from collections.abc import Mapping from dataclasses import dataclass from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np import paddle from ..transformers import BertTokenizer from ..transformers.tokenizer_utils_base import ( Ba...
Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.
39,949
import copy import random import warnings from collections.abc import Mapping from dataclasses import dataclass from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np import paddle from ..transformers import BertTokenizer from ..transformers.tokenizer_utils_base import ( Ba...
Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.
39,950
import copy import random import warnings from collections.abc import Mapping from dataclasses import dataclass from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np import paddle from ..transformers import BertTokenizer from ..transformers.tokenizer_utils_base import ( Ba...
null
39,951
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def __best_fitting_dtype(vocab_size=None): if vocab_size is not None and vocab_size < 65500: return np.uint16 else: return np.int32
null
39,952
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def get_available_dataset_impl(): return ["lazy", "mmap"]
null
39,953
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle class IndexedDataset(paddle.io.Dataset): """Loader for IndexedDataset""" _HDR_MAGIC = b"TNTIDX\x00\x00" def __init__(self, path): super().__init__() ...
null
39,954
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def read_longs(f, n): a = np.empty(n, dtype=np.int64) f.readinto(a) return a
null
39,955
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def write_longs(f, a): f.write(np.array(a, dtype=np.int64))
null
39,956
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def read_shorts(f, n): a = np.empty(n, dtype=np.int32) f.readinto(a) return a
null
39,957
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def write_shorts(f, a): f.write(np.array(a, dtype=np.int32))
null
39,958
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle dtypes = { 1: np.uint8, 2: np.int8, 3: np.int16, 4: np.int32, 5: np.int64, 6: np.float64, 7: np.float32, 8: np.uint16, 9: np.uint32, ...
null
39,959
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def index_file_path(prefix_path): return prefix_path + ".idx"
null
39,960
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def data_file_path(prefix_path): return prefix_path + ".bin"
null
39,961
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def loss_mask_file_path(prefix_path): return prefix_path + ".lsm"
null
39,962
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def create_doc_idx(sizes): doc_idx = [0] for i, s in enumerate(sizes): if s == 0: doc_idx.append(i + 1) return doc_idx
null
39,963
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle def _warmup_mmap_file(path): with open(path, "rb") as stream: while stream.read(100 * 1024 * 1024): pass
null
39,964
import os import shutil import struct import time from functools import lru_cache from itertools import accumulate import numpy as np import paddle class IndexedDatasetBuilder(object): element_sizes = { np.uint8: 1, np.int8: 1, np.int16: 2, np.uint16: 2, np.int32: 4, ...
null
39,965
import os.path as osp import numpy as np import paddle import paddle.nn as nn from paddle.utils.download import get_path_from_url from paddlenlp.data import Vocab, get_idx_from_word from paddlenlp.utils.env import MODEL_HOME, _get_sub_home from paddlenlp.utils.log import logger from .constant import EMBEDDING_NAME_LIST...
Lists all names of pretrained embedding models paddlenlp provides.
39,966
import paddle def bloom_postprocess_past_key_value(past_key_values): # (layer_num, bs, head_num/tensor_parallel_degree, prefixlen, head_dim)*2 keys, values = paddle.transpose(past_key_values, perm=[2, 0, 1, 3, 4]).split(2) # keys: [layer_num, bs, head_num/tensor_parallel_degree, head_dim, prefixlen] # ...
null
39,967
import paddle def chatglm_postprocess_past_key_value(past_key_values): # (layer_num, prefixlen, bs, head_num/tensor_parallel_degree, head_dim)*2 keys, values = paddle.transpose(past_key_values, perm=[2, 1, 0, 3, 4]).split(2) return tuple(zip(keys, values))
null
39,968
import paddle def llama_postprocess_past_key_value(past_key_values): # (layer_num, bs, prefixlen, head_num/tensor_parallel_degree, head_dim)*2 keys, values = paddle.transpose(past_key_values, perm=[2, 0, 1, 3, 4]).split(2) return tuple(zip(keys, values))
null
39,969
import paddle def qwen_postprocess_past_key_value(past_key_values): # (layer_num, bs, prefixlen, head_num/tensor_parallel_degree, head_dim)*2 keys, values = paddle.transpose(past_key_values, perm=[2, 0, 1, 3, 4]).split(2) return tuple(zip(keys, values))
null
39,970
import paddle import paddle paddle.nn.TransformerEncoderLayer._ft_forward = encoder_layer_forward paddle.nn.TransformerEncoder._ft_forward = encoder_forward paddle.nn.TransformerEncoderLayer._ori_forward = paddle.nn.TransformerEncoderLayer.forward paddle.nn.TransformerEncoder._ori_forward = paddle.nn.Transforme...
r""" Executes the sum of product of provided operands based on the Einstein summation convention. Einsum can be used to complete a variety of operations, such as sum, transpose, batch matrix multiplication. Args: equation (`str`): Uses uncased letters to specify the dimension of the operands and result. The input equat...
39,971
import functools import hashlib import os import subprocess import sys import sysconfig import textwrap from pathlib import Path from filelock import FileLock from paddle.utils.cpp_extension import load_op_meta_info_and_register_op from paddle.utils.cpp_extension.cpp_extension import CUDA_HOME from paddle.utils.cpp_ext...
null
39,972
import functools import hashlib import os import subprocess import sys import sysconfig import textwrap from pathlib import Path from filelock import FileLock from paddle.utils.cpp_extension import load_op_meta_info_and_register_op from paddle.utils.cpp_extension.cpp_extension import CUDA_HOME from paddle.utils.cpp_ext...
Helps to list all files under the given path.
39,973
from functools import partial import paddle from paddle.optimizer import AdamW The provided code snippet includes necessary dependencies for implementing the `layerwise_lr_decay` function. Write a Python function `def layerwise_lr_decay(decay_rate, name_dict, n_layers, param)` to solve the following problem: Args: dec...
Args: decay_rate (float): The layer-wise decay ratio. name_dict (dict): The keys of name_dict is dynamic name of model while the value of name_dict is static name. Use model.named_parameters() to get name_dict. n_layers (int): Total number of layers in the transformer encoder.
39,974
import paddle import paddle.nn as nn try: from paddle.distributed.fleet import fleet except Exception: import warnings warnings.warn("paddle.distributed is not contains in you paddle!") def guard(device): def decorator(Layer): class WrapperClass(Layer): def __init__(self, *args, **k...
null
39,975
import contextlib import paddle RNG_STATE_TRACKER = RNGStatesTracker() def get_rng_state_tracker(): return RNG_STATE_TRACKER
null
39,976
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,977
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,978
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,979
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,980
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,981
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,982
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,983
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,984
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null
39,985
import functools import os from collections import defaultdict from functools import partial import numpy as np import paddle import paddle.nn as nn from paddle.common_ops_import import LayerHelper from paddle.framework import core import paddlenlp from paddlenlp.ops.ext_utils import LOADED_EXT, load from paddlenlp.tra...
null