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_electra_pretraining_model(model_name, ctx_l,
max_seq_length=128,
hidden_dropout_prob=0.1,
attention_dropout_prob=0.1,
generator_units_scale=None,
... |
A Electra Pretrain Model is built with a generator and a discriminator, in which
the generator has the same embedding as the discriminator but different backbone.
| get_electra_pretraining_model | python | dmlc/gluon-nlp | scripts/pretraining/pretraining_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/pretraining_utils.py | Apache-2.0 |
def parameters_option(step_num, model, ckpt_dir, option='Saving'):
"""Save or load the model parameter, marked by step_num."""
param_path = os.path.join(
ckpt_dir, '{}.params'.format(str(step_num).zfill(7)))
logging.info('[step {}], {} model params to/from {}.'.format(
step_num, option, para... | Save or load the model parameter, marked by step_num. | parameters_option | python | dmlc/gluon-nlp | scripts/pretraining/run_electra.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/run_electra.py | Apache-2.0 |
def states_option(step_num, trainer, ckpt_dir, local_rank=0, option='Saving'):
"""Save or load the trainer states, marked by step_num and local rank."""
state_path = os.path.join(ckpt_dir, '{}.states.{}'.format(
str(step_num).zfill(7), str(local_rank).zfill(2)))
logging.info('[step {}], {} trainer s... | Save or load the trainer states, marked by step_num and local rank. | states_option | python | dmlc/gluon-nlp | scripts/pretraining/run_electra.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/run_electra.py | Apache-2.0 |
def transform(instance, max_seq_length):
"""Transform instance to inputs for MLM and NSP."""
input_ids = instance.tokens
assert len(input_ids) <= max_seq_length
segment_ids = instance.segment_ids
masked_lm_positions = instance.masked_lm_positions
valid_lengths = len(input_ids)
masked_lm_ids... | Transform instance to inputs for MLM and NSP. | transform | python | dmlc/gluon-nlp | scripts/pretraining/bert/create_pretraining_data.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/create_pretraining_data.py | Apache-2.0 |
def write_to_files_np(features, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
# pylint: disable=unused-argument
"""Write to numpy files from `TrainingInstance`s."""
next_sentence_labels = []
valid_lengths = []
assert len(output_files) == 1, 'numpy format o... | Write to numpy files from `TrainingInstance`s. | write_to_files_np | python | dmlc/gluon-nlp | scripts/pretraining/bert/create_pretraining_data.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/create_pretraining_data.py | Apache-2.0 |
def tokenize_lines_fn(x):
"""
Worker function to tokenize lines based on the tokenizer, and perform vocabulary lookup.
Parameters
----------
lines
Lines to be tokenized of the whole file
tokenizer
The trained tokenizer
Returns
-------
results
A list storing ... |
Worker function to tokenize lines based on the tokenizer, and perform vocabulary lookup.
Parameters
----------
lines
Lines to be tokenized of the whole file
tokenizer
The trained tokenizer
Returns
-------
results
A list storing the valid tokenized lines
| tokenize_lines_fn | python | dmlc/gluon-nlp | scripts/pretraining/bert/create_pretraining_data.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/create_pretraining_data.py | Apache-2.0 |
def convert_to_npz(instances, max_seq_length):
"""Create masked language model and next sentence prediction samples as numpy arrays."""
input_ids = []
segment_ids = []
masked_lm_positions = []
masked_lm_ids = []
masked_lm_weights = []
next_sentence_labels = []
valid_lengths = []
for... | Create masked language model and next sentence prediction samples as numpy arrays. | convert_to_npz | python | dmlc/gluon-nlp | scripts/pretraining/bert/create_pretraining_data.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/create_pretraining_data.py | Apache-2.0 |
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq,
whole_word_mask, vocab, tokenizer,
_MASK_TOKEN, _CLS_TOKEN, _SEP_TOKEN):
"""Creates the predictions for the masked LM objective."""
cand_indexes = []
for (i, to... | Creates the predictions for the masked LM objective. | create_masked_lm_predictions | python | dmlc/gluon-nlp | scripts/pretraining/bert/create_pretraining_data.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/create_pretraining_data.py | Apache-2.0 |
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens):
"""Truncates a pair of sequences to a maximum sequence length."""
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_num_tokens:
break
trunc_tokens = tokens_a if len(tokens_a) > len(token... | Truncates a pair of sequences to a maximum sequence length. | truncate_seq_pair | python | dmlc/gluon-nlp | scripts/pretraining/bert/create_pretraining_data.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/create_pretraining_data.py | Apache-2.0 |
def prepare_pretrain_npz_dataset(filename, allow_pickle=False):
"""Create dataset based on the numpy npz file"""
if isinstance(filename, (list, tuple)):
assert len(filename) == 1, \
'When .npy/.npz data file is loaded, len(filename) must be 1.' \
' Received len(filename)={}.'.for... | Create dataset based on the numpy npz file | prepare_pretrain_npz_dataset | python | dmlc/gluon-nlp | scripts/pretraining/bert/pretraining_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/pretraining_utils.py | Apache-2.0 |
def prepare_pretrain_text_dataset(filename, tokenizer, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, whole_word_mask,
random_next_sentence, vocab):
"""Create dataset based on the raw text files"""
dupe_factor = 1
... | Create dataset based on the raw text files | prepare_pretrain_text_dataset | python | dmlc/gluon-nlp | scripts/pretraining/bert/pretraining_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/pretraining_utils.py | Apache-2.0 |
def prepare_pretrain_bucket_sampler(dataset, batch_size, shuffle=False, num_buckets=1):
"""Create data sampler based on the dataset"""
if isinstance(dataset, NumpyDataset):
lengths = dataset.get_field('valid_lengths')
else:
lengths = dataset.transform(lambda input_ids, segment_ids, masked_lm... | Create data sampler based on the dataset | prepare_pretrain_bucket_sampler | python | dmlc/gluon-nlp | scripts/pretraining/bert/pretraining_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/pretraining_utils.py | Apache-2.0 |
def get_pretrain_data_npz(data, batch_size,
shuffle, num_buckets,
vocab, num_parts=1, part_idx=0,
num_dataset_workers=1, num_batch_workers=1,
circle_length=1, repeat=1,
dataset_cached=False,... | Get a data iterator from pre-processed npz files.
Parameters
----------
batch_size : int
The batch size per GPU.
shuffle : bool
Whether to shuffle the data.
num_buckets : int
The number of buckets for the FixedBucketSampler for training.
vocab : Vocab
The vocabul... | get_pretrain_data_npz | python | dmlc/gluon-nlp | scripts/pretraining/bert/pretraining_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/pretraining_utils.py | Apache-2.0 |
def parameters_option(step_num, model, ckpt_dir, option='Saving', ctx_l=None):
"""Save or load the model parameter, marked by step_num."""
param_path = os.path.join(
ckpt_dir, '{}.params'.format(str(step_num).zfill(7)))
logging.info('[step {}], {} model params to/from {}.'.format(
step_num, ... | Save or load the model parameter, marked by step_num. | parameters_option | python | dmlc/gluon-nlp | scripts/pretraining/bert/run_pretraining.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/run_pretraining.py | Apache-2.0 |
def states_option(step_num, trainer, ckpt_dir, local_rank=0, option='Saving'):
"""Save or load the trainer states, marked by step_num and local rank."""
state_path = os.path.join(ckpt_dir, '{}.states.{}'.format(
str(step_num).zfill(7), str(local_rank).zfill(2)))
logging.info('[step {}], {} trainer s... | Save or load the trainer states, marked by step_num and local rank. | states_option | python | dmlc/gluon-nlp | scripts/pretraining/bert/run_pretraining.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/bert/run_pretraining.py | Apache-2.0 |
def create_masked_lm_predictions(*, args, tokens, cls_token_id, sep_token_id, mask_token_id,
non_special_ids):
"""Creates the predictions for the masked LM objective."""
cand_indexes = [i for i, tok in enumerate(tokens) if tok not in (cls_token_id, sep_token_id)]
output_toke... | Creates the predictions for the masked LM objective. | create_masked_lm_predictions | python | dmlc/gluon-nlp | scripts/pretraining/torch/bert/prepare_quickthought.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/torch/bert/prepare_quickthought.py | Apache-2.0 |
def _initializer(function):
"""Initialize state of each process in multiprocessing pool.
The process local state is stored as an attribute of the function
object, which is specified in Pool(..., initargs=(function, )) and by
convention refers to the function executed during map.
... | Initialize state of each process in multiprocessing pool.
The process local state is stored as an attribute of the function
object, which is specified in Pool(..., initargs=(function, )) and by
convention refers to the function executed during map.
| _initializer | python | dmlc/gluon-nlp | scripts/pretraining/torch/bert/prepare_quickthought.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/torch/bert/prepare_quickthought.py | Apache-2.0 |
def parameters_option(step_num, model, args, option='Saving', ctx_l=None):
"""Save or load the model parameter, marked by step_num."""
param_path = os.path.join(args.ckpt_dir, f'{step_num:07}.params')
logging.info(f'[Step {step_num}], {option} model params to/from {param_path}.')
if option == 'Saving':
... | Save or load the model parameter, marked by step_num. | parameters_option | python | dmlc/gluon-nlp | scripts/pretraining/torch/bert/run_pretraining.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/torch/bert/run_pretraining.py | Apache-2.0 |
def states_option(step_num, optimizer, args, option='Saving'):
"""Save or load the trainer states, marked by step_num and local rank."""
state_path = os.path.join(args.ckpt_dir, f'{step_num:07}.states.{args.local_rank:02}')
logging.info(f'[Step {step_num}], {option} trainer states to/from {state_path}.')
... | Save or load the trainer states, marked by step_num and local rank. | states_option | python | dmlc/gluon-nlp | scripts/pretraining/torch/bert/run_pretraining.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/pretraining/torch/bert/run_pretraining.py | Apache-2.0 |
def check_both_latin1(src_sentence: str, tgt_sentence: str) -> bool:
"""Check whether the sentence pair can all be encoded in latin1
This is used in
https://github.com/mlperf/training/blob/master/rnn_translator/pytorch/scripts/filter_dataset.py
The idea is to filter the sentences with rare unicode gly... | Check whether the sentence pair can all be encoded in latin1
This is used in
https://github.com/mlperf/training/blob/master/rnn_translator/pytorch/scripts/filter_dataset.py
The idea is to filter the sentences with rare unicode glyphs and are unlikely to be en-de
Returns
-------
ret
Wh... | check_both_latin1 | python | dmlc/gluon-nlp | scripts/processing/clean_tok_corpus.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/processing/clean_tok_corpus.py | Apache-2.0 |
def check_latin1(sentence: str) -> bool:
"""Check whether the sentence can be encoded in latin1
This is used in
https://github.com/mlperf/training/blob/master/rnn_translator/pytorch/scripts/filter_dataset.py
The idea is to filter the sentences with rare unicode glyphs
Returns
-------
ret
... | Check whether the sentence can be encoded in latin1
This is used in
https://github.com/mlperf/training/blob/master/rnn_translator/pytorch/scripts/filter_dataset.py
The idea is to filter the sentences with rare unicode glyphs
Returns
-------
ret
Whether sentences are latin1
| check_latin1 | python | dmlc/gluon-nlp | scripts/processing/clean_tok_corpus.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/processing/clean_tok_corpus.py | Apache-2.0 |
def get_line_byte_start(corpus_path: str) -> np.ndarray:
"""Get the start position of each lines in terms of bytes so that we can use seek + read to
load an arbitrary line.
Parameters
----------
corpus_path
The path of the corpus
Returns
-------
line_pos
Shape (#Lens +... | Get the start position of each lines in terms of bytes so that we can use seek + read to
load an arbitrary line.
Parameters
----------
corpus_path
The path of the corpus
Returns
-------
line_pos
Shape (#Lens + 1,)
| get_line_byte_start | python | dmlc/gluon-nlp | scripts/processing/clean_tok_corpus.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/processing/clean_tok_corpus.py | Apache-2.0 |
def process_parallel_corpus(self, src_corpus_paths: List[str],
tgt_corpus_paths: List[str],
src_out_path: str, tgt_out_path: str,
chunk_size: int = 1024 * 1024,
num_process: int = 8) -> int:
... | Preprocess the parallel corpus
Parameters
----------
src_corpus_paths
Source corpus paths
tgt_corpus_paths
Target corpus paths
src_out_path
Write the results to the source output path
tgt_out_path
Write the results to the t... | process_parallel_corpus | python | dmlc/gluon-nlp | scripts/processing/clean_tok_corpus.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/processing/clean_tok_corpus.py | Apache-2.0 |
def process_mono_corpus(self,
corpus_paths: List[str],
out_path: str,
chunk_size: int = 1024 * 1024,
num_process: int = 8) -> int:
"""Preprocess the mono corpus
Parameters
----------
... | Preprocess the mono corpus
Parameters
----------
corpus_paths
Corpus paths
out_path
Write the results to the output path
chunk_size
Approximately split the corpus files into multiple chunks
num_process
The number of process... | process_mono_corpus | python | dmlc/gluon-nlp | scripts/processing/clean_tok_corpus.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/processing/clean_tok_corpus.py | Apache-2.0 |
def calc_approx_error(expected_tensor: np.ndarray, observed_tensor: np.ndarray) -> float:
'''
Calculating relative error for one tensor
'''
error = observed_tensor - expected_tensor
absolute_error = np.abs(error)
mean_absolute_error = absolute_error.mean()
mean_expected_value = np.abs(expect... |
Calculating relative error for one tensor
| calc_approx_error | python | dmlc/gluon-nlp | scripts/question_answering/custom_strategy.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/custom_strategy.py | Apache-2.0 |
def get_approx_errors(expected_tensors, observed_tensors):
'''
Calculating relative error for multiple tensors: Dict[tensors_name: str, tensor: np.ndarray]
'''
errors = {}
for node_name in observed_tensors.keys():
expected_tensor = expected_tensors[node_name][node_name]
observed_tens... |
Calculating relative error for multiple tensors: Dict[tensors_name: str, tensor: np.ndarray]
| get_approx_errors | python | dmlc/gluon-nlp | scripts/question_answering/custom_strategy.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/custom_strategy.py | Apache-2.0 |
def get_qtensors(self, quant_cfg, node_list):
'''
Generating quantized model based on configuration and capturing intermediate tensors
'''
qmodel = self.adaptor.quantize(quant_cfg, self.model, self.calib_dataloader)
tensors = self.adaptor.inspect_tensor(qmodel, self.calib_dataloa... |
Generating quantized model based on configuration and capturing intermediate tensors
| get_qtensors | python | dmlc/gluon-nlp | scripts/question_answering/custom_strategy.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/custom_strategy.py | Apache-2.0 |
def bayesian_params_to_tune_configs(self, params):
'''
Creating configuration from params - changing configurations' indexes for real configurations
'''
node_cfgs = {}
for node_key, configs in self.opwise_quant_cfgs.items():
if node_key in params:
valu... |
Creating configuration from params - changing configurations' indexes for real configurations
| bayesian_params_to_tune_configs | python | dmlc/gluon-nlp | scripts/question_answering/custom_strategy.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/custom_strategy.py | Apache-2.0 |
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_pun... | Lower text and remove punctuation, articles and extra whitespace. | normalize_answer | python | dmlc/gluon-nlp | scripts/question_answering/eval_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/eval_utils.py | Apache-2.0 |
def compute_f1(a_gold, a_pred):
"""
Compute the token-level f1 scores in which the common tokens are considered
as True Positives. Precision and recall are percentages of the number of
common tokens in the prediction and groud truth, respectively.
"""
gold_toks = get_tokens(a_gold)
pred_toks... |
Compute the token-level f1 scores in which the common tokens are considered
as True Positives. Precision and recall are percentages of the number of
common tokens in the prediction and groud truth, respectively.
| compute_f1 | python | dmlc/gluon-nlp | scripts/question_answering/eval_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/eval_utils.py | Apache-2.0 |
def find_best_thresh(preds, scores, na_probs, qid_to_has_ans):
"""
Find the best threshold of the raw scores.
The initial score is set to the number of unanswerable questions,
assuming that each unanswerable question is successfully predicted.
In the following traverse, the best threshold is consta... |
Find the best threshold of the raw scores.
The initial score is set to the number of unanswerable questions,
assuming that each unanswerable question is successfully predicted.
In the following traverse, the best threshold is constantly adjusted
according to the difference from the assumption ('di... | find_best_thresh | python | dmlc/gluon-nlp | scripts/question_answering/eval_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/eval_utils.py | Apache-2.0 |
def revise_unanswerable(preds, na_probs, na_prob_thresh):
"""
Revise the predictions results and return a null string for unanswerable question
whose unanswerable probability above the threshold.
Parameters
----------
preds: dict
A dictionary of full prediction of spans
na_probs: di... |
Revise the predictions results and return a null string for unanswerable question
whose unanswerable probability above the threshold.
Parameters
----------
preds: dict
A dictionary of full prediction of spans
na_probs: dict
A dictionary of unanswerable probabilities
na_prob... | revise_unanswerable | python | dmlc/gluon-nlp | scripts/question_answering/eval_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/eval_utils.py | Apache-2.0 |
def squad_eval(data_file, preds, na_probs, na_prob_thresh=0.0, revise=False):
"""
Parameters
----------
data_file
dataset(list) or data_file(str)
preds
predictions dictionary
na_probs
probabilities dictionary of unanswerable
na_prob_thresh
threshold of unansw... |
Parameters
----------
data_file
dataset(list) or data_file(str)
preds
predictions dictionary
na_probs
probabilities dictionary of unanswerable
na_prob_thresh
threshold of unanswerable
revise
Wether to get the final predictions with impossible answers... | squad_eval | python | dmlc/gluon-nlp | scripts/question_answering/eval_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/eval_utils.py | Apache-2.0 |
def forward(self, tokens, token_types, valid_length, p_mask):
"""
Parameters
----------
tokens
Shape (batch_size, seq_length)
The merged input tokens
token_types
Shape (batch_size, seq_length)
Token types for the sequences, used to... |
Parameters
----------
tokens
Shape (batch_size, seq_length)
The merged input tokens
token_types
Shape (batch_size, seq_length)
Token types for the sequences, used to indicate whether the word belongs to the
first sentence or t... | forward | python | dmlc/gluon-nlp | scripts/question_answering/models.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/models.py | Apache-2.0 |
def inference(self, tokens, token_types, valid_length, p_mask,
start_top_n: int = 5, end_top_n: int = 5):
"""Get the inference result with beam search
Parameters
----------
tokens
The input tokens. Shape (batch_size, sequence_length)
token_types
... | Get the inference result with beam search
Parameters
----------
tokens
The input tokens. Shape (batch_size, sequence_length)
token_types
The input token types. Shape (batch_size, sequence_length)
valid_length
The valid length of the tokens. Sh... | inference | python | dmlc/gluon-nlp | scripts/question_answering/models.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/models.py | Apache-2.0 |
def get_end_logits(self, contextual_embedding, start_positions, p_mask):
"""
Parameters
----------
contextual_embedding
Shape (batch_size, sequence_length, C)
start_positions
Shape (batch_size, N)
We process multiple candidates simultaneously
... |
Parameters
----------
contextual_embedding
Shape (batch_size, sequence_length, C)
start_positions
Shape (batch_size, N)
We process multiple candidates simultaneously
p_mask
Shape (batch_size, sequence_length)
Returns
... | get_end_logits | python | dmlc/gluon-nlp | scripts/question_answering/models.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/models.py | Apache-2.0 |
def get_answerable_logits(self, contextual_embedding, p_mask):
"""Get the answerable logits.
Parameters
----------
contextual_embedding
Shape (batch_size, sequence_length, C)
p_mask
Shape (batch_size, sequence_length)
Mask the sequence.
... | Get the answerable logits.
Parameters
----------
contextual_embedding
Shape (batch_size, sequence_length, C)
p_mask
Shape (batch_size, sequence_length)
Mask the sequence.
0 --> Denote that the element is masked,
1 --> Denote th... | get_answerable_logits | python | dmlc/gluon-nlp | scripts/question_answering/models.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/models.py | Apache-2.0 |
def forward(self, tokens, token_types, valid_length, p_mask, start_position):
"""
Parameters
----------
tokens
Shape (batch_size, sequence_length)
token_types
Shape (batch_size, sequence_length)
valid_length
Shape (batch_size,)
... |
Parameters
----------
tokens
Shape (batch_size, sequence_length)
token_types
Shape (batch_size, sequence_length)
valid_length
Shape (batch_size,)
p_mask
Shape (batch_size, sequence_length)
start_position
... | forward | python | dmlc/gluon-nlp | scripts/question_answering/models.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/models.py | Apache-2.0 |
def inference(self, tokens, token_types, valid_length, p_mask,
start_top_n: int = 5, end_top_n: int = 5):
"""Get the inference result with beam search
Parameters
----------
tokens
The input tokens. Shape (batch_size, sequence_length)
token_types
... | Get the inference result with beam search
Parameters
----------
tokens
The input tokens. Shape (batch_size, sequence_length)
token_types
The input token types. Shape (batch_size, sequence_length)
valid_length
The valid length of the tokens. Sh... | inference | python | dmlc/gluon-nlp | scripts/question_answering/models.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/models.py | Apache-2.0 |
def __init__(self, tokenizer, doc_stride, max_seq_length, max_query_length):
"""
Parameters
----------
tokenizer
The tokenizer
doc_stride
The stride to chunk the document
max_seq_length
Maximum length of the merged data
max_que... |
Parameters
----------
tokenizer
The tokenizer
doc_stride
The stride to chunk the document
max_seq_length
Maximum length of the merged data
max_query_length
Maximum query length
| __init__ | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def process_sample(self, feature: SquadFeature):
"""Process the data to the following format.
Note that we mask all the special tokens except the CLS token. The reason for not masking
the CLS token is that if the question is not answerable, we will set the start and end to
be 0.
... | Process the data to the following format.
Note that we mask all the special tokens except the CLS token. The reason for not masking
the CLS token is that if the question is not answerable, we will set the start and end to
be 0.
Merged: <CLS> Question <SEP> Context <SEP>
S... | process_sample | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def get_train(self, features, skip_unreliable=True):
"""Get the training dataset
Parameters
----------
features
skip_unreliable
Whether to skip the unreliable spans in the training set
Returns
-------
train_dataset
num_token_answer_mi... | Get the training dataset
Parameters
----------
features
skip_unreliable
Whether to skip the unreliable spans in the training set
Returns
-------
train_dataset
num_token_answer_mismatch
num_unreliable
| get_train | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def get_squad_features(args, tokenizer, segment):
"""
Get processed data features of SQuADExampls
Parameters
----------
args : argparse.Namespace
tokenizer:
Tokenizer instance
segment: str
train or dev
Returns
-------
data_features
The list of processed ... |
Get processed data features of SQuADExampls
Parameters
----------
args : argparse.Namespace
tokenizer:
Tokenizer instance
segment: str
train or dev
Returns
-------
data_features
The list of processed data features
| get_squad_features | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def get_network(model_name,
ctx_l,
dropout=0.1,
checkpoint_path=None,
backbone_path=None,
dtype='float32'):
"""
Get the network that fine-tune the Question Answering Task
Parameters
----------
model_name : str
T... |
Get the network that fine-tune the Question Answering Task
Parameters
----------
model_name : str
The model name of the backbone model
ctx_l :
Context list of training device like [mx.gpu(0), mx.gpu(1)]
dropout : float
Dropout probability of the task specified layer
... | get_network | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def setup_logging(args, local_rank):
"""
Setup logging configuration as well as random seed
"""
logging_config(args.output_dir,
name='finetune_squad{}'.format(args.version),# avoid race
overwrite_handler=True,
console=(local_rank == 0))
loggin... |
Setup logging configuration as well as random seed
| setup_logging | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def predict_extended(original_feature,
chunked_features,
results,
n_best_size,
max_answer_length=64,
start_top_n=5,
end_top_n=5):
"""Get prediction results for SQuAD.
Start Logits: (B, ... | Get prediction results for SQuAD.
Start Logits: (B, N_start)
End Logits: (B, N_start, N_end)
Parameters
----------
original_feature:
The original SquadFeature before chunked
chunked_features
List of ChunkFeatures
results
List of model predictions for span start and ... | predict_extended | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def collect(self, name, op_name, arr):
"""Callback function for collecting min and max values from an NDArray."""
if name not in self.include_layers:
return
arr = arr.copyto(mx.cpu()).asnumpy()
min_range = np.min(arr)
max_range = np.max(arr)
if (name.find("sg... | Callback function for collecting min and max values from an NDArray. | collect | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def eval_validation(ckpt_name, best_eval):
"""
Model inference during validation or final evaluation.
"""
dev_dataloader = mx.gluon.data.DataLoader(
dev_all_chunk_features,
batchify_fn=dataset_processor.BatchifyFunction,
batch_size=args.eval_batch_size... |
Model inference during validation or final evaluation.
| eval_validation | python | dmlc/gluon-nlp | scripts/question_answering/run_squad.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad.py | Apache-2.0 |
def __init__(self, tokenizer, doc_stride, max_seq_length, max_query_length):
"""
Parameters
----------
tokenizer
The tokenizer
doc_stride
The stride to chunk the document
max_seq_length
Maximum length of the merged data
max_que... |
Parameters
----------
tokenizer
The tokenizer
doc_stride
The stride to chunk the document
max_seq_length
Maximum length of the merged data
max_query_length
Maximum query length
| __init__ | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def process_sample(self, feature: SquadFeature):
"""Process the data to the following format.
Note that we mask all the special tokens except the CLS token. The reason for not masking
the CLS token is that if the question is not answerable, we will set the start and end to
be 0.
... | Process the data to the following format.
Note that we mask all the special tokens except the CLS token. The reason for not masking
the CLS token is that if the question is not answerable, we will set the start and end to
be 0.
Merged: <CLS> Question <SEP> Context <SEP>
S... | process_sample | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def get_train(self, features, skip_unreliable=True):
"""Get the training dataset
Parameters
----------
features
skip_unreliable
Whether to skip the unreliable spans in the training set
Returns
-------
train_dataset
num_token_answer_mi... | Get the training dataset
Parameters
----------
features
skip_unreliable
Whether to skip the unreliable spans in the training set
Returns
-------
train_dataset
num_token_answer_mismatch
num_unreliable
| get_train | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def get_squad_features(args, tokenizer, segment):
"""
Get processed data features of SQuADExampls
Parameters
----------
args : argparse.Namespace
tokenizer:
Tokenizer instance
segment: str
train or dev
Returns
-------
data_features
The list of processed ... |
Get processed data features of SQuADExampls
Parameters
----------
args : argparse.Namespace
tokenizer:
Tokenizer instance
segment: str
train or dev
Returns
-------
data_features
The list of processed data features
| get_squad_features | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def get_network(model_name,
ctx_l,
dropout=0.1,
checkpoint_path=None,
backbone_path=None,
dtype='float32'):
"""
Get the network that fine-tune the Question Answering Task
Parameters
----------
model_name : str
T... |
Get the network that fine-tune the Question Answering Task
Parameters
----------
model_name : str
The model name of the backbone model
ctx_l :
Context list of training device like [mx.gpu(0), mx.gpu(1)]
dropout : float
Dropout probability of the task specified layer
... | get_network | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def setup_logging(args, local_rank):
"""
Setup logging configuration as well as random seed
"""
logging_config(args.output_dir,
name='finetune_squad{}'.format(args.version), # avoid race
overwrite_handler=True,
console=(local_rank == 0))
logg... |
Setup logging configuration as well as random seed
| setup_logging | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def predict_extended(original_feature,
chunked_features,
results,
n_best_size,
max_answer_length=64,
start_top_n=5,
end_top_n=5):
"""Get prediction results for SQuAD.
Start Logits: (B, ... | Get prediction results for SQuAD.
Start Logits: (B, N_start)
End Logits: (B, N_start, N_end)
Parameters
----------
original_feature:
The original SquadFeature before chunked
chunked_features
List of ChunkFeatures
results
List of model predictions for span start and ... | predict_extended | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def eval_validation(backbone):
"""
Model inference during validation or final evaluation.
"""
del qa_net.quantized_backbone
qa_net.quantized_backbone = backbone
dev_dataloader = mx.gluon.data.DataLoader(
dev_all_chunk_features,
batchify_fn... |
Model inference during validation or final evaluation.
| eval_validation | python | dmlc/gluon-nlp | scripts/question_answering/run_squad_albert.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/run_squad_albert.py | Apache-2.0 |
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace.
This is from the official evaluate-v2.0.py in SQuAD.
"""
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
def white_space_fix(te... | Lower text and remove punctuation, articles and extra whitespace.
This is from the official evaluate-v2.0.py in SQuAD.
| normalize_answer | python | dmlc/gluon-nlp | scripts/question_answering/squad_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/squad_utils.py | Apache-2.0 |
def get_chunks(self, doc_stride, max_chunk_length=None):
"""Get a sequence of chunks for the squad feature.
In reality, the document will be too long for the NLP model, and we will split it into
multiple chunks.
For example, consider the following
Doc: the man went to the store... | Get a sequence of chunks for the squad feature.
In reality, the document will be too long for the NLP model, and we will split it into
multiple chunks.
For example, consider the following
Doc: the man went to the store and bought a gallon of milk
We may divide it into four chu... | get_chunks | python | dmlc/gluon-nlp | scripts/question_answering/squad_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/squad_utils.py | Apache-2.0 |
def get_squad_examples_from_json(json_file: str, is_training: bool) -> List[SquadExample]:
"""
Read the whole entry of raw json file and convert it to examples.
Parameters
----------
json_file
The path to the json file
is_training
Whether or not training
Returns
-------... |
Read the whole entry of raw json file and convert it to examples.
Parameters
----------
json_file
The path to the json file
is_training
Whether or not training
Returns
-------
ret
List of SquadExample objects
| get_squad_examples_from_json | python | dmlc/gluon-nlp | scripts/question_answering/squad_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/squad_utils.py | Apache-2.0 |
def get_squad_examples(data_dir, segment='train', version='1.1'):
"""
Parameters
----------
data_dir
The directory of the data
segment
The segment
version
Version of the SQuAD
Returns
-------
examples
A list of SquadExampls objects
"""
if ver... |
Parameters
----------
data_dir
The directory of the data
segment
The segment
version
Version of the SQuAD
Returns
-------
examples
A list of SquadExampls objects
| get_squad_examples | python | dmlc/gluon-nlp | scripts/question_answering/squad_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/squad_utils.py | Apache-2.0 |
def convert_squad_example_to_feature(example: SquadExample,
tokenizer: BaseTokenizerWithVocab,
is_training: bool):
"""
Convert a SquadExample object to a SquadFeature object with the designated tokenizer.
There are accually few examp... |
Convert a SquadExample object to a SquadFeature object with the designated tokenizer.
There are accually few examples can not be converted properly with token level tokenization,
due to the ground-truth are given by the start position and the answer text, and some examples
are annotated with wrong lab... | convert_squad_example_to_feature | python | dmlc/gluon-nlp | scripts/question_answering/squad_utils.py | https://github.com/dmlc/gluon-nlp/blob/master/scripts/question_answering/squad_utils.py | Apache-2.0 |
def gen_self_attn_mask(data,
valid_length=None,
dtype: type = np.float32,
attn_type: str = 'full',
layout: str = 'NT'):
"""Generate the mask used for the encoder, i.e, self-attention.
In our implementation, 1 --> not ma... | Generate the mask used for the encoder, i.e, self-attention.
In our implementation, 1 --> not masked, 0 --> masked
Let's consider the data with two samples:
.. code-block:: none
data =
[['I', 'can', 'now', 'use', 'numpy', 'in', 'Gluon@@', 'NLP' ],
['May', 'the', 'f... | gen_self_attn_mask | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def gen_mem_attn_mask(mem, mem_valid_length, data, data_valid_length=None,
dtype=np.float32, layout: str = 'NT'):
"""Generate the mask used for the decoder. All query slots are attended to the memory slots.
In our implementation, 1 --> not masked, 0 --> masked
Let's consider the data... | Generate the mask used for the decoder. All query slots are attended to the memory slots.
In our implementation, 1 --> not masked, 0 --> masked
Let's consider the data + mem with a batch of two samples:
.. code-block:: none
mem = [['I', 'can', 'now', 'use'],
['May', 'the', 'fo... | gen_mem_attn_mask | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def masked_softmax(att_score, mask, axis: int = -1, temperature=None):
"""Ignore the masked elements when calculating the softmax. The mask can be broadcastable.
Parameters
----------
att_score : Symbol or NDArray
Shape (..., length, ...)
mask : Symbol or NDArray or None
Shape (...,... | Ignore the masked elements when calculating the softmax. The mask can be broadcastable.
Parameters
----------
att_score : Symbol or NDArray
Shape (..., length, ...)
mask : Symbol or NDArray or None
Shape (..., length, ...)
1 --> The element is not masked
0 --> The elemen... | masked_softmax | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def masked_logsoftmax(att_score, mask, axis: int = -1):
"""Ignore the masked elements when calculating the softmax. The mask can be broadcastable.
Parameters
----------
att_score : Symborl or NDArray
Shape (..., length, ...)
mask : Symbol or NDArray or None
Shape (..., length, ...)
... | Ignore the masked elements when calculating the softmax. The mask can be broadcastable.
Parameters
----------
att_score : Symborl or NDArray
Shape (..., length, ...)
mask : Symbol or NDArray or None
Shape (..., length, ...)
mask = 1 --> not masked
mask = 0 --> masked
... | masked_logsoftmax | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def multi_head_dot_attn(query, key, value,
mask=None,
edge_scores=None,
dropout: float = 0.0,
scaled: bool = True, normalized: bool = False,
eps: float = 1E-6, query_head_units: Optional[int] = None,
... | Multihead dot product attention between the query, key, value.
scaled is False, normalized is False:
D(h_q, h_k) = <h_q, h_k>
scaled is True, normalized is False:
D(h_q, h_k) = <h_q, h_k> / sqrt(dim_q)
scaled is False, normalized is True:
D(h_q, h_k) = <h_q / ||h_q||, h_k / ||h_k||>... | multi_head_dot_attn | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def gen_rel_position(data, past_data=None, dtype=np.int32, layout='NT'):
"""Create a matrix of relative position for RelAttentionScoreCell.
The relative position is defined as the index difference: `mem_i` - `query_j`.
Note, though, that the implementation here makes sense in self-attention's settin... | Create a matrix of relative position for RelAttentionScoreCell.
The relative position is defined as the index difference: `mem_i` - `query_j`.
Note, though, that the implementation here makes sense in self-attention's setting,
but not in cross-attention's. Hence, both `mem_i` and `query_j` are time ... | gen_rel_position | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def __init__(self, query_units,
num_heads,
pos_embed_units: Optional[int] = None,
max_distance=None,
bidirectional=False,
num_buckets=None,
method='transformer_xl',
dropout: float = 0.0,
... |
Parameters
----------
query_units
num_heads
pos_embed_units
max_distance
bidirectional
num_buckets
method
dropout
dtype
layout
use_einsum
| __init__ | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def forward(self, rel_positions, query=None):
"""Forward function
Parameters
----------
rel_positions
The relative shifts. Shape (query_length, mem_length).
Each element represents the shift between the :math:`i-th` element of query and
the :math:`j-t... | Forward function
Parameters
----------
rel_positions
The relative shifts. Shape (query_length, mem_length).
Each element represents the shift between the :math:`i-th` element of query and
the :math:`j-th` element of memory.
query
The query... | forward | python | dmlc/gluon-nlp | src/gluonnlp/attention_cell.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/attention_cell.py | Apache-2.0 |
def get_home_dir():
"""Get home directory for storing datasets/models/pre-trained word embeddings"""
_home_dir = os.environ.get('GLUONNLP_HOME', os.path.join('~', '.gluonnlp'))
# expand ~ to actual path
_home_dir = os.path.expanduser(_home_dir)
return _home_dir | Get home directory for storing datasets/models/pre-trained word embeddings | get_home_dir | python | dmlc/gluon-nlp | src/gluonnlp/base.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/base.py | Apache-2.0 |
def get_data_home_dir():
"""Get home directory for storing the datasets"""
home_dir = get_home_dir()
return os.path.join(home_dir, 'datasets') | Get home directory for storing the datasets | get_data_home_dir | python | dmlc/gluon-nlp | src/gluonnlp/base.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/base.py | Apache-2.0 |
def get_model_zoo_home_dir():
"""Get the local directory for storing pretrained models"""
home_dir = get_home_dir()
return os.path.join(home_dir, 'models') | Get the local directory for storing pretrained models | get_model_zoo_home_dir | python | dmlc/gluon-nlp | src/gluonnlp/base.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/base.py | Apache-2.0 |
def get_model_zoo_checksum_dir():
"""Get the directory that stores the checksums of the artifacts in the model zoo """
curr_dir = os.path.realpath(os.path.dirname(os.path.realpath(__file__)))
check_sum_dir = os.path.join(curr_dir, 'models', 'model_zoo_checksums')
return check_sum_dir | Get the directory that stores the checksums of the artifacts in the model zoo | get_model_zoo_checksum_dir | python | dmlc/gluon-nlp | src/gluonnlp/base.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/base.py | Apache-2.0 |
def get_repo_url():
"""Return the base URL for Gluon dataset and model repository """
default_repo = 's3://gluonnlp-numpy-data'
repo_url = os.environ.get('GLUONNLP_REPO_URL', default_repo)
if repo_url[-1] != '/':
repo_url = repo_url + '/'
return repo_url | Return the base URL for Gluon dataset and model repository | get_repo_url | python | dmlc/gluon-nlp | src/gluonnlp/base.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/base.py | Apache-2.0 |
def get_repo_model_zoo_url():
"""Return the base URL for GluonNLP Model Zoo"""
repo_url = get_repo_url()
model_zoo_url = repo_url + 'models/'
return model_zoo_url | Return the base URL for GluonNLP Model Zoo | get_repo_model_zoo_url | python | dmlc/gluon-nlp | src/gluonnlp/base.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/base.py | Apache-2.0 |
def get_norm_layer(normalization: str = 'layer_norm',
axis: int = -1,
epsilon: float = 1e-5,
in_channels: int = 0, **kwargs):
"""
Get the normalization layer based on the type
Parameters
----------
normalization
The type of the layer ... |
Get the normalization layer based on the type
Parameters
----------
normalization
The type of the layer normalization from ['layer_norm', 'no_norm', 'batch_norm']
axis
The axis to normalize the
epsilon
The epsilon of the normalization layer
in_channels
Input... | get_norm_layer | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def _fmt_and_check_cutoffs(cutoffs, vocab_size):
"""Parse and get the cutoffs used in adaptive embedding + adaptive softmax
Parameters
----------
cutoffs
The cutoffs of the
vocab_size
Size of the vocabulary
Returns
-------
cutoffs
The parsed cutoffs, will be [0,... | Parse and get the cutoffs used in adaptive embedding + adaptive softmax
Parameters
----------
cutoffs
The cutoffs of the
vocab_size
Size of the vocabulary
Returns
-------
cutoffs
The parsed cutoffs, will be [0, c0, c1, ..., c_{k-1}, V]
If the original cutoff... | _fmt_and_check_cutoffs | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def get_activation(act: Optional[Union[str, HybridBlock]]) -> HybridBlock:
"""Get the activation based on the string
Parameters
----------
act
The activation
Returns
-------
ret
The activation layer
"""
if act is None:
return lambda x: x
if isinstance(a... | Get the activation based on the string
Parameters
----------
act
The activation
Returns
-------
ret
The activation layer
| get_activation | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def __init__(self, units: int, dtype: Union[str, type] = 'float32'):
"""Use a geometric sequence of timescales.
Parameters
----------
units
The number of units for positional embedding
dtype
The dtype of the inner positional embeddings
"""
... | Use a geometric sequence of timescales.
Parameters
----------
units
The number of units for positional embedding
dtype
The dtype of the inner positional embeddings
| __init__ | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def forward(self, positions):
"""
Parameters
----------
positions : NDArray
Shape (..., )
Returns
-------
ret :
Shape (..., units)
"""
emb = np.expand_dims(positions.astype(self._dtype), axis=-1) * self.base_mult.data()
... |
Parameters
----------
positions : NDArray
Shape (..., )
Returns
-------
ret :
Shape (..., units)
| forward | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def __init__(self,
units: int = 512,
hidden_size: int = 2048,
use_bias=True,
activation_dropout: float = 0.0,
dropout: float = 0.1,
weight_initializer=None,
bias_initializer='zeros',
a... |
Parameters
----------
units
hidden_size
activation_dropout
dropout
weight_initializer
bias_initializer
activation
normalization
layer_norm or no_norm
layer_norm_eps
pre_norm
Pre-layer normalization ... | __init__ | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def forward(self, data):
"""
Parameters
----------
F
data :
Shape (B, seq_length, C_in)
Returns
-------
out :
Shape (B, seq_length, C_out)
"""
residual = data
if self._pre_norm:
data = self.laye... |
Parameters
----------
F
data :
Shape (B, seq_length, C_in)
Returns
-------
out :
Shape (B, seq_length, C_out)
| forward | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def __init__(self, vocab_size: int,
embed_size: int,
units: int,
cutoffs: Optional[Union[int, List]] = None,
div_val: float = 1.0,
dtype='float32',
scaled=True,
embedding_initializer: InitializerType =... |
Parameters
----------
vocab_size
The size of the vocabulary
embed_size
The base size of the embedding vectors. The embedding size of each cluster will be
[embed_size / div_val**0, embed_size / div_val**1, embed_size / div_val**2, ...]
units
... | __init__ | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def forward(self, inp): # pylint: disable=arguments-differ
"""
Parameters
----------
inp
Shape (...,)
Returns
-------
out
Shape (..., units)
"""
if self._div_val == 1.0:
emb = np.take(getattr(self, 'embed0_wei... |
Parameters
----------
inp
Shape (...,)
Returns
-------
out
Shape (..., units)
| forward | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def __init__(self, vocab_size: int, embed_size: int, in_units: int,
cutoffs: Optional[Union[int, List]] = None,
div_val: float = 1.0,
dtype='float32',
use_bias=True,
weight_initializer: InitializerType = None,
bias_ini... |
Parameters
----------
vocab_size
Size of the vocabulary
embed_size
Base embedding size. The hidden will be first projected to
embed_size and then project to vocab_size
in_units
The number of input units
cutoffs
... | __init__ | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def get_logits(self, hidden):
"""Get all the logits.
Parameters
----------
hidden
The hidden representation/ Shape (..., in_units)
Returns
-------
logits
Shape (..., :math:`|V|`)
"""
if self._cutoffs is None:
... | Get all the logits.
Parameters
----------
hidden
The hidden representation/ Shape (..., in_units)
Returns
-------
logits
Shape (..., :math:`|V|`)
| get_logits | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def forward(self, hidden, target):
"""
Parameters
----------
hidden
The hidden representation
Shape (..., in_units)
target
The target representation
Shape (...,)
Returns
-------
sel_logits
The l... |
Parameters
----------
hidden
The hidden representation
Shape (..., in_units)
target
The target representation
Shape (...,)
Returns
-------
sel_logits
The log probability that each hidden has when label... | forward | python | dmlc/gluon-nlp | src/gluonnlp/layers.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/layers.py | Apache-2.0 |
def forward(self, pred, label):
"""
Parameters
----------
pred :
The predictions of the network. Shape (..., V)
label :
The labels. Shape (..., )
Returns
-------
loss :
Shape (..., )
"""
if not self._fr... |
Parameters
----------
pred :
The predictions of the network. Shape (..., V)
label :
The labels. Shape (..., )
Returns
-------
loss :
Shape (..., )
| forward | python | dmlc/gluon-nlp | src/gluonnlp/loss.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/loss.py | Apache-2.0 |
def select_vectors_by_position(data, positions):
"""Select each batch with the given positions.
Once advanced indexing can be hybridized, we can revise the implementation.
out[i, j, ...] = data[i, positions[i, j], ...]
Parameters
----------
data
Input tensor of contextualized token em... | Select each batch with the given positions.
Once advanced indexing can be hybridized, we can revise the implementation.
out[i, j, ...] = data[i, positions[i, j], ...]
Parameters
----------
data
Input tensor of contextualized token embeddings
Shape (batch_size, seq_length, ...)
... | select_vectors_by_position | python | dmlc/gluon-nlp | src/gluonnlp/op.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/op.py | Apache-2.0 |
def add_vectors_by_position(data, increment, positions):
"""Scatter each batch with the given positions.
data[i, positions[i, j], ...] += increment[i, j, ...]
Parameters
----------
data
Input tensor of the array to be updated.
Shape (batch_size, seq_length, ...)
increment
... | Scatter each batch with the given positions.
data[i, positions[i, j], ...] += increment[i, j, ...]
Parameters
----------
data
Input tensor of the array to be updated.
Shape (batch_size, seq_length, ...)
increment
Input tensor of token ids
Shape (batch_size, num_disp... | add_vectors_by_position | python | dmlc/gluon-nlp | src/gluonnlp/op.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/op.py | Apache-2.0 |
def update_vectors_by_position(data, val, positions):
"""
Update each batch with the given positions. Considered as a reversed process of
"select_vectors_by_position", this is an operator similar to "add_vectors_by_position"
that updates the results instead of adding.
data[i, positions[i, j], :] = ... |
Update each batch with the given positions. Considered as a reversed process of
"select_vectors_by_position", this is an operator similar to "add_vectors_by_position"
that updates the results instead of adding.
data[i, positions[i, j], :] = val[i, j, :]
Parameters
----------
data
... | update_vectors_by_position | python | dmlc/gluon-nlp | src/gluonnlp/op.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/op.py | Apache-2.0 |
def gumbel_softmax(logits, temperature: float = 1.0, eps: float = 1E-10,
hard=True, use_np_gumbel: bool = True):
r"""Perform the gumbel-softmax trick to generate differentiable one-hot vectors from the input
logits.
Here, the gumbel distribution is
Gumbel(\alpha) = -log (-log U) + \... | Perform the gumbel-softmax trick to generate differentiable one-hot vectors from the input
logits.
Here, the gumbel distribution is
Gumbel(\alpha) = -log (-log U) + \log \alpha, in which U is the uniform(0, 1) distribution.
A nice property of Gumbel is:
\argmax({Gumbel(\alpha_i)}) \sim multinomi... | gumbel_softmax | python | dmlc/gluon-nlp | src/gluonnlp/op.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/op.py | Apache-2.0 |
def trunc_gumbel(logits, truncation):
"""Sample from the TruncGumbel distribution.
The cumulative density function (CDF) of the Truncated Gumbel distribution is defined as
TruncGumbel(\alpha, truncation) \prop max(Gumbel(\alpha), truncation)
To sample from the distribution, we can use the CDF inversi... | Sample from the TruncGumbel distribution.
The cumulative density function (CDF) of the Truncated Gumbel distribution is defined as
TruncGumbel(lpha, truncation) \prop max(Gumbel(lpha), truncation)
To sample from the distribution, we can use the CDF inversion technique.
References:
1. [NIP... | trunc_gumbel | python | dmlc/gluon-nlp | src/gluonnlp/op.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/op.py | Apache-2.0 |
def relative_position_bucket(relative_position,
bidirectional: bool = True,
num_buckets: int = 32,
max_distance: int = 128):
"""Map the relative position to buckets. The implementation is consistent with that
in [mesh_tensorf... | Map the relative position to buckets. The implementation is consistent with that
in [mesh_tensorflow](https://github.com/tensorflow/mesh/blob/c59988047e49b4d2af05603e3170724cdbadc467/mesh_tensorflow/transformer/transformer_layers.py#L595-L637)
where relative position is defined as `mem_i - query_j`. Thus, a pos... | relative_position_bucket | python | dmlc/gluon-nlp | src/gluonnlp/op.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/op.py | Apache-2.0 |
def _expand_to_beam_size(data, beam_size, batch_size, state_batch_axis=None):
"""Tile all the states to have batch_size * beam_size on the batch axis.
Parameters
----------
data : A single mx.np.ndarray or nested container with mx.np.ndarray
Each mx.np.ndarray should have shape (N, ...) when st... | Tile all the states to have batch_size * beam_size on the batch axis.
Parameters
----------
data : A single mx.np.ndarray or nested container with mx.np.ndarray
Each mx.np.ndarray should have shape (N, ...) when state_info is None,
or same as the layout in state_info when it's not None.
... | _expand_to_beam_size | python | dmlc/gluon-nlp | src/gluonnlp/sequence_sampler.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/sequence_sampler.py | Apache-2.0 |
def _choose_states(states, indices, state_batch_axis=None):
"""
Parameters
----------
states : Object contains mx.np.ndarray
indices : mx.np.ndarray
Indices of the states to take. Shape (N,).
state_batch_axis
Descriptors for states, it is generated from decoder's ``state_batch_a... |
Parameters
----------
states : Object contains mx.np.ndarray
indices : mx.np.ndarray
Indices of the states to take. Shape (N,).
state_batch_axis
Descriptors for states, it is generated from decoder's ``state_batch_axis``.
When None, this method assumes that the batch axis i... | _choose_states | python | dmlc/gluon-nlp | src/gluonnlp/sequence_sampler.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/sequence_sampler.py | Apache-2.0 |
def __init__(self, beam_size, vocab_size, eos_id, scorer, state_batch_axis,
stochastic=False):
"""
Parameters
----------
beam_size : int
vocab_size : int
eos_id : int
scorer : BeamSearchScorer
state_batch_axis :
stochastic: bool
... |
Parameters
----------
beam_size : int
vocab_size : int
eos_id : int
scorer : BeamSearchScorer
state_batch_axis :
stochastic: bool
prefix : None
params : None
| __init__ | python | dmlc/gluon-nlp | src/gluonnlp/sequence_sampler.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/sequence_sampler.py | Apache-2.0 |
def gumbel_with_maximum(self, phi, T, dim=-1):
"""Calculate the Gumbel with maximum.
Parameters
----------
phi : mx.np.ndarray
Shape (batch_size, beam_size, L).
T : mx.np.ndarray
The previous scores. Shape (batch_size, beam_size)
"""
g_phi... | Calculate the Gumbel with maximum.
Parameters
----------
phi : mx.np.ndarray
Shape (batch_size, beam_size, L).
T : mx.np.ndarray
The previous scores. Shape (batch_size, beam_size)
| gumbel_with_maximum | python | dmlc/gluon-nlp | src/gluonnlp/sequence_sampler.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/sequence_sampler.py | Apache-2.0 |
def shift_gumbel_maximum(self, g_phi, T, axis=-1, Z=None):
"""
Parameters
----------
g_phi : mx.np.ndarray
Shape (batch_size, beam_size, L).
T : mx.np.ndarray
The previous scores. Shape (batch_size, beam_size)
axis
The axis
Z
... |
Parameters
----------
g_phi : mx.np.ndarray
Shape (batch_size, beam_size, L).
T : mx.np.ndarray
The previous scores. Shape (batch_size, beam_size)
axis
The axis
Z
The Z value
| shift_gumbel_maximum | python | dmlc/gluon-nlp | src/gluonnlp/sequence_sampler.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/sequence_sampler.py | Apache-2.0 |
def forward(self, samples, valid_length, outputs, scores, step, beam_alive_mask, # pylint: disable=arguments-differ
states, batch_shift):
"""
Parameters
----------
samples : mx.np.ndarray
The current samples generated by beam search.
Shape (batc... |
Parameters
----------
samples : mx.np.ndarray
The current samples generated by beam search.
Shape (batch_size, beam_size, L).
valid_length : mx.np.ndarray
The current valid lengths of the samples
outputs : mx.np.ndarray
Outputs fr... | forward | python | dmlc/gluon-nlp | src/gluonnlp/sequence_sampler.py | https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/sequence_sampler.py | Apache-2.0 |
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.