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 evaluate_and_print_results(prefix, data_iterator, model,
args, timers, forward_step_func, verbose=False, step=None, summary_writer=None):
"""Helper function to evaluate and dump results on screen."""
lm_loss, gpt_loss, bert_loss, sent_loss, multi_loss = evaluate(data_iterator,... | Helper function to evaluate and dump results on screen. | evaluate_and_print_results | python | THUDM/GLM | pretrain_glm.py | https://github.com/THUDM/GLM/blob/master/pretrain_glm.py | MIT |
def get_train_val_test_data(args, tokenizer):
"""Load the data on rank zero and boradcast number of tokens to all GPUS."""
(train_data, val_data, test_data) = (None, None, None)
# Data loader only on rank 0 of each model parallel group.
if mpu.get_model_parallel_rank() == 0:
data_config = confi... | Load the data on rank zero and boradcast number of tokens to all GPUS. | get_train_val_test_data | python | THUDM/GLM | pretrain_glm.py | https://github.com/THUDM/GLM/blob/master/pretrain_glm.py | MIT |
def print_params_min_max_norm(optimizer, iteration):
"""Print min, max, and norm of all parameters."""
index = 0
rank = torch.distributed.get_rank()
string = 'iteration, rank, index, model-parallel,min, max, norm\n'
optimizer_ = optimizer
if isinstance(optimizer, FP16_Optimizer):
optimiz... | Print min, max, and norm of all parameters. | print_params_min_max_norm | python | THUDM/GLM | utils.py | https://github.com/THUDM/GLM/blob/master/utils.py | MIT |
def load_weights(src, dst, dst2src=False):
"""
Loads weights from src to dst via in place copy.
src is a huggingface gpt2model, while dst is one of our models.
dst2src=True loads parameters from our models into huggingface's.
^dst2src is still untested
"""
conv_layer = 'Conv1D' in str(type(s... |
Loads weights from src to dst via in place copy.
src is a huggingface gpt2model, while dst is one of our models.
dst2src=True loads parameters from our models into huggingface's.
^dst2src is still untested
| load_weights | python | THUDM/GLM | utils.py | https://github.com/THUDM/GLM/blob/master/utils.py | MIT |
def move_weights(our, oai, dst2src=False):
"""
Loads weights from `oai` to `our` via in place copy.
`oai` is a huggingface gpt2model, while `our` is one of our models.
dst2src=True loads parameters from our models into huggingface's.
^dst2src=True is still untested
"""
# while isinstance(... |
Loads weights from `oai` to `our` via in place copy.
`oai` is a huggingface gpt2model, while `our` is one of our models.
dst2src=True loads parameters from our models into huggingface's.
^dst2src=True is still untested
| move_weights | python | THUDM/GLM | utils.py | https://github.com/THUDM/GLM/blob/master/utils.py | MIT |
def split_ds(ds, split=None, shuffle=True, save_splits=None, load_splits=None):
"""
Split a dataset into subsets given proportions of how
much to allocate per split. If a split is 0% returns None for that split.
Purpose: Useful for creating train/val/test splits
Arguments:
ds (Dataset or arr... |
Split a dataset into subsets given proportions of how
much to allocate per split. If a split is 0% returns None for that split.
Purpose: Useful for creating train/val/test splits
Arguments:
ds (Dataset or array-like): Data to be split.
split (1D array-like): proportions to split `ds`. `... | split_ds | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def __getitem__(self, index):
"""process+tokenize string and return string,label,and stringlen"""
x = self.X[index]
if self.tokenizer is not None:
x = self.tokenizer.EncodeAsIds(x, self.preprocess_fn)
elif self.preprocess_fn is not None:
x = self.preprocess_fn(x)
... | process+tokenize string and return string,label,and stringlen | __getitem__ | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def write(self, writer_gen=None, path=None, skip_header=False):
"""
given a generator of metrics for each of the data points X_i,
write the metrics, text, and labels to a csv file
"""
if path is None:
path = self.path + '.results'
print('generating csv at ... |
given a generator of metrics for each of the data points X_i,
write the metrics, text, and labels to a csv file
| write | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def __getitem__(self, index):
"""gets the index'th string from the dataset"""
x = self.X[index]
if self.tokenizer is not None:
x = self.tokenizer.EncodeAsIds(x, self.preprocess_fn)
elif self.preprocess_fn is not None:
x = self.preprocess_fn(x)
y = self.Y[i... | gets the index'th string from the dataset | __getitem__ | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def write(self, writer_gen=None, path=None, skip_header=False):
"""
given a generator of metrics for each of the data points X_i,
write the metrics, text, and labels to a json file
"""
if path is None:
path = self.path + '.results'
jsons = []
if ... |
given a generator of metrics for each of the data points X_i,
write the metrics, text, and labels to a json file
| write | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def __init__(self, ds, tokenizer,
max_seq_len=1024,
sample_across_doc=True,
non_sentence_start=0.0, filter_english=False, **kwargs):
"""
sentence_start: the stripped article must start with a complete sentence
"""
self.ds = ds
se... |
sentence_start: the stripped article must start with a complete sentence
| __init__ | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def __init__(self, ds, tokenizer,
max_seq_len=1024,
num_samples=None,
weighted=True,
sample_across_doc=True,
random_across_doc_sampling=True,
sentence_start=False, **kwargs):
"""
sentence_start: the str... |
sentence_start: the stripped article must start with a complete sentence
| __init__ | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def sentence_tokenize(self, sent, sentence_num=0, beginning=False, ending=False):
"""tokenize sentence and get token types"""
tokens = self.tokenizer.EncodeAsIds(sent).tokenization
str_type = 'str' + str(sentence_num)
token_types = [self.tokenizer.get_type(str_type).Id] * len(tokens)
... | tokenize sentence and get token types | sentence_tokenize | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def get_doc(self, idx):
"""gets text of document corresponding to idx"""
rtn = self.ds[idx]
if isinstance(rtn, dict):
rtn = rtn['text']
return rtn | gets text of document corresponding to idx | get_doc | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def create_random_sentencepair(self, target_seq_length, rng, np_rng):
"""
fetches a random sentencepair corresponding to rng state similar to
https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L248-L294
"""
is_random_next = None
curr_strs = []... |
fetches a random sentencepair corresponding to rng state similar to
https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L248-L294
| create_random_sentencepair | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def truncate_seq_pair(self, a, b, max_seq_len, rng):
"""
Truncate sequence pair according to original BERT implementation:
https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L391
"""
tokens_a, token_types_a = a
tokens_b, token_types_b = b
... |
Truncate sequence pair according to original BERT implementation:
https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L391
| truncate_seq_pair | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def mask_token(self, idx, tokens, types, vocab_words, rng):
"""
helper function to mask `idx` token from `tokens` according to
section 3.3.1 of https://arxiv.org/pdf/1810.04805.pdf
"""
label = tokens[idx]
if rng.random() < 0.8:
new_label = self.tokenizer.get_c... |
helper function to mask `idx` token from `tokens` according to
section 3.3.1 of https://arxiv.org/pdf/1810.04805.pdf
| mask_token | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def pad_seq(self, seq):
"""helper function to pad sequence pair"""
num_pad = max(0, self.max_seq_len - len(seq))
pad_mask = [0] * len(seq) + [1] * num_pad
seq += [self.tokenizer.get_command('pad').Id] * num_pad
return seq, pad_mask | helper function to pad sequence pair | pad_seq | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def create_masked_lm_predictions(self, a, b, mask_lm_prob, max_preds_per_seq, vocab_words, rng):
"""
Mask sequence pair for BERT training according to:
https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L338
"""
tokens_a, token_types_a = a
toke... |
Mask sequence pair for BERT training according to:
https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L338
| create_masked_lm_predictions | python | THUDM/GLM | data_utils/datasets.py | https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py | MIT |
def filename_to_url(filename, cache_dir=None):
"""
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
if sys.version_info[... |
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.
| filename_to_url | python | THUDM/GLM | data_utils/file_utils.py | https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py | MIT |
def cached_path(url_or_filename, cache_dir=None):
"""
Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
make sure the file exists and then return the pa... |
Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
make sure the file exists and then return the path.
| cached_path | python | THUDM/GLM | data_utils/file_utils.py | https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py | MIT |
def split_s3_path(url):
"""Split a full s3 path into the bucket name and path."""
parsed = urlparse(url)
if not parsed.netloc or not parsed.path:
raise ValueError("bad s3 path {}".format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
# Remove '/' at beginning of path.
if s3_... | Split a full s3 path into the bucket name and path. | split_s3_path | python | THUDM/GLM | data_utils/file_utils.py | https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py | MIT |
def s3_request(func):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.response["Error"]["... |
Wrapper function for s3 requests in order to create more helpful error
messages.
| s3_request | python | THUDM/GLM | data_utils/file_utils.py | https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py | MIT |
def get_from_cache(url, cache_dir=None):
"""
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
"""
if cache_dir is None:
cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
if sys.version_info[0] == 3 and is... |
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
| get_from_cache | python | THUDM/GLM | data_utils/file_utils.py | https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py | MIT |
def read_set_from_file(filename):
'''
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
'''
collection = set()
with open(filename, 'r', encoding='utf-8') as file_:
for line in file_:
collection.add(line.rstrip())
return co... |
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
| read_set_from_file | python | THUDM/GLM | data_utils/file_utils.py | https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py | MIT |
def exists_lazy(path, data_type='data'):
"""
Check if we've already made a lazy version of this file for the `data_type` field.
"""
if not os.path.exists(get_lazy_path(path)):
return False
contents = os.listdir(get_lazy_path(path))
if data_type not in contents:
return False
i... |
Check if we've already made a lazy version of this file for the `data_type` field.
| exists_lazy | python | THUDM/GLM | data_utils/lazy_loader.py | https://github.com/THUDM/GLM/blob/master/data_utils/lazy_loader.py | MIT |
def SetTokenizer(self, tokenizer):
"""
logic to set and remove (set to None) tokenizer.
combines preprocessing/tokenization into one callable.
"""
if tokenizer is None:
if not hasattr(self, '_tokenizer'):
self._tokenizer = tokenizer
else:
... |
logic to set and remove (set to None) tokenizer.
combines preprocessing/tokenization into one callable.
| SetTokenizer | python | THUDM/GLM | data_utils/lazy_loader.py | https://github.com/THUDM/GLM/blob/master/data_utils/lazy_loader.py | MIT |
def __getitem__(self, index):
"""
read file and splice strings based on string ending array `self.ends`
"""
if not isinstance(index, slice):
if index == 0:
start = 0
else:
start = self.ends[index - 1]
end = self.ends[ind... |
read file and splice strings based on string ending array `self.ends`
| __getitem__ | python | THUDM/GLM | data_utils/lazy_loader.py | https://github.com/THUDM/GLM/blob/master/data_utils/lazy_loader.py | MIT |
def _batch(self, batch):
"""extracts samples only pertaining to this worker's batch"""
start = self.rank*self.batch_size//self.world_size
end = (self.rank+1)*self.batch_size//self.world_size
return batch[start:end] | extracts samples only pertaining to this worker's batch | _batch | python | THUDM/GLM | data_utils/samplers.py | https://github.com/THUDM/GLM/blob/master/data_utils/samplers.py | MIT |
def data_iterator(self, _iter, wrap_around=False):
"""iterates through data and handles wrap around"""
for i, idx in enumerate(_iter):
if i < self.wrap_around%self.batch_size:
continue
if wrap_around:
self.wrap_around += 1
self.wrap... | iterates through data and handles wrap around | data_iterator | python | THUDM/GLM | data_utils/samplers.py | https://github.com/THUDM/GLM/blob/master/data_utils/samplers.py | MIT |
def _batch(self, batch):
"""extracts samples only pertaining to this worker's batch"""
start = self.rank*self.batch_size//self.world_size
end = (self.rank+1)*self.batch_size//self.world_size
return batch[start:end] | extracts samples only pertaining to this worker's batch | _batch | python | THUDM/GLM | data_utils/samplers.py | https://github.com/THUDM/GLM/blob/master/data_utils/samplers.py | MIT |
def make_tokenizer(tokenizer_type, corpus, model_path=None, vocab_size=None, model_type=None, pad_token=0,
character_coverage=1.0, command_tokens=None, type_tokens=None, fix_command_token=False, **kwargs):
"""
Helper function to instantiate a tokenizer given common combinations of options.
... |
Helper function to instantiate a tokenizer given common combinations of options.
| make_tokenizer | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def EncodeAsIds(self, text, process_fn=None):
"""
encode text using text tokenizer and shift Id values for command tokens
"""
processed_text = text
if process_fn is not None:
processed_text = process_fn(processed_text)
def split_on_token(tok_extended: Command... |
encode text using text tokenizer and shift Id values for command tokens
| EncodeAsIds | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def EncodeAsTokens(self, text, process_fn=None):
"""
encode text as tokens using text tokenizer
"""
tokenization = self.text_tokenizer.EncodeAsTokens(text, process_fn=process_fn)
tokenization.set_command_tokens(self._command_tokens)
return tokenization |
encode text as tokens using text tokenizer
| EncodeAsTokens | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def IdToToken(self, Id, type_token=False):
"""convert Id to token accounting for command and type tokens"""
if isinstance(Id, (TypeToken, CommandToken)):
return Id.token
if type_token:
return self.type_id_map[Id].token
if Id < self.num_command_tokens:
... | convert Id to token accounting for command and type tokens | IdToToken | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def TokenToId(self, token, type_token=False):
"""convert token to Id accounting for command and type tokens"""
if isinstance(token, (TypeToken, CommandToken)):
return token.Id
if type_token:
return self.type_token_map[token].Id
if token in self.command_token_map:
... | convert token to Id accounting for command and type tokens | TokenToId | 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):
"""
convert Ids to tokens accounting for command and type tokens, tokens
are joined and returned as a string.
"""
if type_token:
return ' '.join(Id.token if isinstance(Id, TypeToken) else self.type_id_map[Id].token for Id in... |
convert Ids to tokens accounting for command and type tokens, tokens
are joined and returned as a 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):
"""
convert tokens to a string accounting for command and type tokens.
"""
if type_token:
return ' '.join(t.token if isinstance(t, TypeToken) else t for t in Tokens)
rtn_strs = []
current_str = []
if is... |
convert tokens to a string accounting for command and type tokens.
| DecodeTokens | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def DecodeIds(self, Ids):
"""converts ascii ids to tokens before joining them into text"""
if isinstance(Ids, Tokenization):
Ids = Ids.tokenization
return ''.join([self.IdToToken(tok) for tok in Ids]) | converts ascii ids to tokens before joining them into text | DecodeIds | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
def DecodeTokens(self, Tokens):
"""just concatenates ascii tokens into text"""
if isinstance(Tokens, Tokenization):
Tokens = Tokens.tokenization
return ''.join(Tokens) | just concatenates ascii tokens into text | DecodeTokens | python | THUDM/GLM | data_utils/tokenization.py | https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py | MIT |
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 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/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 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.