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 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_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 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 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
def forward(self, inputs, states, src_seq_lengths=None): """Sample by beam search. Parameters ---------- inputs : mx.np.ndarray The initial input of the decoder. Shape is (batch_size,). states : Object that contains mx.np.ndarrays The initial states of th...
Sample by beam search. Parameters ---------- inputs : mx.np.ndarray The initial input of the decoder. Shape is (batch_size,). states : Object that contains mx.np.ndarrays The initial states of the decoder. src_seq_lengths : mx.np.ndarray The s...
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
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype, round_to=None): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False dtype : round_to : int Returns ----...
Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False dtype : round_to : int Returns ------- ret : NDArray original_length : NDArray
_pad_arrs_to_max_length
python
dmlc/gluon-nlp
src/gluonnlp/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/batchify.py
Apache-2.0
def __call__(self, data): """Batchify the input data. The input can be list of numpy.ndarray, list of numbers or list of mxnet.nd.NDArray. Inputting mxnet.nd.NDArray is discouraged as each array need to be converted to numpy for efficient padding. The arrays will be padded to t...
Batchify the input data. The input can be list of numpy.ndarray, list of numbers or list of mxnet.nd.NDArray. Inputting mxnet.nd.NDArray is discouraged as each array need to be converted to numpy for efficient padding. The arrays will be padded to the largest dimension at `axis` and th...
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/batchify.py
Apache-2.0
def __call__(self, data): """Batchify the input data. Parameters ---------- data : list The samples to batchfy. Each sample should contain N attributes. Returns ------- ret : tuple A tuple of length N. Contains the batchified result of ea...
Batchify the input data. Parameters ---------- data : list The samples to batchfy. Each sample should contain N attributes. Returns ------- ret : tuple A tuple of length N. Contains the batchified result of each attribute in the input.
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/batchify.py
Apache-2.0
def __call__(self, data: t_List[t_Dict]) -> t_Dict: """ Parameters ---------- data The samples to batchify. Each sample should be a dictionary Returns ------- ret The resulting dictionary that stores the merged samples. """ ...
Parameters ---------- data The samples to batchify. Each sample should be a dictionary Returns ------- ret The resulting dictionary that stores the merged samples.
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/batchify.py
Apache-2.0
def __call__(self, data: t_List[t_NamedTuple]) -> t_NamedTuple: """Batchify the input data. Parameters ---------- data The samples to batchfy. Each sample should be a namedtuple. Returns ------- ret A namedtuple of length N. Contains the ...
Batchify the input data. Parameters ---------- data The samples to batchfy. Each sample should be a namedtuple. Returns ------- ret A namedtuple of length N. Contains the batchified result of each attribute in the input.
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/batchify.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/batchify.py
Apache-2.0
def _words_match_regex(words: List[str], ignore_case=False, replace_white_space=False) -> Pattern: """Obtain the regex that finds whether a given corpus contains any word in the input words Parameters ---------- words Returns ------- regex """ words = [ele for ele in words if ele]...
Obtain the regex that finds whether a given corpus contains any word in the input words Parameters ---------- words Returns ------- regex
_words_match_regex
python
dmlc/gluon-nlp
src/gluonnlp/data/filtering.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/filtering.py
Apache-2.0
def __call__(self, corpus: str): """ Parameters ---------- corpus Input corpus Returns ------- lang_label The ISO-639 1 code of the predicted language score The score of the prediction """ if self._use_...
Parameters ---------- corpus Input corpus Returns ------- lang_label The ISO-639 1 code of the predicted language score The score of the prediction
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/filtering.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/filtering.py
Apache-2.0
def _dataset_worker_fn(urls, dataset_fn, batch_sampler_fn): """Function to generate datasets and batch sampler for each worker.""" global _manager, _dataset dataset = dataset_fn(urls) batch_sampler = batch_sampler_fn(dataset) if _manager: dataset = _manager.list(zip(*dataset._data)) _dat...
Function to generate datasets and batch sampler for each worker.
_dataset_worker_fn
python
dmlc/gluon-nlp
src/gluonnlp/data/loading.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/loading.py
Apache-2.0
def _batch_worker_fn(samples, batchify_fn, dataset=None, counter=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of ov...
Function for processing data in worker process.
_batch_worker_fn
python
dmlc/gluon-nlp
src/gluonnlp/data/loading.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/loading.py
Apache-2.0
def _push_next(self): """Assign next batch workload to workers.""" if self._batch_iter is not None: r = next(self._batch_iter, None) else: r = None if r is None: result = self._next_dataset() if result is None: return ...
Assign next batch workload to workers.
_push_next
python
dmlc/gluon-nlp
src/gluonnlp/data/loading.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/loading.py
Apache-2.0
def _push_next_dataset(self): """Assign next dataset workload to workers.""" current_dataset_idx = self._sent_idx * self._circle_length if current_dataset_idx < self._num_datasets: circle_length = min(self._circle_length, self._num_datasets - current_d...
Assign next dataset workload to workers.
_push_next_dataset
python
dmlc/gluon-nlp
src/gluonnlp/data/loading.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/loading.py
Apache-2.0
def _next_dataset(self): """Retrieve the next dataset. Returns None if no dataset is available.""" if self._rcvd_idx == self._sent_idx: assert not self._data_buffer, 'Data buffer should be empty at this moment' return None assert self._rcvd_idx < self._sent_idx, \ ...
Retrieve the next dataset. Returns None if no dataset is available.
_next_dataset
python
dmlc/gluon-nlp
src/gluonnlp/data/loading.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/loading.py
Apache-2.0
def __call__(self, max_lengths: Union[int, Sequence[int]], min_lengths: Union[int, Sequence[int]], num_buckets: int) -> List[int]: """Generate bucket keys based on the lengths of sequences and number of buckets. Parameters ---------- max_lengths Maximum of l...
Generate bucket keys based on the lengths of sequences and number of buckets. Parameters ---------- max_lengths Maximum of lengths of sequences. min_lengths Minimum of lengths of sequences. num_buckets Number of buckets Returns ...
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/sampler.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/sampler.py
Apache-2.0
def __call__(self, max_lengths: Union[int, Sequence[int]], min_lengths: Union[int, Sequence[int]], num_buckets: int) -> List[int]: r"""This generate bucket keys given that all the buckets have the same width. Parameters ---------- max_lengths Maximum of leng...
This generate bucket keys given that all the buckets have the same width. Parameters ---------- max_lengths Maximum of lengths of sequences. min_lengths Minimum of lengths of sequences. num_buckets Number of buckets Returns --...
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/sampler.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/sampler.py
Apache-2.0
def __call__(self, max_lengths: Union[int, Sequence[int]], min_lengths: Union[int, Sequence[int]], num_buckets: int) -> List[int]: r"""This function generates bucket keys with linearly increasing bucket width: Parameters ---------- max_lengths Maximum of len...
This function generates bucket keys with linearly increasing bucket width: Parameters ---------- max_lengths Maximum of lengths of sequences. min_lengths Minimum of lengths of sequences. num_buckets Number of buckets Returns -...
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/sampler.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/sampler.py
Apache-2.0
def __call__(self, max_lengths: Union[int, Sequence[int]], min_lengths: Union[int, Sequence[int]], num_buckets: int) -> List[int]: r"""This function generates bucket keys exponentially increasing bucket width. Parameters ---------- max_lengths Maximum of len...
This function generates bucket keys exponentially increasing bucket width. Parameters ---------- max_lengths Maximum of lengths of sequences. min_lengths Minimum of lengths of sequences. num_buckets Number of buckets Returns -...
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/sampler.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/sampler.py
Apache-2.0
def __repr__(self): """Return a string representing the statistics of the bucketing sampler. Returns ------- ret : str String representing the statistics of the buckets. """ ret = '{name}(\n' \ ' sample_num={sample_num}, batch_num={batch_num}\n' ...
Return a string representing the statistics of the bucketing sampler. Returns ------- ret : str String representing the statistics of the buckets.
__repr__
python
dmlc/gluon-nlp
src/gluonnlp/data/sampler.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/sampler.py
Apache-2.0
def _check_special_token_identifier(key): """Raise error if the key is not valid as a key for the special token. Parameters ---------- key The identifier """ if not (key.endswith('_token') and key != '_token'): raise ValueError('Each key needs to have the form "name_token".' ...
Raise error if the key is not valid as a key for the special token. Parameters ---------- key The identifier
_check_special_token_identifier
python
dmlc/gluon-nlp
src/gluonnlp/data/vocab.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/vocab.py
Apache-2.0
def to_tokens(self, idx: Union[int, Tuple[int], List[int], np.ndarray])\ -> Union[Hashable, List[Hashable]]: """Get the tokens correspond to the chosen indices Parameters ---------- idx The index used to select the tokens. Returns ------- ...
Get the tokens correspond to the chosen indices Parameters ---------- idx The index used to select the tokens. Returns ------- ret The tokens of these selected indices.
to_tokens
python
dmlc/gluon-nlp
src/gluonnlp/data/vocab.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/vocab.py
Apache-2.0
def __getitem__(self, tokens: Union[Hashable, List[Hashable], Tuple[Hashable]])\ -> Union[int, List[int]]: """Looks up indices of text tokens according to the vocabulary. If `unknown_token` of the vocabulary is None, looking up unknown tokens results in KeyError. Parameters ...
Looks up indices of text tokens according to the vocabulary. If `unknown_token` of the vocabulary is None, looking up unknown tokens results in KeyError. Parameters ---------- tokens A source token or tokens to be converted. Returns ------- ret ...
__getitem__
python
dmlc/gluon-nlp
src/gluonnlp/data/vocab.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/vocab.py
Apache-2.0
def __call__(self, tokens: Union[Hashable, List[Hashable], Tuple[Hashable]])\ -> Union[int, np.ndarray]: """Looks up indices of text tokens according to the vocabulary. Parameters ---------- tokens A source token or tokens to be converted. Returns ...
Looks up indices of text tokens according to the vocabulary. Parameters ---------- tokens A source token or tokens to be converted. Returns ------- ret A token index or a list of token indices according to the vocabulary.
__call__
python
dmlc/gluon-nlp
src/gluonnlp/data/vocab.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/vocab.py
Apache-2.0
def to_json(self) -> str: """Serialize Vocab object into a json string. Returns ------- ret The serialized json string """ vocab_dict = dict() # Perform sanity check to make sure that we are able to reconstruct the original vocab for i, tok in...
Serialize Vocab object into a json string. Returns ------- ret The serialized json string
to_json
python
dmlc/gluon-nlp
src/gluonnlp/data/vocab.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/vocab.py
Apache-2.0
def from_json(cls, json_str: Union[str, bytes, bytearray]) -> 'Vocab': """Deserialize Vocab object from json string. Parameters ---------- json_str Serialized json string of a Vocab object. Returns ------- vocab The constructed Vocab obje...
Deserialize Vocab object from json string. Parameters ---------- json_str Serialized json string of a Vocab object. Returns ------- vocab The constructed Vocab object
from_json
python
dmlc/gluon-nlp
src/gluonnlp/data/vocab.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/vocab.py
Apache-2.0
def load_vocab(vocab: Union[str, Vocab]) -> Vocab: """Quick helper function to load vocabulary from a file. Parameters ---------- vocab Returns ------- """ if isinstance(vocab, Vocab): return vocab elif isinstance(vocab, str): return Vocab.load(vocab) else: ...
Quick helper function to load vocabulary from a file. Parameters ---------- vocab Returns -------
load_vocab
python
dmlc/gluon-nlp
src/gluonnlp/data/vocab.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/vocab.py
Apache-2.0
def get_token_type(tokens: Union[List[str], List[int], List[List[str]], List[List[int]]]) -> type: """ Parameters ---------- tokens The input tokens. Returns ------- token_type If the tokens is empty, return `str`. Otherwise, return ...
Parameters ---------- tokens The input tokens. Returns ------- token_type If the tokens is empty, return `str`. Otherwise, return `str` if the input is str and `int` if the input is int.
get_token_type
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/base.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/base.py
Apache-2.0
def rebuild_offset_from_tokens(sentence: str, tokens: List[str]) \ -> List[Tuple[int, int]]: """Recover the offset of the tokens in the original sentence. If you are using a subword tokenizer, make sure to remove the prefix/postfix of the tokens before using this function. Also, this does not work ...
Recover the offset of the tokens in the original sentence. If you are using a subword tokenizer, make sure to remove the prefix/postfix of the tokens before using this function. Also, this does not work for n-gram-based (n>1) subword tokenization, i.e. it works for "gluonnlp" --> ["gluon", "nlp"] b...
rebuild_offset_from_tokens
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/base.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/base.py
Apache-2.0
def get_char_offset_from_byte_offset(sentence: str, byte_offsets: List[Tuple[int, int]]): """Get the character-level offsets based on the byte-level offsets Parameters ---------- sentence The input sentence byte_offsets The byte-level offsets Returns ------- char_offset...
Get the character-level offsets based on the byte-level offsets Parameters ---------- sentence The input sentence byte_offsets The byte-level offsets Returns ------- char_offsets The character-level offsets
get_char_offset_from_byte_offset
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/base.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/base.py
Apache-2.0
def encode(self, sentences: SentencesType, output_type: type = str) \ -> Union[TokensType, TokenIDsType]: """Encode the input sentence(s) into multiple tokens. Parameters ---------- sentences The sentences to tokenize output_type ...
Encode the input sentence(s) into multiple tokens. Parameters ---------- sentences The sentences to tokenize output_type The type of the output tokens. - str means each token is represented by its original text. - int means each token is r...
encode
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/base.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/base.py
Apache-2.0
def encode_with_offsets(self, sentences: SentencesType, output_type: type = str) \ -> Tuple[Union[TokensType, TokenIDsType], TokenOffsetsType]: """Encode the input sentence(s) into multiple tokens. Different from encode, it will also return the character start and...
Encode the input sentence(s) into multiple tokens. Different from encode, it will also return the character start and end positions of each token in the original text. The original text is assumed to be Here, the default implementation is to use the tokenized result to recover the offsets. ...
encode_with_offsets
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/base.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/base.py
Apache-2.0
def is_new_version_model_file(model_file_path: str) -> bool: """Check whether the model file belongs to the new version of HuggingFace Tokenizers, i.e., >= 0.8 Parameters ---------- model_file_path Path to the model file Returns ------- is_new_version Whether the model ...
Check whether the model file belongs to the new version of HuggingFace Tokenizers, i.e., >= 0.8 Parameters ---------- model_file_path Path to the model file Returns ------- is_new_version Whether the model file is generated by the new version of huggingface tokenizer.
is_new_version_model_file
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/huggingface.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/huggingface.py
Apache-2.0
def hf_encode(model, sentences, output_type: type = str): """ Parameters ---------- model Model object in HuggingFace tokenizer sentences Input sentences output_type Output type Returns ------- ret """ is_multi_sentences = isinstance(sentences, list)...
Parameters ---------- model Model object in HuggingFace tokenizer sentences Input sentences output_type Output type Returns ------- ret
hf_encode
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/huggingface.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/huggingface.py
Apache-2.0
def is_last_subword(self, tokens): """Whether the sub-token is the last sub-token in a split token list. Only supports the case when the tokenizer is a HuggingFaceBPETokenizer Parameters ---------- tokens A single token or a list of tokens Returns -...
Whether the sub-token is the last sub-token in a split token list. Only supports the case when the tokenizer is a HuggingFaceBPETokenizer Parameters ---------- tokens A single token or a list of tokens Returns ------- ret The results ...
is_last_subword
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/huggingface.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/huggingface.py
Apache-2.0
def is_first_subword(self, tokens): """Whether the sub-token is the first sub-token in a token list. Only supports the case when the tokenizer is a HuggingFaceWordPieceTokenizer Parameters ---------- tokens A single token or a list of tokens Returns ...
Whether the sub-token is the first sub-token in a token list. Only supports the case when the tokenizer is a HuggingFaceWordPieceTokenizer Parameters ---------- tokens A single token or a list of tokens Returns ------- ret The results ...
is_first_subword
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/huggingface.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/huggingface.py
Apache-2.0
def __init__(self, merges_file: Optional[str] = None, vocab_file: Optional[str] = None, unk_token: Optional[str] = Vocab.UNK_TOKEN, suffix: Optional[str] = '</w>', dropout: Optional[float] = None, lowercase: bool = False): """ ...
Parameters ---------- merges_file The merges file saved by HuggingFace vocab_file Vocabulary file in GluonNLP unk_token The unknown token suffix The suffix for sub-tokens. For example, "Sunnyvale" will be "Sunny vale</w>" ...
__init__
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/huggingface.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/huggingface.py
Apache-2.0
def is_last_subword(self, tokens: Union[str, int, List[str], List[int]]) \ -> Union[bool, List[bool]]: """Whether the token is the last subword token. This can be used for whole-word masking. Parameters ---------- tokens The input tokens Returns ...
Whether the token is the last subword token. This can be used for whole-word masking. Parameters ---------- tokens The input tokens Returns ------- ret Whether the token is the last subword token in the list of subwords.
is_last_subword
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/huggingface.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/huggingface.py
Apache-2.0
def is_first_subword(self, tokens: Union[str, int, List[str], List[int]]) \ -> Union[bool, List[bool]]: """Whether the token is the first subword token in a sequence of subword tokens. This can be used for implementing whole-word masking. We won't care about the special tokens ...
Whether the token is the first subword token in a sequence of subword tokens. This can be used for implementing whole-word masking. We won't care about the special tokens Parameters ---------- tokens Returns ------- ret
is_first_subword
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/huggingface.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/huggingface.py
Apache-2.0
def is_first_subword(self, tokens: Union[str, int, List[str], List[int]]) \ -> Union[bool, List[bool]]: """Whether the token is the first subword token. This can be used to implement whole-word masking. Parameters ---------- tokens The input tokens ...
Whether the token is the first subword token. This can be used to implement whole-word masking. Parameters ---------- tokens The input tokens Returns ------- ret Whether the token is the first subword token in the list of subwords ...
is_first_subword
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/sentencepiece.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/sentencepiece.py
Apache-2.0
def set_subword_regularization(self, nbest, alpha): """Set the subword-regularization parameters For more details, you may refer to the official SentencePiece library: https://github.com/google/sentencepiece Parameters ---------- nbest alpha Returns ...
Set the subword-regularization parameters For more details, you may refer to the official SentencePiece library: https://github.com/google/sentencepiece Parameters ---------- nbest alpha Returns -------
set_subword_regularization
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/sentencepiece.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/sentencepiece.py
Apache-2.0
def __getstate__(self): """Make the SentencepieceTokenizer pickleble. We will remove the _spt_cls and _sp_model, which are not picklable, and try to reconstruct the class via the saved model_path. This behavior is only acceptable for multiprocessing and should not be used to save sent...
Make the SentencepieceTokenizer pickleble. We will remove the _spt_cls and _sp_model, which are not picklable, and try to reconstruct the class via the saved model_path. This behavior is only acceptable for multiprocessing and should not be used to save sentencepiece models.
__getstate__
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/sentencepiece.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/sentencepiece.py
Apache-2.0
def transform_sentence(self, sentence): """replace the separator in encoded result with suffix a@@, b@@, c -> a, b, c</w> Parameters ---------- sentence Returns ------- new_sentence """ return [word[:-2] if len(word) > 2 and word[-2:] =...
replace the separator in encoded result with suffix a@@, b@@, c -> a, b, c</w> Parameters ---------- sentence Returns ------- new_sentence
transform_sentence
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/subword_nmt.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/subword_nmt.py
Apache-2.0
def is_last_subword(self, tokens: Union[str, int, List[str], List[int]]) \ -> Union[bool, List[bool]]: """Whether the token is the last subword token. This can be used for whole-word masking. Parameters ---------- tokens The input tokens Returns ...
Whether the token is the last subword token. This can be used for whole-word masking. Parameters ---------- tokens The input tokens Returns ------- ret Whether the token is the last subword token in the list of subwords
is_last_subword
python
dmlc/gluon-nlp
src/gluonnlp/data/tokenizers/subword_nmt.py
https://github.com/dmlc/gluon-nlp/blob/master/src/gluonnlp/data/tokenizers/subword_nmt.py
Apache-2.0