code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_corpus_freq(dataset, filepath, filetype='tsv'):
"""
Take corpus, split it into sentences, and extract word frequencies.
Write frequencies to `filepath` as a tsv. Only write the first
MAX_SENTENCEPIECE_SENTENCES most common words to the file.
"""
nltk.download('punkt', download_dir="./nlt... |
Take corpus, split it into sentences, and extract word frequencies.
Write frequencies to `filepath` as a tsv. Only write the first
MAX_SENTENCEPIECE_SENTENCES most common words to the file.
| get_corpus_freq | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def load_spm_model(self):
"""load sentencepiece model and parse vocab"""
if not os.path.exists(self.spm_model) and not self.spm_model.endswith('.model'):
self.spm_model = self.spm_model + '.model'
self.sp = spm.SentencePieceProcessor()
self.sp.Load(self.spm_model)
sel... | load sentencepiece model and parse vocab | load_spm_model | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def Train(self, corpus, num_text_tokens):
"""train sentencepiece model on corpus using word frequencies"""
self.num_text_tokens = num_text_tokens
use_model_path = self.spm_model
random_hash = str(random.randint(0, 2147483647))
if use_model_path is None:
use_model_path... | train sentencepiece model on corpus using word frequencies | Train | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def DecodeTokens(self, Tokens):
"""converts sentencepiece tokens to a text string"""
if isinstance(Tokens, Tokenization):
Tokens = Tokens.tokenization
return self.sp.DecodeTokens(Tokens) | converts sentencepiece tokens to a text string | DecodeTokens | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def DecodeIds(self, Ids, type_token=False):
"""converts ids to wordpiece tokens and joins them as a text string"""
if type_token:
return ' '.join(Id.token if isinstance(Id, TypeToken) else self.type_id_map[Id].token for Id in Ids)
if isinstance(Ids, Tokenization):
Ids = I... | converts ids to wordpiece tokens and joins them as a text string | DecodeIds | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def DecodeTokens(self, Tokens, type_token=False):
"""converts wordpiece tokens to a text string"""
if type_token:
return ' '.join(t.token if isinstance(t, TypeToken) else t for t in Tokens)
if isinstance(Tokens, Tokenization):
Tokens = Tokens.tokenization
return '... | converts wordpiece tokens to a text string | DecodeTokens | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs | Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
| get_pairs | python | THUDM/GLM | data_utils/tokenization_gpt2.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization_gpt2.py | MIT |
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
"""
Instantiate a PreTrainedBertModel from a pre-trained model file.
Download and cache the pre-trained model file if needed.
"""
if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHI... |
Instantiate a PreTrainedBertModel from a pre-trained model file.
Download and cache the pre-trained model file if needed.
| from_pretrained | python | THUDM/GLM | data_utils/tokenization_gpt2.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization_gpt2.py | MIT |
def set_special_tokens(self, special_tokens):
""" Add a list of additional tokens to the encoder.
The additional tokens are indexed starting from the last index of the
current vocabulary in the order of the `special_tokens` list.
"""
if not special_tokens:
sel... | Add a list of additional tokens to the encoder.
The additional tokens are indexed starting from the last index of the
current vocabulary in the order of the `special_tokens` list.
| set_special_tokens | python | THUDM/GLM | data_utils/tokenization_gpt2.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization_gpt2.py | MIT |
def convert_tokens_to_ids(self, tokens):
""" Converts a sequence of tokens into ids using the vocab. """
ids = []
if isinstance(tokens, str) or (sys.version_info[0] == 2 and isinstance(tokens, unicode)):
if tokens in self.special_tokens:
return self.special_tokens[tok... | Converts a sequence of tokens into ids using the vocab. | convert_tokens_to_ids | python | THUDM/GLM | data_utils/tokenization_gpt2.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization_gpt2.py | MIT |
def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
"""Converts a sequence of ids in BPE tokens using the vocab."""
tokens = []
for i in ids:
if i in self.special_tokens_decoder:
if not skip_special_tokens:
tokens.append(self.special_t... | Converts a sequence of ids in BPE tokens using the vocab. | convert_ids_to_tokens | python | THUDM/GLM | data_utils/tokenization_gpt2.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization_gpt2.py | MIT |
def save_vocabulary(self, vocab_path):
"""Save the tokenizer vocabulary and merge files to a directory."""
if not os.path.isdir(vocab_path):
logger.error("Vocabulary path ({}) should be a directory".format(vocab_path))
return
vocab_file = os.path.join(vocab_path, VOCAB_NA... | Save the tokenizer vocabulary and merge files to a directory. | save_vocabulary | python | THUDM/GLM | data_utils/tokenization_gpt2.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization_gpt2.py | MIT |
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens | Runs basic whitespace cleaning and splitting on a piece of text. | whitespace_tokenize | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def __init__(self, vocab_file, do_lower_case=True, max_len=None, do_basic_tokenize=True,
never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
"""Constructs a BertTokenizer.
Args:
vocab_file: Path to a one-wordpiece-per-line vocabulary file
do_lower_case: Whe... | Constructs a BertTokenizer.
Args:
vocab_file: Path to a one-wordpiece-per-line vocabulary file
do_lower_case: Whether to lower case the input
Only has an effect when do_wordpiece_only=False
do_basic_tokenize: Whether to do basic tokenization before wordpie... | __init__ | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def convert_tokens_to_ids(self, tokens):
"""Converts a sequence of tokens into ids using the vocab."""
ids = []
for token in tokens:
ids.append(self.vocab[token])
if len(ids) > self.max_len:
logger.warning(
"Token indices sequence length is longer ... | Converts a sequence of tokens into ids using the vocab. | convert_tokens_to_ids | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def convert_ids_to_tokens(self, ids):
"""Converts a sequence of ids in wordpiece tokens using the vocab."""
tokens = []
for i in ids:
tokens.append(self.ids_to_tokens[i])
return tokens | Converts a sequence of ids in wordpiece tokens using the vocab. | convert_ids_to_tokens | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def __init__(self,
do_lower_case=True,
never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
"""Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input.
"""
self.do_lower_case = do_lower_case
self.never... | Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input.
| __init__ | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
... | Strips accents from a piece of text. | _run_strip_accents | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
if text in self.never_split:
return [text]
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_... | Splits punctuation on a piece of text. | _run_split_on_punc | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
... | Adds whitespace around any CJK character. | _tokenize_chinese_chars | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _is_chinese_char(self, cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is ... | Checks whether CP is the codepoint of a CJK character. | _is_chinese_char | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xfffd or _is_control(char):
continue
if _is_whitespace(char):
... | Performs invalid character removal and whitespace cleanup on text. | _clean_text | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def tokenize(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
... | Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespa... | tokenize | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat... | Checks whether `chars` is a whitespace character. | _is_whitespace | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _is_control(char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char == "\t" or char == "\n" or char == "\r":
return False
cat = unicodedata.category(char)
if cat.startswith("C"):
... | Checks whether `chars` is a control character. | _is_control | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.... | Checks whether `chars` is a punctuation character. | _is_punctuation | python | THUDM/GLM | data_utils/wordpiece.py | https://github.com/THUDM/GLM/blob/master/data_utils/wordpiece.py | MIT |
def get_dataset(name, tokenizer, pre_tokenize, data_parallel_rank, loader_scatter=None, no_lazy_loader=False,
half_lazy_loader=False):
"""gets dataset object based on keyword args and file at `path`"""
global_rank = torch.distributed.get_rank()
if not supported_corpus(name):
raise No... | gets dataset object based on keyword args and file at `path` | get_dataset | python | THUDM/GLM | data_utils/__init__.py | https://github.com/THUDM/GLM/blob/master/data_utils/__init__.py | MIT |
def make_dataset(path, seq_length, mem_length, shuffle=True, split=None, tokenizer=None,
sample_one_document=False, pre_tokenize=False, ds_type='', save_splits=None, load_splits=None,
save_test_data=None, no_lazy_loader=False, loader_scatter=None, data_parallel_rank=None,
... | function to create datasets+tokenizers for common options | make_dataset | python | THUDM/GLM | data_utils/__init__.py | https://github.com/THUDM/GLM/blob/master/data_utils/__init__.py | MIT |
def conversion_helper(val, conversion):
"""Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure."""
if not isinstance(val, (tuple, list)):
return conversion(val)
rtn = [conversion_helper(v, conversion) for v in val]
if isinstance(val, tuple):
rt... | Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure. | conversion_helper | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def clip_master_grads(self, max_norm, norm_type=2):
"""
Clips fp32 master gradients via ``torch.nn.utils.clip_grad_norm``.
Args:
max_norm (float or int): max norm of the gradients
norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
inf... |
Clips fp32 master gradients via ``torch.nn.utils.clip_grad_norm``.
Args:
max_norm (float or int): max norm of the gradients
norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
infinity norm.
Returns:
Total norm of the cur... | clip_master_grads | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def state_dict(self):
"""
Returns a dict containing the current state of this :class:`FP16_Optimizer` instance.
This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict
of the contained Pytorch optimizer.
Example::
checkpoint = {}
... |
Returns a dict containing the current state of this :class:`FP16_Optimizer` instance.
This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict
of the contained Pytorch optimizer.
Example::
checkpoint = {}
checkpoint['model'] = model.st... | state_dict | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def load_state_dict(self, state_dict):
"""
Loads a state_dict created by an earlier call to state_dict().
If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``,
whose parameters in turn came from ``model``, it is expected that the user
will call ``model.l... |
Loads a state_dict created by an earlier call to state_dict().
If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``,
whose parameters in turn came from ``model``, it is expected that the user
will call ``model.load_state_dict()`` before
``fp16_optimizer... | load_state_dict | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def step(self, closure=None): # could add clip option.
"""
If no closure is supplied, :attr:`step` should be called after
``fp16_optimizer_obj.backward(loss)``.
:attr:`step` updates the fp32 master copy of parameters using the optimizer supplied to
:class:`FP16_Optimizer`'s con... |
If no closure is supplied, :attr:`step` should be called after
``fp16_optimizer_obj.backward(loss)``.
:attr:`step` updates the fp32 master copy of parameters using the optimizer supplied to
:class:`FP16_Optimizer`'s constructor, then copies the updated fp32 params into the fp16 params
... | step | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def backward(self, loss, update_master_grads=True, retain_graph=False):
"""
:attr:`backward` performs the following conceptual steps:
1. fp32_loss = loss.float() (see first Note below)
2. scaled_loss = fp32_loss*loss_scale
3. scaled_loss.backward(), which accumulates scaled gra... |
:attr:`backward` performs the following conceptual steps:
1. fp32_loss = loss.float() (see first Note below)
2. scaled_loss = fp32_loss*loss_scale
3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's leaves (which may be fp16, fp32... | backward | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def update_master_grads(self):
"""
Copy the ``.grad`` attribute from stored references to fp16 parameters to
the ``.grad`` attribute of the fp32 master parameters that are directly
updated by the optimizer. :attr:`update_master_grads` only needs to be called if
``fp16_optimize... |
Copy the ``.grad`` attribute from stored references to fp16 parameters to
the ``.grad`` attribute of the fp32 master parameters that are directly
updated by the optimizer. :attr:`update_master_grads` only needs to be called if
``fp16_optimizer_obj.backward`` was called with ``update_... | update_master_grads | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def inspect_master_grad_data(self):
"""
When running with :class:`FP16_Optimizer`,
``.grad`` attributes of a model's fp16 leaves should not be
regarded as truthful, because they might be scaled.
After a call to :attr:`fp16_optimizer_obj.backward(loss)`, if no overflow was enco... |
When running with :class:`FP16_Optimizer`,
``.grad`` attributes of a model's fp16 leaves should not be
regarded as truthful, because they might be scaled.
After a call to :attr:`fp16_optimizer_obj.backward(loss)`, if no overflow was encountered,
the fp32 master params' ``.gra... | inspect_master_grad_data | python | THUDM/GLM | fp16/fp16.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16.py | MIT |
def BN_convert_float(module):
"""
Utility function for network_to_half().
Retained for legacy purposes.
"""
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True:
module.float()
for child in module.children():
BN_convert_float(child)
return m... |
Utility function for network_to_half().
Retained for legacy purposes.
| BN_convert_float | python | THUDM/GLM | fp16/fp16util.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16util.py | MIT |
def convert_module(module, dtype):
"""
Converts a module's immediate parameters and buffers to dtype.
"""
for param in module.parameters(recurse=False):
if param is not None:
if param.data.dtype.is_floating_point:
param.data = param.data.to(dtype=dtype)
if... |
Converts a module's immediate parameters and buffers to dtype.
| convert_module | python | THUDM/GLM | fp16/fp16util.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16util.py | MIT |
def convert_network(network, dtype):
"""
Converts a network's parameters and buffers to dtype.
"""
for module in network.modules():
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True:
continue
convert_module(module, dtype)
return networ... |
Converts a network's parameters and buffers to dtype.
| convert_network | python | THUDM/GLM | fp16/fp16util.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16util.py | MIT |
def prep_param_lists(model, flat_master=False):
"""
Creates a list of FP32 master parameters for a given model, as in
`Training Neural Networks with Mixed Precision: Real Examples`_.
Args:
model (torch.nn.Module): Existing Pytorch model
flat_master (bool, optional, default=False): Fla... |
Creates a list of FP32 master parameters for a given model, as in
`Training Neural Networks with Mixed Precision: Real Examples`_.
Args:
model (torch.nn.Module): Existing Pytorch model
flat_master (bool, optional, default=False): Flatten the master parameters into a single tensor, as a p... | prep_param_lists | python | THUDM/GLM | fp16/fp16util.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16util.py | MIT |
def model_grads_to_master_grads(model_params, master_params, flat_master=False):
"""
Copy model gradients to master gradients.
Args:
model_params: List of model parameters created by :func:`prep_param_lists`.
master_params: List of FP32 master parameters created by :func:`prep_param_lis... |
Copy model gradients to master gradients.
Args:
model_params: List of model parameters created by :func:`prep_param_lists`.
master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` s... | model_grads_to_master_grads | python | THUDM/GLM | fp16/fp16util.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16util.py | MIT |
def master_params_to_model_params(model_params, master_params, flat_master=False):
"""
Copy master parameters to model parameters.
Args:
model_params: List of model parameters created by :func:`prep_param_lists`.
master_params: List of FP32 master parameters created by :func:`prep_param_l... |
Copy master parameters to model parameters.
Args:
model_params: List of model parameters created by :func:`prep_param_lists`.
master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` s... | master_params_to_model_params | python | THUDM/GLM | fp16/fp16util.py | https://github.com/THUDM/GLM/blob/master/fp16/fp16util.py | MIT |
def scaled_init_method(mean, std, num_layers):
"""Init method based on N(0, sigma/sqrt(2*num_layers)."""
std = std / math.sqrt(2.0 * num_layers)
def init_(tensor):
return torch.nn.init.normal_(tensor, mean=mean, std=std)
return init_ | Init method based on N(0, sigma/sqrt(2*num_layers). | scaled_init_method | python | THUDM/GLM | model/modeling_bert.py | https://github.com/THUDM/GLM/blob/master/model/modeling_bert.py | MIT |
def load_tf_weights_in_bert(model, tf_checkpoint_path):
""" Load tf checkpoints in a pytorch model
"""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please ... | Load tf checkpoints in a pytorch model
| load_tf_weights_in_bert | python | THUDM/GLM | model/modeling_bert.py | https://github.com/THUDM/GLM/blob/master/model/modeling_bert.py | MIT |
def __init__(self,
vocab_size_or_config_json_file,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
at... | Constructs BertConfig.
Args:
vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.
hidden_size: Size of the encoder layers and the pooler layer.
num_hidden_layers: Number of hidden layers in the Transformer encoder.
num_attention_heads: ... | __init__ | python | THUDM/GLM | model/modeling_bert.py | https://github.com/THUDM/GLM/blob/master/model/modeling_bert.py | MIT |
def from_dict(cls, json_object):
"""Constructs a `BertConfig` from a Python dictionary of parameters."""
config = BertConfig(vocab_size_or_config_json_file=-1)
for key, value in json_object.items():
config.__dict__[key] = value
return config | Constructs a `BertConfig` from a Python dictionary of parameters. | from_dict | python | THUDM/GLM | model/modeling_bert.py | https://github.com/THUDM/GLM/blob/master/model/modeling_bert.py | MIT |
def from_json_file(cls, json_file):
"""Constructs a `BertConfig` from a json file of parameters."""
with open(json_file, "r", encoding='utf-8') as reader:
text = reader.read()
return cls.from_dict(json.loads(text)) | Constructs a `BertConfig` from a json file of parameters. | from_json_file | python | THUDM/GLM | model/modeling_bert.py | https://github.com/THUDM/GLM/blob/master/model/modeling_bert.py | MIT |
def __init__(self, hidden_size, eps=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(BertLayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hid... | Construct a layernorm module in the TF style (epsilon inside the square root).
| __init__ | python | THUDM/GLM | model/modeling_bert.py | https://github.com/THUDM/GLM/blob/master/model/modeling_bert.py | MIT |
def from_pretrained(cls, pretrained_model_name, state_dict=None, cache_dir=None,
fp32_layernorm=False, fp32_embedding=False, layernorm_epsilon=1e-12,
fp32_tokentypes=False, *inputs, **kwargs):
"""
Instantiate a PreTrainedBertModel from a pre-trained model ... |
Instantiate a PreTrainedBertModel from a pre-trained model file or a pytorch state dict.
Download and cache the pre-trained model file if needed.
Params:
pretrained_model_name: either:
- a str with the name of a pre-trained model to load selected in the list of:
... | from_pretrained | python | THUDM/GLM | model/modeling_bert.py | https://github.com/THUDM/GLM/blob/master/model/modeling_bert.py | MIT |
def init_method_normal(std=0.02):
"""Init method based on normal distribution.
This is only used for embeddings. The transformer has its
own initializer.
"""
def init_(tensor):
return torch.nn.init.normal_(tensor, mean=0.0, std=std)
return init_ | Init method based on normal distribution.
This is only used for embeddings. The transformer has its
own initializer.
| init_method_normal | python | THUDM/GLM | model/modeling_glm.py | https://github.com/THUDM/GLM/blob/master/model/modeling_glm.py | MIT |
def _check_data_types(keys, data, target_dtype):
"""Check that all the keys have the same target data type."""
for key in keys:
assert data[key].dtype == target_dtype, '{} has data type {} which '\
'is different than {}'.format(key, data[key].dtype, target_dtype) | Check that all the keys have the same target data type. | _check_data_types | python | THUDM/GLM | mpu/data.py | https://github.com/THUDM/GLM/blob/master/mpu/data.py | MIT |
def _build_key_size_numel_dictionaries(keys, data):
"""Build the size on rank 0 and broadcast."""
max_dim = _MAX_DATA_DIM
sizes = [0 for _ in range(max_dim) for _ in keys]
# Pack the sizes on rank zero.
if get_model_parallel_rank() == 0:
offset = 0
for key in keys:
asser... | Build the size on rank 0 and broadcast. | _build_key_size_numel_dictionaries | python | THUDM/GLM | mpu/data.py | https://github.com/THUDM/GLM/blob/master/mpu/data.py | MIT |
def broadcast_data(keys, data, datatype):
"""Broadcast data from rank zero of each model parallel group to the
members of the same model parallel group.
Arguments:
keys: list of keys in the data disctionary to be broadcasted
data: data dictionary of string keys and cpu tensor values.
... | Broadcast data from rank zero of each model parallel group to the
members of the same model parallel group.
Arguments:
keys: list of keys in the data disctionary to be broadcasted
data: data dictionary of string keys and cpu tensor values.
datatype: torch data type of all tensors in dat... | broadcast_data | python | THUDM/GLM | mpu/data.py | https://github.com/THUDM/GLM/blob/master/mpu/data.py | MIT |
def clip_grad_norm(parameters, max_norm, norm_type=2):
"""Clips gradient norm of an iterable of parameters.
This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and
added functionality to handle model parallel parameters. Note that
the gradients are modified in place.
Arguments:
p... | Clips gradient norm of an iterable of parameters.
This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and
added functionality to handle model parallel parameters. Note that
the gradients are modified in place.
Arguments:
parameters (Iterable[Tensor] or Tensor): an iterable of Tensors... | clip_grad_norm | python | THUDM/GLM | mpu/grads.py | https://github.com/THUDM/GLM/blob/master/mpu/grads.py | MIT |
def initialize_model_parallel(model_parallel_size_):
"""
Initialize model data parallel groups.
Arguments:
model_parallel_size: number of GPUs used to parallelize model.
Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we
use 2 GPUs to parallelize the model. The present functio... |
Initialize model data parallel groups.
Arguments:
model_parallel_size: number of GPUs used to parallelize model.
Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we
use 2 GPUs to parallelize the model. The present function will
create 4 model parallel groups and 2 data paralle... | initialize_model_parallel | python | THUDM/GLM | mpu/initialize.py | https://github.com/THUDM/GLM/blob/master/mpu/initialize.py | MIT |
def model_parallel_is_initialized():
"""Check if model and data parallel groups are initialized."""
if _MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None:
return False
return True | Check if model and data parallel groups are initialized. | model_parallel_is_initialized | python | THUDM/GLM | mpu/initialize.py | https://github.com/THUDM/GLM/blob/master/mpu/initialize.py | MIT |
def get_model_parallel_group():
"""Get the model parallel group the caller rank belongs to."""
assert _MODEL_PARALLEL_GROUP is not None, \
'model parallel group is not initialized'
return _MODEL_PARALLEL_GROUP | Get the model parallel group the caller rank belongs to. | get_model_parallel_group | python | THUDM/GLM | mpu/initialize.py | https://github.com/THUDM/GLM/blob/master/mpu/initialize.py | MIT |
def get_data_parallel_group():
"""Get the data parallel group the caller rank belongs to."""
assert _DATA_PARALLEL_GROUP is not None, \
'data parallel group is not initialized'
return _DATA_PARALLEL_GROUP | Get the data parallel group the caller rank belongs to. | get_data_parallel_group | python | THUDM/GLM | mpu/initialize.py | https://github.com/THUDM/GLM/blob/master/mpu/initialize.py | MIT |
def get_model_parallel_src_rank():
"""Calculate the global rank corresponding to a local rank zeor
in the model parallel group."""
global_rank = torch.distributed.get_rank()
local_world_size = get_model_parallel_world_size()
return (global_rank // local_world_size) * local_world_size | Calculate the global rank corresponding to a local rank zeor
in the model parallel group. | get_model_parallel_src_rank | python | THUDM/GLM | mpu/initialize.py | https://github.com/THUDM/GLM/blob/master/mpu/initialize.py | MIT |
def _initialize_affine_weight(weight, output_size, input_size,
per_partition_size, partition_dim, init_method,
stride=1, return_master_weight=False):
"""Initialize affine weight for model parallel.
Build the master weight on all processes and scatter
... | Initialize affine weight for model parallel.
Build the master weight on all processes and scatter
the relevant chunk. | _initialize_affine_weight | python | THUDM/GLM | mpu/layers.py | https://github.com/THUDM/GLM/blob/master/mpu/layers.py | MIT |
def _reduce(input_):
"""All-reduce the the input tensor across model parallel group."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
if torch.distributed.get_world_size(group=group) == 1:
return input_
# All-reduce.
torch.distributed.all_reduce(i... | All-reduce the the input tensor across model parallel group. | _reduce | python | THUDM/GLM | mpu/mappings.py | https://github.com/THUDM/GLM/blob/master/mpu/mappings.py | MIT |
def _split(input_):
"""Split the tensor along its last dimension and keep the
corresponding slice."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
if torch.distributed.get_world_size(group=group) == 1:
return input_
# Split along last dimension.
... | Split the tensor along its last dimension and keep the
corresponding slice. | _split | python | THUDM/GLM | mpu/mappings.py | https://github.com/THUDM/GLM/blob/master/mpu/mappings.py | MIT |
def _gather(input_):
"""Gather tensors and concatinate along the last dimension."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
if torch.distributed.get_world_size(group=group) == 1:
return input_
# Size and dimension.
last_dim = input_.dim() - ... | Gather tensors and concatinate along the last dimension. | _gather | python | THUDM/GLM | mpu/mappings.py | https://github.com/THUDM/GLM/blob/master/mpu/mappings.py | MIT |
def _set_cuda_rng_state(new_state, device=-1):
"""Sets the random number generator state of the current GPU.
Argumentss:
new_state (torch.ByteTensor): The desired state
This function is adapted from PyTorch repo (torch.cuda.set_rng_state)
with a single change: the input state is not cloned. Clo... | Sets the random number generator state of the current GPU.
Argumentss:
new_state (torch.ByteTensor): The desired state
This function is adapted from PyTorch repo (torch.cuda.set_rng_state)
with a single change: the input state is not cloned. Cloning caused
major performance issues for +4 GPU ca... | _set_cuda_rng_state | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def reset(self):
"""Set to the initial state (no tracker)."""
self.states_ = {}
self.seeds_ = set() | Set to the initial state (no tracker). | reset | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def get_states(self):
"""Get rng states. Copy the dictionary so we have direct
pointers to the states, not just a pointer to the dictionary."""
states = {}
for name in self.states_:
states[name] = self.states_[name]
return states | Get rng states. Copy the dictionary so we have direct
pointers to the states, not just a pointer to the dictionary. | get_states | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME):
"""Fork the cuda rng state, perform operations, and exit with
the original state."""
# Check if we have added the state
if name not in self.states_:
raise Exception('cuda rng state {} is not added'.format(name))
#... | Fork the cuda rng state, perform operations, and exit with
the original state. | fork | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def model_parallel_cuda_manual_seed(seed):
"""Initialize model parallel cuda seed.
This function should be called after the model parallel is
initialized. Also, no torch.cuda.manual_seed should be called
after this function. Basically, this is replacement for that
function.
Two set of RNG state... | Initialize model parallel cuda seed.
This function should be called after the model parallel is
initialized. Also, no torch.cuda.manual_seed should be called
after this function. Basically, this is replacement for that
function.
Two set of RNG states are tracked:
default state: This is for ... | model_parallel_cuda_manual_seed | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def _transpose_for_scores(self, tensor):
"""Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
"""
new_tensor_shape = tensor.size()[:-1] + \
(self.num_attention_heads_per_partition,
self.hidden_size_per_at... | Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
| _transpose_for_scores | python | THUDM/GLM | mpu/transformer.py | https://github.com/THUDM/GLM/blob/master/mpu/transformer.py | MIT |
def divide(numerator, denominator):
"""Ensure that numerator is divisible by the denominator and return
the division value."""
ensure_divisibility(numerator, denominator)
return numerator // denominator | Ensure that numerator is divisible by the denominator and return
the division value. | divide | python | THUDM/GLM | mpu/utils.py | https://github.com/THUDM/GLM/blob/master/mpu/utils.py | MIT |
def split_tensor_along_last_dim(tensor, num_partitions,
contiguous_split_chunks=False):
"""Split a tensor along its last dimension.
Arguments:
tensor: input tensor.
num_partitions: number of partitions to split the tensor
contiguous_split_chunks: If True, ... | Split a tensor along its last dimension.
Arguments:
tensor: input tensor.
num_partitions: number of partitions to split the tensor
contiguous_split_chunks: If True, make each chunk contiguous
in memory.
| split_tensor_along_last_dim | python | THUDM/GLM | mpu/utils.py | https://github.com/THUDM/GLM/blob/master/mpu/utils.py | MIT |
def update_cmd(cmd, config):
'''
@param cmd str
@param configs list of dicts
'''
for k, v in config.items():
if v is None:
continue
if type(v) == bool:
if v:
cmd += "--{} ".format(k)
else:
cmd += "--{} {} ".format(k,... |
@param cmd str
@param configs list of dicts
| update_cmd | python | THUDM/GLM | scripts/dispatcher.py | https://github.com/THUDM/GLM/blob/master/scripts/dispatcher.py | MIT |
def clean_text(text):
"""Remove new lines and multiple spaces and adjust end of sentence dot."""
text = text.replace("\n", " ")
text = re.sub(r'\s+', ' ', text)
for _ in range(3):
text = text.replace(' . ', '. ')
return text | Remove new lines and multiple spaces and adjust end of sentence dot. | clean_text | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def __init__(self, guid, text_a, text_b=None, label=None, logits=None, meta: Optional[Dict] = None, idx=-1,
num_choices=1):
"""
Create a new InputExample.
:param guid: a unique textual identifier
:param text_a: the sequence of text
:param text_b: an optional, se... |
Create a new InputExample.
:param guid: a unique textual identifier
:param text_a: the sequence of text
:param text_b: an optional, second sequence of text
:param label: an optional label
:param logits: an optional list of per-class logits
:param meta: an option... | __init__ | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def build_sample(ids, types=None, paddings=None, positions=None, masks=None, label=None, unique_id=None, target=None,
logit_mask=None, segment_ids=None, prompt_ids=None):
"""Convert to numpy and return a sample consumed by the batch producer."""
ids_np = np.array(ids, dtype=np.int64)
sampl... | Convert to numpy and return a sample consumed by the batch producer. | build_sample | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def build_data_loader(dataset, batch_size, num_workers, drop_last, shuffle=True, only_rank0=False):
"""Data loader. Note that batch-size is the local (per GPU) batch-size."""
# Sampler.
if only_rank0:
rank, world_size = 0, 1
else:
world_size = mpu.get_data_parallel_world_size()
... | Data loader. Note that batch-size is the local (per GPU) batch-size. | build_data_loader | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def multichoice_evaluate(model, dataloader, example_dict, args):
"""Calculate correct over total answers and return prediction if the
`output_predictions` is true."""
model.eval()
results = {}
with torch.no_grad():
# For all the batches in the dataset.
for _, batch in enumerate(datal... | Calculate correct over total answers and return prediction if the
`output_predictions` is true. | multichoice_evaluate | python | THUDM/GLM | tasks/eval_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/eval_utils.py | MIT |
def evaluate_and_print_results(data_loader, model, eval_metric, args):
"""Evaluate and print results on screen."""
# Evaluate and get results.
output, _ = evaluate(model, data_loader, eval_metric, args)
string = ""
if eval_metric == 'loss':
output = output['loss']
num_tokenized_tok... | Evaluate and print results on screen. | evaluate_and_print_results | python | THUDM/GLM | tasks/language_model/finetune.py | https://github.com/THUDM/GLM/blob/master/tasks/language_model/finetune.py | MIT |
def evaluate(self, model, dataloader, example_dict, args):
"""Calculate correct over total answers and return prediction if the
`output_predictions` is true."""
model.eval()
local_predictions = {}
print_rank_0("Distributed store created")
with torch.no_grad():
... | Calculate correct over total answers and return prediction if the
`output_predictions` is true. | evaluate | python | THUDM/GLM | tasks/seq2seq/evaluate.py | https://github.com/THUDM/GLM/blob/master/tasks/seq2seq/evaluate.py | MIT |
def multirc_em(predictions, labels, examples: List[InputExample]):
"""Compute the exact match (EM) for a sequence of predictions and actual labels"""
question_ids = [example.meta["question_idx"] for example in examples]
unique_questions = set(question_ids)
q_actuals = list(zip(question_ids, labels))
... | Compute the exact match (EM) for a sequence of predictions and actual labels | multirc_em | python | THUDM/GLM | tasks/superglue/evaluate.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/evaluate.py | MIT |
def __init__(self, args, tokenizer, label_list, max_seq_length, pattern_id: int = 0, verbalizer_file: str = None,
seed: int = 42, is_multi_token=False, max_segment_length=0, fast_decode: bool = False, split='train',
num_prompt_tokens=0):
"""
Create a new PVP.
:... |
Create a new PVP.
:param args: the args
:param tokenizer: the tokenizer
:param label_list: the list of labels
:param max_seq_length: the maximum length of the sequence
:param pattern_id: the pattern id to use
:param seed: a seed to be used for generating random ... | __init__ | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def encode(self, example: InputExample, priming: bool = False, labeled: bool = False):
"""
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming... |
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming=True``, whether the label should be appended to this example
:return: A tuple, consisting... | encode | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def truncate(self, parts_a: List[Tuple[List[int], bool]], parts_b: List[Tuple[List[int], bool]], answer: List[int],
max_length: int):
"""Truncate two sequences of text to a predefined total maximum length"""
total_len = self._seq_length(parts_a) + self._seq_length(parts_b)
if an... | Truncate two sequences of text to a predefined total maximum length | truncate | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def get_verbalization_ids(word: str, tokenizer, force_single_token: bool) -> Union[int, List[int]]:
"""
Get the token ids corresponding to a verbalization
:param word: the verbalization
:param tokenizer: the tokenizer to use
:param force_single_token: whether it should be enforced that the verbaliz... |
Get the token ids corresponding to a verbalization
:param word: the verbalization
:param tokenizer: the tokenizer to use
:param force_single_token: whether it should be enforced that the verbalization corresponds to a single token.
If set to true, this method returns a single int instead of... | get_verbalization_ids | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def search_github_code_byapi(token: str, peer_page: int = 50, page: int = 1, excludes: list = []) -> list[str]:
"""
curl -Ls -o response.json -H "Authorization: Bearer <token>" https://api.github.com/search/code?q=%22%2Fapi%2Fv1%2Fclient%2Fsubscribe%3Ftoken%3D%22&sort=indexed&order=desc&per_page=30&page=1
"... |
curl -Ls -o response.json -H "Authorization: Bearer <token>" https://api.github.com/search/code?q=%22%2Fapi%2Fv1%2Fclient%2Fsubscribe%3Ftoken%3D%22&sort=indexed&order=desc&per_page=30&page=1
| search_github_code_byapi | python | wzdnzd/aggregator | subscribe/crawl.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/crawl.py | Apache-2.0 |
def download_mmdb(repo: str, target: str, filepath: str, retry: int = 3) -> bool:
"""
Download GeoLite2-City.mmdb from github release
"""
repo = utils.trim(text=repo)
if not repo or len(repo.split("/", maxsplit=1)) != 2:
logger.error(f"invalid github repo name: {repo}")
return False
... |
Download GeoLite2-City.mmdb from github release
| download_mmdb | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def download(url: str, filepath: str, filename: str, retry: int = 3) -> bool:
"""Download file from url to filepath with filename"""
if retry < 0:
logger.error(f"archieved max retry count for download, url: {url}")
return False
url = utils.trim(text=url)
if not url:
logger.erro... | Download file from url to filepath with filename | download | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def query_ip_country(ip: str, reader: database.Reader) -> str:
"""
Query country information for an IP address using mmdb database
Args:
ip: The IP address to query
reader: The mmdb database reader
Returns:
The country name in Chinese
"""
if not ip or not reader:
... |
Query country information for an IP address using mmdb database
Args:
ip: The IP address to query
reader: The mmdb database reader
Returns:
The country name in Chinese
| query_ip_country | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def get_listening_ports() -> set:
"""Get the set of listening ports in the system, cross-platform compatible"""
listening_ports = set()
try:
# Windows system
if os.name == "nt":
try:
# Use 'cp437' encoding to handle Windows command line output
out... | Get the set of listening ports in the system, cross-platform compatible | get_listening_ports | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def scan_ports_batch(start_port: int, count: int = 100) -> dict:
"""Batch scan port statuses, return a dictionary of port statuses"""
global _PORT_STATUS_CACHE, _AVAILABLE_PORTS
# Create a list of ports to scan (excluding ports with known status)
ports_to_scan = [p for p in range(start_port, start_port... | Batch scan port statuses, return a dictionary of port statuses | scan_ports_batch | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def check_single_port(port: int) -> bool:
"""Helper function for checking a single port, checks if the port is listening"""
try:
# Use socket to check TCP port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.2)
result = sock.connect_ex(("127.0.0.1", por... | Helper function for checking a single port, checks if the port is listening | check_single_port | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def is_port_in_use(port: int) -> bool:
"""Check if a port is in use (using cache)"""
global _PORT_STATUS_CACHE, _AVAILABLE_PORTS
# If port is known to be available, return directly
if port in _AVAILABLE_PORTS:
return False
# If port status is already cached, return directly
if port in ... | Check if a port is in use (using cache) | is_port_in_use | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def generate_mihomo_config(proxies: list[dict]) -> tuple[dict, dict]:
"""Generate mihomo configuration for the given proxies"""
# Base configuration
config = {
"mixed-port": 7890,
"allow-lan": True,
"mode": "global",
"log-level": "error",
"proxies": proxies,
"... | Generate mihomo configuration for the given proxies | generate_mihomo_config | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def make_proxy_request(port: int, url: str, max_retries: int = 5, timeout: int = 10) -> tuple[bool, dict]:
"""
Make an HTTP request through a proxy and return the response
Args:
port: The port of the proxy
url: The URL to request
max_retries: Maximum number of retry attempts
... |
Make an HTTP request through a proxy and return the response
Args:
port: The port of the proxy
url: The URL to request
max_retries: Maximum number of retry attempts
timeout: Timeout for the request in seconds
Returns:
A tuple of (success, data) where:
- suc... | make_proxy_request | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def get_ipv4(port: int, max_retries: int = 5) -> str:
"""
Get the IPv4 address by accessing https://api.ipify.org?format=json through a proxy
Args:
port: The port of the proxy
max_retries: Maximum number of retry attempts
Returns:
The IPv4 address or empty string if failed
... |
Get the IPv4 address by accessing https://api.ipify.org?format=json through a proxy
Args:
port: The port of the proxy
max_retries: Maximum number of retry attempts
Returns:
The IPv4 address or empty string if failed
| get_ipv4 | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def locate_by_ipinfo(name: str, port: int, reader: database.Reader = None) -> dict:
"""Check the location of a single proxy by making a request through it"""
result = {"name": name, "country": ""}
if not port:
logger.warning(f"No port found for proxy {name}")
return result
if reader:
... | Check the location of a single proxy by making a request through it | locate_by_ipinfo | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def get_messages(self, account: Account) -> list:
"""download a list of messages currently in the account."""
if not account or not self.auth_headers:
return []
content = utils.http_get(
url="{}/messages?page={}".format(self.api_address, 1),
headers=self.auth... | download a list of messages currently in the account. | get_messages | python | wzdnzd/aggregator | subscribe/mailtm.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/mailtm.py | Apache-2.0 |
def delete_account(self, account: Account) -> bool:
"""try to delete the account. returns True if it succeeds."""
if account is None or not self.auth_headers:
return False
try:
request = urllib.request.Request(
url=f"{self.api_address}/accounts/{account.i... | try to delete the account. returns True if it succeeds. | delete_account | python | wzdnzd/aggregator | subscribe/mailtm.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/mailtm.py | Apache-2.0 |
def test_synthetic_arange_random_n_data():
"""Test if correct data quantity is generated by synthetic_arange_random."""
n_list = [10, 20]
for n in n_list:
y_pred, y_std, y_true, x = synthetic_arange_random(n)
assert len(y_pred) == n
assert len(y_std) == n
assert len(y_true) =... | Test if correct data quantity is generated by synthetic_arange_random. | test_synthetic_arange_random_n_data | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_data.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_data.py | MIT |
def test_synthetic_sine_heteroscedastic_n_data():
"""Test if correct data quantity is generated by synthetic_sine_heteroscedastic."""
n_list = [10, 20]
for n in n_list:
y_pred, y_std, y_true, x = synthetic_sine_heteroscedastic(n)
assert len(y_pred) == n
assert len(y_std) == n
... | Test if correct data quantity is generated by synthetic_sine_heteroscedastic. | test_synthetic_sine_heteroscedastic_n_data | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_data.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_data.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.