id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
20,900
from glob import glob import torch from torch import nn from bert4torch.snippets import DottableDict, ListDataset, sequence_padding from bert4torch.models import BaseModel, build_transformer_model from bert4torch.generation import SeqGeneration from bert4torch.callbacks import Callback, Logger from bert4torch.trainer i...
null
20,901
from glob import glob import torch from torch import nn from bert4torch.snippets import DottableDict, ListDataset, sequence_padding from bert4torch.models import BaseModel, build_transformer_model from bert4torch.generation import SeqGeneration from bert4torch.callbacks import Callback, Logger from bert4torch.trainer i...
null
20,902
from bert4torch.snippets import sequence_padding from bert4torch.callbacks import Callback import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel from transformers import AutoTokenizer from bert...
null
20,903
from bert4torch.snippets import sequence_padding from bert4torch.callbacks import Callback import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel from transformers import AutoTokenizer from bert...
null
20,904
torch from bert4torch.models import build_transformer_model from transformers import AutoTokenizer import re import json import os device = 'cuda' if torch.cuda.is_available() else 'cpu' tokenizer.padding_side = 'left' model = build_transformer_model(config_path=config_path, checkpoint_path=checkpoint_path).half() ...
Naive Bayes-based Context Extension 演示代码
20,905
import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel, DeepSpeedTrainer from bert4torch.snippets...
null
20,906
import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel, DeepSpeedTrainer from bert4torch.snippets...
null
20,907
import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate from bert4torch.callbacks import Callback import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel ...
null
20,908
import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate from bert4torch.callbacks import Callback import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel ...
null
20,909
from bert4torch.models import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel from bert4torch.sni...
null
20,910
from bert4torch.models import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel from bert4torch.sni...
null
20,911
import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import ListDatase...
null
20,912
import build_transformer_model from bert4torch.snippets import sequence_padding, text_segmentate import torch.nn as nn import torch import torch.optim as optim from torch.utils.data import DataLoader import torch from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import ListDatase...
null
20,913
from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequence_padding from bert4torch.callbacks import Callback from bert4torch.optimizers import get_linear_schedule_with_warmup import json import codecs import numpy as np from tqdm...
null
20,914
from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequence_padding from bert4torch.callbacks import Callback from bert4torch.optimizers import get_linear_schedule_with_warmup import json import codecs import numpy as np from tqdm...
从句子s中找与w最相近的片段, 借助分词工具和ngram的方式尽量精确地确定边界。
20,915
from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequence_padding from bert4torch.callbacks import Callback from bert4torch.optimizers import get_linear_schedule_with_warmup import json import codecs import numpy as np from tqdm...
null
20,916
from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequence_padding from bert4torch.callbacks import Callback from bert4torch.optimizers import get_linear_schedule_with_warmup import json import codecs import numpy as np from tqdm...
输入question和headers,转SQL
20,917
from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequence_padding from bert4torch.callbacks import Callback from bert4torch.optimizers import get_linear_schedule_with_warmup import json import codecs import numpy as np from tqdm...
判断两个SQL字典是否全匹配
20,918
torch.utils.data import DataLoader import torch.nn as nn import torch.optim as optim from bert4torch.callbacks import Callback from bert4torch.snippets import sequence_padding, ListDataset, seed_everything, get_pool_emb from bert4torch.layers import CRF from bert4torch.tokenizers import Tokenizer from bert4torch.models...
null
20,919
torch.utils.data import DataLoader import torch.nn as nn import torch.optim as optim from bert4torch.callbacks import Callback from bert4torch.snippets import sequence_padding, ListDataset, seed_everything, get_pool_emb from bert4torch.layers import CRF from bert4torch.tokenizers import Tokenizer from bert4torch.models...
null
20,920
e from tqdm import tqdm from bert4torch.models import build_transformer_model from bert4torch.tokenizers import Tokenizer, load_vocab from bert4torch.snippets import sequence_padding, ListDataset from bert4torch.callbacks import Callback from bert4torch.generation import AutoRegressiveDecoder import torch from torch.ut...
null
20,921
e from tqdm import tqdm from bert4torch.models import build_transformer_model from bert4torch.tokenizers import Tokenizer, load_vocab from bert4torch.snippets import sequence_padding, ListDataset from bert4torch.callbacks import Callback from bert4torch.generation import AutoRegressiveDecoder import torch from torch.ut...
null
20,922
from itertools import groupby from tqdm import tqdm from bert4torch.losses import SparseMultilabelCategoricalCrossentropy from bert4torch.tokenizers import Tokenizer from bert4torch.layers import EfficientGlobalPointer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequ...
null
20,923
from itertools import groupby from tqdm import tqdm from bert4torch.losses import SparseMultilabelCategoricalCrossentropy from bert4torch.tokenizers import Tokenizer from bert4torch.layers import EfficientGlobalPointer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequ...
评估函数,计算f1、precision、recall
20,924
from itertools import groupby from tqdm import tqdm from bert4torch.losses import SparseMultilabelCategoricalCrossentropy from bert4torch.tokenizers import Tokenizer from bert4torch.layers import EfficientGlobalPointer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequ...
预测结果到文件,方便提交
20,925
from bert4torch.models import build_transformer_model, BaseModel, BERT from bert4torch.snippets import sequence_padding, ListDataset from bert4torch.callbacks import Callback from bert4torch.tokenizers import Tokenizer from bert4torch.layers import BertLayer import torch from torch.utils.data import DataLoader, Dataset...
null
20,926
from bert4torch.models import build_transformer_model, BaseModel, BERT from bert4torch.snippets import sequence_padding, ListDataset from bert4torch.callbacks import Callback from bert4torch.tokenizers import Tokenizer from bert4torch.layers import BertLayer import torch from torch.utils.data import DataLoader, Dataset...
null
20,927
json from bert4torch.models import build_transformer_model, BaseModel, BERT from bert4torch.snippets import sequence_padding, ListDataset from bert4torch.callbacks import Callback from bert4torch.tokenizers import Tokenizer from bert4torch.layers import BertLayer import torch from torch.utils.data import DataLoader, Da...
输出预测结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。
20,928
import os import json import torch import sqlite3 import torch.optim as optim import transformers from tqdm import tqdm from tokenizers import AddedToken from func_timeout import func_set_timeout, FunctionTimedOut from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from transformer...
null
20,929
import os import json import torch import sqlite3 import torch.optim as optim import transformers from tqdm import tqdm from tokenizers import AddedToken from func_timeout import func_set_timeout, FunctionTimedOut from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from transformer...
null
20,930
import os import json import torch import sqlite3 import torch.optim as optim import transformers from tqdm import tqdm from tokenizers import AddedToken from func_timeout import func_set_timeout, FunctionTimedOut from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from transformer...
null
20,931
import build_transformer_model, BaseModel from bert4torch.tokenizers import Tokenizer, load_vocab from bert4torch.snippets import sequence_padding, text_segmentate, ListDataset from bert4torch.callbacks import Callback from bert4torch.generation import AutoRegressiveDecoder import torch from torch.utils.data import Dat...
null
20,932
import build_transformer_model, BaseModel from bert4torch.tokenizers import Tokenizer, load_vocab from bert4torch.snippets import sequence_padding, text_segmentate, ListDataset from bert4torch.callbacks import Callback from bert4torch.generation import AutoRegressiveDecoder import torch from torch.utils.data import Dat...
null
20,933
from bert4torch.tokenizers import Tokenizer, load_vocab import torch from torch import nn, optim from torch.utils.data import DataLoader from bert4torch.snippets import sequence_padding, ListDataset, take_along_dim from bert4torch.callbacks import Callback from cchess import * device = 'cuda' if torch.cuda.is_available...
数据生成器
20,934
from bert4torch.tokenizers import Tokenizer, load_vocab import torch from torch import nn, optim from torch.utils.data import DataLoader from bert4torch.snippets import sequence_padding, ListDataset, take_along_dim from bert4torch.callbacks import Callback from cchess import * def convert(tf_path, torch_path): # 用...
null
20,935
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys The provided code snippet includes necessary dependencies for implementing the `is_accelerate_available` function. Write a Python function ...
是否可以使用accelerate
20,936
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys The provided code snippet includes necessary dependencies for implementing the `is_flash_attn_available` function. Write a Python function ...
是否可以使用包flash_attn
20,937
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys The provided code snippet includes necessary dependencies for implementing the `is_xformers_available` function. Write a Python function `d...
是否可以使用xformers加速
20,938
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys The provided code snippet includes necessary dependencies for implementing the `is_fastapi_available` function. Write a Python function `de...
是否可以使用包fastapi
20,939
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys def is_pydantic_available(): return is_package_available('pydantic')
null
20,940
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys def is_trl_available(): return is_package_available("trl")
null
20,941
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys def is_sseclient_available(): return importlib.util.find_spec("sseclient")
null
20,942
import importlib.util from typing import Any, Tuple, Union import torch from packaging import version from torch4keras.snippets.import_utils import is_package_available import sys def is_streamlit_available(): return is_package_available('streamlit')
null
20,943
from contextlib import contextmanager import torch from torch import nn import os def parse_flag_from_env(key, default=False): """Returns truthy value for `key` from the env if available else the default.""" value = os.environ.get(key, str(default)) return str_to_bool(value) == 1 # As its name indicates `s...
A context manager under which models are initialized with all parameters on the meta device, therefore creating an empty model. Useful when just initializing the model would blow the available RAM. Args: include_buffers (`bool`, *optional*): Whether or not to also put all buffers on the meta device while initializing. ...
20,944
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `insert_arguments` function. Write a Python function...
装饰器,为类方法增加参数(主要用于类的__init__方法)
20,945
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `delete_arguments` function. Write a Python function...
装饰器,为类方法删除参数(主要用于类的__init__方法)
20,946
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `cal_ts_num` function. Write a Python function `def ...
查看某个tensor在gc中的数量
20,947
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `get_state_dict_dtype` function. Write a Python func...
Returns the first found floating dtype in `state_dict` if there is one, otherwise returns the first dtype.
20,948
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `set_default_torch_dtype` function. Write a Python f...
设置默认权重类型
20,949
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `load_state_dict_into_meta_model` function. Write a ...
把state_dict导入meta_model 为了代码简洁,这里device_map需要外部手动指定, 形式如{'embeddings.word_embeddings': 0, 'LayerNormFinal': 0, 'lm_head': 0}
20,950
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `old_checkpoint` function. Write a Python function `...
兼容torch<1.11.0时仅允许输入输出是位置参数 通过闭包来对返回参数进行控制
20,951
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `cuda_empty_cache` function. Write a Python function...
清理gpu显存
20,952
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `modify_variable_mapping` function. Write a Python f...
对variable_mapping的返回值(字典)进行修改
20,953
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path if os.environ.get('SAFETENSORS_FIRST', False): SAFETENSORS_BINS = ['.safetensors', '.bin'] # 优先查找safetensors格式权重 else: SAFE...
从一个文件夹copy到另一个文件夹 :param src: str, copy from src :param dst: str, copy to dst
20,954
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path if os.environ.get('SAFETENSORS_FIRST', False): SAFETENSORS_BINS = ['.safetensors', '.bin'] # 优先查找safetensors格式权重 else: SAFE...
获取local文件夹下的config文件路径 1. model_name: 从hf下载 2. local_file且config_path为None: 重新在local_file所在目录找对应的config_path 3. local_dir且config_path为None: 重新在local_dir找对应的config_path
20,955
import json import torch import gc import inspect from torch4keras.snippets import * from torch.utils.checkpoint import CheckpointFunction import shutil import re from pathlib import Path if os.environ.get('SAFETENSORS_FIRST', False): SAFETENSORS_BINS = ['.safetensors', '.bin'] # 优先查找safetensors格式权重 else: SAFE...
获取该local文件夹下的ckpt文件、文件列表 1. model_name: 从hf下载 2. local_file且config_path为None: 重新在local_file所在目录找对应的config_path 3. local_dir且config_path为None: 重新在local_dir找对应的config_path
20,956
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `is_string` function. Write a Python function `def is_string(s)` to solve t...
判断是否是字符串
20,957
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `truncate_sequences` function. Write a Python function `def truncate_sequen...
截断总长度至不超过maxlen
20,958
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `text_segmentate` function. Write a Python function `def text_segmentate(te...
将文本按照标点符号划分为若干个短句 :param text: 待划分的句子 :param maxlen: int, 截断长度 :param seps: 分隔符 :param strips: ''.strip() :param truncate: True表示标点符号切分后仍然超长时, 按照maxlen硬截断分成若干个短句 :return: List[str], 划分后的句子列表
20,959
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `merge_segmentate` function. Write a Python function `def merge_segmentate(...
把m个句子合并成不超过maxlen的n个句子, 主要用途是合并碎句子 :param sequences: List(str), 短句子列表 :param maxlen: int, 最大长度 :param sep: str, 合并使用的分隔符, 可以是,。等标点符号
20,960
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `text_augmentation` function. Write a Python function `def text_augmentatio...
简单的EDA策略, 增删改 :param texts: 需要增强的文本/文本list :param noise_dict: 噪音数据, 元素为str的list, tuple, set :param noise_len: 噪音长度, 优先试用 :param noise_p: 噪音比例 :param skip_words: 跳过的短语, string/list :param strategy: 修改的策略, 包含增insert, 删delete, 改replace, 随机random :param allow_dup: 是否允许同一个位置多次EDA
20,961
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random is_py2 = six.PY2 if not is_py2: basestring = str The provided code snippet includes necessary dependencies for implementing the `lowercase_and_normali...
转小写,并进行简单的标准化
20,962
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `sequence_padding` function. Write a Python function `def sequence_padding(...
将序列padding到同一长度
20,963
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random def parallel_apply_generator(func, iterable, workers, max_queue_size, dummy=False, random_seeds=True): """多进程或多线程地将func应用到iterable的每个元素中(直接从bert4keras中...
多进程或多线程地将func应用到iterable的每个元素中(直接从bert4keras中移植过来)。 注意这个apply是异步且无序的,也就是说依次输入a,b,c,但是输出可能是func(c), func(a), func(b)。 :param callback: 处理单个输出的回调函数; :param dummy: False是多进程/线性,True则是多线程/线性;windows需设置dummy=True :param random_seeds: 每个进程的随机种子; :param unordered: 若为False,则按照输入顺序返回,仅当callback为None时生效。
20,964
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `get_pool_emb` function. Write a Python function `def get_pool_emb(hidden_s...
获取句向量 :param hidden_state: torch.Tensor/List(torch.Tensor),last_hidden_state/all_encoded_layers :param pooled_output: torch.Tensor, bert的pool_output输出 :param attention_mask: torch.Tensor :param pool_strategy: str, ('cls', 'last-avg', 'mean', 'last-max', 'max', 'first-last-avg', 'custom') :param custom_layer: int/List[i...
20,965
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random The provided code snippet includes necessary dependencies for implementing the `create_position_ids_start_at_padding` function. Write a Python function `d...
生成padding_ids, 从padding_idx+1开始。忽略填充符号
20,966
import unicodedata import six import numpy as np import re import torch from torch.nn.utils.rnn import pad_sequence from torch4keras.snippets import * import random def entity_extract_rule(text:str, pattern:str=None, label:str=None, start:int=0, end:int=-1, dotall:bool=True, replace_pattern:Optional[Union[...
按照预设的正则规则来解析实体, 允许占位符
20,967
import torch import torch.nn as nn import numpy as np from bert4torch.activations import get_activation from bert4torch.layers.core import LayerNorm import random import warnings import math class BottleneckAdapterLayer(nn.Module): '''BottleneckAdapterLayer''' def __init__(self, adapter_input_size, bottleneck_s...
null
20,968
from torch import nn import torch import math import torch.nn.functional as F from typing import Union, List The provided code snippet includes necessary dependencies for implementing the `get_sinusoid_encoding_table` function. Write a Python function `def get_sinusoid_encoding_table(n_position, d_hid, base=10000.0, n...
sinusoid编码 :param n_position: int, 位置长度 :param d_hid: int, 位置编码长度 :param padding_idx: padding的token_ids :param ntk_alpha: int, 要扩展的倍数 :param rope_ratio: int, chatglm中32k的插值 :return: [seq_len, d_hid]
20,969
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging from typing import Any, Literal import unicodedata from io import open from bert4torch.snippets import truncate_sequences, is_string, lowercase_and_normalize, sequence_padding import re import six from c...
加载词典文件到dict
20,970
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging from typing import Any, Literal import unicodedata from io import open from bert4torch.snippets import truncate_sequences, is_string, lowercase_and_normalize, sequence_padding import re import six from c...
去除文本中的空白符
20,971
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging from typing import Any, Literal import unicodedata from io import open from bert4torch.snippets import truncate_sequences, is_string, lowercase_and_normalize, sequence_padding import re import six from c...
Checks whether `chars` is a whitespace character.
20,972
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging from typing import Any, Literal import unicodedata from io import open from bert4torch.snippets import truncate_sequences, is_string, lowercase_and_normalize, sequence_padding import re import six from c...
Checks whether `chars` is a control character.
20,973
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging from typing import Any, Literal import unicodedata from io import open from bert4torch.snippets import truncate_sequences, is_string, lowercase_and_normalize, sequence_padding import re import six from c...
Checks whether `chars` is a punctuation character.
20,974
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging from typing import Any, Literal import unicodedata from io import open from bert4torch.snippets import truncate_sequences, is_string, lowercase_and_normalize, sequence_padding import re import six from c...
Converts `text` to Unicode (if it's not already), assuming utf-8 input.
20,975
import math import torch from torch import nn from packaging import version The provided code snippet includes necessary dependencies for implementing the `_gelu_python` function. Write a Python function `def _gelu_python(x)` to solve the following problem: Original Implementation of the GELU activation function in Go...
Original Implementation of the GELU activation function in Google BERT repo when initially created. For information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in nn.functi...
20,976
import math import torch from torch import nn from packaging import version The provided code snippet includes necessary dependencies for implementing the `_gelu_new` function. Write a Python function `def _gelu_new(x)` to solve the following problem: Implementation of the GELU activation function currently in Google ...
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
20,977
import math import torch from torch import nn from packaging import version def gelu_fast(x): return 0.5 * x * (1.0 + torch.tanh(x * 0.7978845608 * (1.0 + 0.044715 * x * x)))
null
20,978
import math import torch from torch import nn from packaging import version def quick_gelu(x): return x * torch.sigmoid(1.702 * x)
null
20,979
import math import torch from torch import nn from packaging import version The provided code snippet includes necessary dependencies for implementing the `_silu_python` function. Write a Python function `def _silu_python(x)` to solve the following problem: See Gaussian Error Linear Units (Hendrycks et al., https://ar...
See Gaussian Error Linear Units (Hendrycks et al., https://arxiv.org/abs/1606.08415) where the SiLU (Sigmoid Linear Unit) was originally introduced and coined, and see Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning (Elfwing et al., https://arxiv.org/abs/1702.03118) and...
20,980
import math import torch from torch import nn from packaging import version The provided code snippet includes necessary dependencies for implementing the `_mish_python` function. Write a Python function `def _mish_python(x)` to solve the following problem: See Mish: A Self-Regularized Non-Monotonic Activation Functio...
See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://arxiv.org/abs/1908.08681). Also visit the official repository for the paper: https://github.com/digantamisra98/Mish
20,981
import math import torch from torch import nn from packaging import version def linear_act(x): return x
null
20,982
import math import torch from torch import nn from packaging import version def swiglu(x, dim=-1): x = torch.chunk(x, 2, dim=dim) return silu(x[0]) * x[1]
null
20,983
import math import torch from torch import nn from packaging import version ACT2FN = { "relu": nn.functional.relu, "silu": silu, "swish": silu, "swiglu": swiglu, "gelu": gelu, "tanh": torch.tanh, "gelu_new": _gelu_new, "gelu_fast": gelu_fast, "quick_gelu": quick_gelu, "mish": mis...
根据activation_string返回对应的激活函数 :param activation_string: str, 传入的激活函数名 :return: Any
20,984
import numpy as np import math import os import torch from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model from bert4torch.snippets import sequence_padding import re The provided code snippet includes necessary dependencies for implementing the `get_bool_ids_greater_than` f...
Get idx of the last dimension in probability arrays, which is greater than a limitation. Args: probs (List[List[float]]): The input probability arrays. limit (float): The limitation for probability. return_prob (bool): Whether to return the probability Returns: List[List[int]]: The index of the last dimension meet the ...
20,985
import numpy as np import math import os import torch from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model from bert4torch.snippets import sequence_padding import re The provided code snippet includes necessary dependencies for implementing the `get_span` function. Write a ...
Get span set from position start and end list. Args: start_ids (List[int]/List[tuple]): The start index list. end_ids (List[int]/List[tuple]): The end index list. with_prob (bool): If True, each element for start_ids and end_ids is a tuple aslike: (index, probability). Returns: set: The span set without overlapping, ev...
20,986
import numpy as np import math import os import torch from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model from bert4torch.snippets import sequence_padding import re def get_id_and_prob(spans, offset_map): prompt_length = 0 for i in range(1, len(offset_map)): ...
null
20,987
import numpy as np import math import os import torch from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model from bert4torch.snippets import sequence_padding import re The provided code snippet includes necessary dependencies for implementing the `cut_chinese_sent` function. ...
Cut the Chinese sentences more precisely, reference to "https://blog.csdn.net/blmoistawinde/article/details/82379256".
20,988
import numpy as np import math import os import torch from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model from bert4torch.snippets import sequence_padding import re def dbc2sbc(s): rs = "" for char in s: code = ord(char) if code == 0x3000: ...
null
20,989
import time import json import requests from contextlib import asynccontextmanager from typing import Any, Dict, List, Literal, Optional, Union from bert4torch.snippets import log_info, log_warn, cuda_empty_cache, AnyClass from bert4torch.snippets import is_fastapi_available, is_pydantic_available, is_sseclient_availab...
null
20,990
import time import json import requests from contextlib import asynccontextmanager from typing import Any, Dict, List, Literal, Optional, Union from bert4torch.snippets import log_info, log_warn, cuda_empty_cache, AnyClass from bert4torch.snippets import is_fastapi_available, is_pydantic_available, is_sseclient_availab...
添加ChatWebDemo
20,991
import os import torch from typing import Union, Optional from bert4torch.models import build_transformer_model from bert4torch.snippets import log_warn_once, cuda_empty_cache, is_streamlit_available, log_info from packaging import version import gc class ChatCli(Chat): '''在命令行中交互的demo''' def __init__(self, *ar...
添加ChatCliDemo
20,992
import os import torch from typing import Union, Optional from bert4torch.models import build_transformer_model from bert4torch.snippets import log_warn_once, cuda_empty_cache, is_streamlit_available, log_info from packaging import version import gc class ChatWebGradio(Chat): '''gradio实现的网页交互的demo 默认是stream输出,默...
添加ChatWebDemo
20,993
import os import torch from typing import Union, Optional from bert4torch.models import build_transformer_model from bert4torch.snippets import log_warn_once, cuda_empty_cache, is_streamlit_available, log_info from packaging import version import gc class ChatWebStreamlit(Chat): def __init__(self, *args, max_length...
添加ChatWebDemo
20,994
from torch.nn import Linear, Embedding from torch.nn.parameter import Parameter import torch.nn.functional as F import bz2 import torch import base64 import ctypes from typing import List import re from tqdm import tqdm from functools import partial import inspect from bert4torch.snippets import log_error def compress...
null
20,995
from torch.nn import Linear, Embedding from torch.nn.parameter import Parameter import torch.nn.functional as F import bz2 import torch import base64 import ctypes from typing import List import re from tqdm import tqdm from functools import partial import inspect from bert4torch.snippets import log_error def extract_...
null
20,996
from torch.nn import Linear, Embedding from torch.nn.parameter import Parameter import torch.nn.functional as F import bz2 import torch import base64 import ctypes from typing import List import re from tqdm import tqdm from functools import partial import inspect from bert4torch.snippets import log_error class CacheTe...
从chagglm-6b移植过来的的量化,方便以int8和int4进行推理 源链接:https://huggingface.co/THUDM/chatglm-6b/blob/main/quantization.py Replace fp16 linear with quantized linear 这里修改了hard code, 可以适配其他模型 target_modules: str/list, 指定对某些层做量化
20,997
from torch.nn import Linear, Embedding from torch.nn.parameter import Parameter import torch.nn.functional as F import bz2 import torch import base64 import ctypes from typing import List import re from tqdm import tqdm from functools import partial import inspect from bert4torch.snippets import log_error The provided...
transformer的load_in_8bit, 源自transformer源代码
20,998
from torch.optim.lr_scheduler import LambdaLR from torch.optim.optimizer import Optimizer import torch The provided code snippet includes necessary dependencies for implementing the `get_linear_schedule_with_warmup` function. Write a Python function `def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num...
带warmup的schedule, 源自transformers包optimization.py中 :param num_warmup_steps: 需要warmup的步数, 一般为 num_training_steps * warmup_proportion(warmup的比例, 建议0.05-0.15) :param num_training_steps: 总的训练步数, 一般为 train_batches * num_epoch
20,999
from torch.optim.lr_scheduler import LambdaLR from torch.optim.optimizer import Optimizer import torch The provided code snippet includes necessary dependencies for implementing the `extend_with_exponential_moving_average` function. Write a Python function `def extend_with_exponential_moving_average(model, decay=0.999...
模型权重的指数滑动平均, 不参加梯度更新,只是记录滑动平均的参数,给预测使用 注意区别于类似adam一类的自适应学习率优化器, 针对一阶二阶梯度的指数滑动平均, 两者完全不同 Example: >>> # 初始化 >>> ema = ExponentialMovingAverage(model, 0.999) >>> # 训练过程中, 更新完参数后, 同步update ema_weights weights >>> def train(): >>> optimizer.step() >>> ema.step() >>> # eval前, 调用apply_ema_weights(); eval之后, restore_raw_weigh...