INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_regex : str The regex for parameter names used in the self.params.get(), such as 'weight'. rate : float Fract...
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_rege...
create rnn cell given specs Parameters ---------- mode : str The type of RNN cell to use. Options are 'lstmpc', 'rnn_tanh', 'rnn_relu', 'lstm', 'gru'. num_layers : int The number of RNN cells in the encoder. input_size : int The initial input size of in the RNN cell. hid...
def _get_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, cell_clip=None, proj_clip=None): """create rnn cell given specs Parameters ---------- m...
create rnn layer given specs
def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout): """create rnn layer given specs""" if mode == 'rnn_relu': rnn_block = functools.partial(rnn.RNN, activation='relu') elif mode == 'rnn_tanh': rnn_block = functools.partial(rnn.RNN, activation='tanh') e...
Forward computation.
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = ...
Forward computation.
def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shape=(-1,)) # (num_sampled+batch_size,) ids = F.concat(sampled_candidates, label, dim=0) ...
Forward computation.
def forward(self, x, sampled_values, label): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = label.reshape(shape=(-1,)) # (num_sampled+batch_size,) ids = nd.concat(sampled_candidates, label, dim=0) # lookup weights and ...
Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None The container thats holds flattened result. Returns ------- st...
def _extract_and_flatten_nested_structure(data, flattened=None): """Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None Th...
Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None The container thats holds flattened result. Returns ...
def _reconstruct_flattened_structure(structure, flattened): """Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None ...
Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when state_info is None, or same as the layout in state_info when it's not None....
def _expand_to_beam_size(data, beam_size, batch_size, state_info=None): """Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when stat...
Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbol The current valid lengths of the samples outputs: NDArray or Symbol Decoder outp...
def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states): """ Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbo...
Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or Symbols The initial states of the decoder. Returns ------- ...
def hybrid_forward(self, F, inputs, states): # pylint: disable=arguments-differ """Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or ...
Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx """ d = self._...
r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. pretrained : bool, default False Whether to load th...
def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name...
Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. Returns ------- token_embe...
def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) ...
Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward laye...
def hybrid_forward(self, F, inputs, states=None, mask=None): # pylint: disable=arguments-differ """ Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. ...
r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitex...
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Param...
r"""Standard 2-layer LSTM language model with tied embedding and output weights. Both embedding and hidden dimensions are 200. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitext-2'. If specifi...
def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Standard 2-layer LSTM language model with tied embedding and output weights. Both embedding and hidden dimensions are 200. Parameters ...
r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. If specified, then the returned vocabular...
def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_n...
Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list initial recurrent state tensor with length equals to num_layers. the ...
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list initial recurrent state tensor with length equals to num_layers*2. Fo...
def forward(self, inputs, begin_state): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
Get the object type of the cell by parsing the input Parameters ---------- cell_type : str or type Returns ------- cell_constructor: type The constructor of the RNNCell
def _get_cell_type(cell_type): """Get the object type of the cell by parsing the input Parameters ---------- cell_type : str or type Returns ------- cell_constructor: type The constructor of the RNNCell """ if isinstance(cell_type, str): if cell_type == 'lstm': ...
Compute the context with respect to a center word in a sentence. Takes an numpy array of sentences boundaries.
def _get_context(center_idx, sentence_boundaries, window_size, random_window_size, seed): """Compute the context with respect to a center word in a sentence. Takes an numpy array of sentences boundaries. """ random.seed(seed + center_idx) sentence_index = np.searchsorted(sentence...
Construct the model.
def model(dropout, vocab, model_mode, output_size): """Construct the model.""" textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\ output_size=output_size) textCNN.hybridize() return textCNN
Initialize parameters.
def init(textCNN, vocab, model_mode, context, lr): """Initialize parameters.""" textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True) if model_mode != 'rand': textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec) if model_mode == 'multichannel': textCNN.embedding_...
Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of multiprocessing workers to use for data preprocessing.
def preprocess_dataset(dataset, transform, num_workers=8): """Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of mult...
Ignore the masked elements when calculating the softmax Parameters ---------- F : symbol or ndarray att_score : Symborl or NDArray Shape (batch_size, query_length, memory_length) mask : Symbol or NDArray or None Shape (batch_size, query_length, memory_length) Returns -------...
def _masked_softmax(F, att_score, mask, dtype): """Ignore the masked elements when calculating the softmax Parameters ---------- F : symbol or ndarray att_score : Symborl or NDArray Shape (batch_size, query_length, memory_length) mask : Symbol or NDArray or None Shape (batch_siz...
Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. The dataset name on which the pre-trained model is trained. For language model, options are 'wikitext-2'. For ELMo, Options are 'gbw...
def get_model(name, dataset_name='wikitext-2', **kwargs): """Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. The dataset name on which the pre-trained model is trained. For language mo...
Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (batch_size, query_length, memory_length). For mult...
def _read_by_weight(self, F, att_weights, value): """Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (b...
Get the translation result given the input sentence. Parameters ---------- src_seq : mx.nd.NDArray Shape (batch_size, length) src_valid_length : mx.nd.NDArray Shape (batch_size,) Returns ------- samples : NDArray Samples draw ...
def translate(self, src_seq, src_valid_length): """Get the translation result given the input sentence. Parameters ---------- src_seq : mx.nd.NDArray Shape (batch_size, length) src_valid_length : mx.nd.NDArray Shape (batch_size,) Returns ...
Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built from data set num_buckets_test : int size of buckets (cluster sentences into this number of clusters) test_batch_size : int batch...
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False): """Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built ...
Create parameter with its value initialized according to a numpy tensor Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.gluon.parameter a parameter object
def parameter_from_numpy(self, name, array): """ Create parameter with its value initialized according to a numpy tensor Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.glu...
Create parameter given name, shape and initiator Parameters ---------- name : str parameter name shape : tuple parameter shape init : mxnet.initializer an initializer Returns ------- mxnet.gluon.parameter a...
def parameter_init(self, name, shape, init): """Create parameter given name, shape and initiator Parameters ---------- name : str parameter name shape : tuple parameter shape init : mxnet.initializer an initializer Returns ...
Run decoding Parameters ---------- word_inputs : mxnet.ndarray.NDArray word indices of seq_len x batch_size tag_inputs : mxnet.ndarray.NDArray tag indices of seq_len x batch_size arc_targets : mxnet.ndarray.NDArray gold arc indices of seq_len ...
def forward(self, word_inputs, tag_inputs, arc_targets=None, rel_targets=None): """Run decoding Parameters ---------- word_inputs : mxnet.ndarray.NDArray word indices of seq_len x batch_size tag_inputs : mxnet.ndarray.NDArray tag indices of seq_len x batc...
Save model Parameters ---------- filename : str path to model file
def save_parameters(self, filename): """Save model Parameters ---------- filename : str path to model file """ params = self._collect_params_with_prefix() if self.pret_word_embs: # don't save word embeddings inside model params.pop('pret_...
Function for processing data in worker process.
def _worker_fn(samples, batchify_fn, dataset=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 overhead and is safe i...
Threadpool worker function for processing data.
def _thread_worker_fn(samples, batchify_fn, dataset): """Threadpool worker function for processing data.""" if isinstance(samples[0], (list, tuple)): batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples] else: batch = batchify_fn([dataset[i] for i in samples]) return ba...
Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :func:`gluonnlp.embedding.list_sources`. Pa...
def create(embedding_name, **kwargs): """Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :fun...
Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `gluonnlp.embedding.create(embedding_name, source)`. This method returns all the valid names...
def list_sources(embedding_name=None): """Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `gluonnlp.embedding.create(embedding_name, source)...
Load embedding vectors from a pre-trained token embedding file. Both text files and TokenEmbedding serialization files are supported. elem_delim and encoding are ignored for non-text files. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-tr...
def _load_embedding(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. Both text files and TokenEmbedding serialization files are supported. elem_delim and encoding are ignored for non-text files. ...
Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherwise...
def _load_embedding_txt(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_t...
Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherwise...
def _load_embedding_serialized(self, pretrained_file_path): """Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre...
Check that tokens and embedding are in the format for __setitem__.
def _check_vector_update(self, tokens, new_embedding): """Check that tokens and embedding are in the format for __setitem__.""" assert self._idx_to_vec is not None, '`idx_to_vec` has not been initialized.' if not isinstance(tokens, (list, tuple)) or len(tokens) == 1: assert isinstan...
Checks if a pre-trained token embedding source name is valid. Parameters ---------- source : str The pre-trained token embedding source.
def _check_source(cls, source_file_hash, source): """Checks if a pre-trained token embedding source name is valid. Parameters ---------- source : str The pre-trained token embedding source. """ embedding_name = cls.__name__.lower() if source not in s...
Creates a user-defined token embedding from a pre-trained embedding file. This is to load embedding vectors from a user-defined pre-trained token embedding file. For example, if `elem_delim` = ' ', the expected format of a custom pre-trained token embedding file may look like: 'hello ...
def from_file(file_path, elem_delim=' ', encoding='utf8', **kwargs): """Creates a user-defined token embedding from a pre-trained embedding file. This is to load embedding vectors from a user-defined pre-trained token embedding file. For example, if `elem_delim` = ' ', the expected format of a...
Create a new TokenEmbedding from a serialized one. TokenEmbedding is serialized by converting the list of tokens, the array of word embeddings and other metadata to numpy arrays, saving all in a single (optionally compressed) Zipfile. See https://docs.scipy.org/doc/numpy-1.14.2/neps/npy...
def deserialize(cls, file_path, **kwargs): """Create a new TokenEmbedding from a serialized one. TokenEmbedding is serialized by converting the list of tokens, the array of word embeddings and other metadata to numpy arrays, saving all in a single (optionally compressed) Zipfile. See ...
Serializes the TokenEmbedding to a file specified by file_path. TokenEmbedding is serialized by converting the list of tokens, the array of word embeddings and other metadata to numpy arrays, saving all in a single (optionally compressed) Zipfile. See https://docs.scipy.org/doc/numpy-1....
def serialize(self, file_path, compress=True): """Serializes the TokenEmbedding to a file specified by file_path. TokenEmbedding is serialized by converting the list of tokens, the array of word embeddings and other metadata to numpy arrays, saving all in a single (optionally compressed...
Evaluate the model on a mini-batch.
def evaluate(data_source): """Evaluate the model on a mini-batch. """ log.info('Start predict') tic = time.time() for batch in data_source: inputs, token_types, valid_length = batch out = net(inputs.astype('float32').as_in_context(ctx), token_types.astype('float32')...
Registers a dataset with segment specific hyperparameters. When passing keyword arguments to `register`, they are checked to be valid keyword arguments for the registered Dataset class constructor and are saved in the registry. Registered keyword arguments can be retrieved with the `list_datasets` func...
def register(class_=None, **kwargs): """Registers a dataset with segment specific hyperparameters. When passing keyword arguments to `register`, they are checked to be valid keyword arguments for the registered Dataset class constructor and are saved in the registry. Registered keyword arguments can be...
Creates an instance of a registered dataset. Parameters ---------- name : str The dataset name (case-insensitive). Returns ------- An instance of :class:`mxnet.gluon.data.Dataset` constructed with the keyword arguments passed to the create function.
def create(name, **kwargs): """Creates an instance of a registered dataset. Parameters ---------- name : str The dataset name (case-insensitive). Returns ------- An instance of :class:`mxnet.gluon.data.Dataset` constructed with the keyword arguments passed to the create functio...
Get valid datasets and registered parameters. Parameters ---------- name : str or None, default None Return names and registered parameters of registered datasets. If name is specified, only registered parameters of the respective dataset are returned. Returns ------- d...
def list_datasets(name=None): """Get valid datasets and registered parameters. Parameters ---------- name : str or None, default None Return names and registered parameters of registered datasets. If name is specified, only registered parameters of the respective dataset are ret...
Parse command line arguments.
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='Vocabulary extractor.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--max-size', type=int, default=None) parser.add_argument('--min-freq', type=int, defau...
Compute the vocabulary.
def get_vocab(args): """Compute the vocabulary.""" counter = nlp.data.Counter() start = time.time() for filename in args.files: print('Starting processing of {} after {:.1f} seconds.'.format( filename, time.time() - start)) with open(filename, 'r') as f: ...
Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_length) Input words for the sequences. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to i...
def forward(self, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ """Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_length) Input words for the sequences. ...
Add evaluation specific parameters to parser.
def add_parameters(parser): """Add evaluation specific parameters to parser.""" group = parser.add_argument_group('Evaluation arguments') group.add_argument('--eval-batch-size', type=int, default=1024) # Datasets group.add_argument( '--similarity-datasets', type=str, default=nlp.da...
Validate provided arguments and act on --help.
def validate_args(args): """Validate provided arguments and act on --help.""" # Check correctness of similarity dataset names for dataset_name in args.similarity_datasets: if dataset_name.lower() not in map( str.lower, nlp.data.word_embedding_evaluation.word_similarit...
Generator over all similarity evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
def iterate_similarity_datasets(args): """Generator over all similarity evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset. """ for dataset_name in args.similarity_datasets: parameters = nlp.data.list_datasets(dataset_name) ...
Generator over all analogy evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
def iterate_analogy_datasets(args): """Generator over all analogy evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset. """ for dataset_name in args.analogy_datasets: parameters = nlp.data.list_datasets(dataset_name) for key...
Returns a set of all tokens occurring the evaluation datasets.
def get_similarity_task_tokens(args): """Returns a set of all tokens occurring the evaluation datasets.""" tokens = set() for _, _, dataset in iterate_similarity_datasets(args): tokens.update( itertools.chain.from_iterable((d[0], d[1]) for d in dataset)) return tokens
Returns a set of all tokens occuring the evaluation datasets.
def get_analogy_task_tokens(args): """Returns a set of all tokens occuring the evaluation datasets.""" tokens = set() for _, _, dataset in iterate_analogy_datasets(args): tokens.update( itertools.chain.from_iterable( (d[0], d[1], d[2], d[3]) for d in dataset)) return ...
Evaluate on specified similarity datasets.
def evaluate_similarity(args, token_embedding, ctx, logfile=None, global_step=0): """Evaluate on specified similarity datasets.""" results = [] for similarity_function in args.similarity_functions: evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity( idx...
Evaluate on specified analogy datasets. The analogy task is an open vocabulary task, make sure to pass a token_embedding with a sufficiently large number of supported tokens.
def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0): """Evaluate on specified analogy datasets. The analogy task is an open vocabulary task, make sure to pass a token_embedding with a sufficiently large number of supported tokens. """ results = [] exclude_question_wor...
Log a similarity evaluation result dictionary as TSV to logfile.
def log_similarity_result(logfile, result): """Log a similarity evaluation result dictionary as TSV to logfile.""" assert result['task'] == 'similarity' if not logfile: return with open(logfile, 'a') as f: f.write('\t'.join([ str(result['global_step']), result['...
Get model for pre-training.
def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None): """Get model for pre-training.""" # model model, vocabulary = nlp.model.get_model(model, dataset_name=dataset_name, pretrai...
create dataset for pretraining.
def get_pretrain_dataset(data, batch_size, num_ctxes, shuffle, use_avg_len, num_buckets, num_parts=1, part_idx=0, prefetch=True): """create dataset for pretraining.""" num_files = len(glob.glob(os.path.expanduser(data))) logging.debug('%d files found.', num_files) assert num_fil...
Return a dummy data loader which returns a fixed data batch of target shape
def get_dummy_dataloader(dataloader, target_shape): """Return a dummy data loader which returns a fixed data batch of target shape""" data_iter = enumerate(dataloader) _, data_batch = next(data_iter) logging.debug('Searching target batch shape: %s', target_shape) while data_batch[0].shape != target_...
Save the model parameter, marked by step_num.
def save_params(step_num, model, trainer, ckpt_dir): """Save the model parameter, marked by step_num.""" param_path = os.path.join(ckpt_dir, '%07d.params'%step_num) trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num) logging.info('[step %d] Saving checkpoints to %s, %s.', step...
Log training progress.
def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num, mlm_metric, nsp_metric, trainer, log_interval): """Log training progress.""" end_time = time.time() duration = end_time - begin_time throughput = running_num_tks / duration / 1000.0 running_mlm_loss = running_...
split and load arrays to a list of contexts
def split_and_load(arrs, ctx): """split and load arrays to a list of contexts""" assert isinstance(arrs, (list, tuple)) # split and load loaded_arrs = [mx.gluon.utils.split_and_load(arr, ctx, even_split=False) for arr in arrs] return zip(*loaded_arrs)
forward computation for evaluation
def forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype): """forward computation for evaluation""" (input_id, masked_id, masked_position, masked_weight, \ next_sentence_label, segment_id, valid_length) = data num_masks = masked_weight.sum() + 1e-8 valid_length = valid_length.reshape(-1) ...
Evaluation function.
def evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype): """Evaluation function.""" mlm_metric = MaskedAccuracy() nsp_metric = MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() eval_begin_time = time.time() begin_time = time.time() step_num = 0 ...
Argument parser
def get_argparser(): """Argument parser""" parser = argparse.ArgumentParser(description='BERT pretraining example.') parser.add_argument('--num_steps', type=int, default=20, help='Number of optimization steps') parser.add_argument('--num_buckets', type=int, default=1, help='Numbe...
Cache the processed npy dataset the dataset into a npz Parameters ---------- dataset : SimpleDataset file_path : str
def _cache_dataset(dataset, prefix): """Cache the processed npy dataset the dataset into a npz Parameters ---------- dataset : SimpleDataset file_path : str """ if not os.path.exists(_constants.CACHE_PATH): os.makedirs(_constants.CACHE_PATH) src_data = np.concatenate([e[0] for e...
Load translation dataset Parameters ---------- dataset : str args : argparse result Returns -------
def load_translation_data(dataset, bleu, args): """Load translation dataset Parameters ---------- dataset : str args : argparse result Returns ------- """ src_lang, tgt_lang = args.src_lang, args.tgt_lang if dataset == 'IWSLT2015': common_prefix = 'IWSLT2015_{}_{}_{}_{...
Create data loaders for training/validation/test.
def make_dataloader(data_train, data_val, data_test, args, use_average_length=False, num_shards=0, num_workers=8): """Create data loaders for training/validation/test.""" data_train_lengths = get_data_lengths(data_train) data_val_lengths = get_data_lengths(data_val) data_test_lengths...
Method representing the process’s activity.
def run(self): """Method representing the process’s activity.""" random.seed(self.seed) np.random.seed(self.np_seed) if not isinstance(self, multiprocessing.Process): # Calling mxnet methods in a subprocess will raise an exception if # mxnet is built with GPU supp...
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`.
def forward(self, inputs, states=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`.""" batch_size = inputs.shape[self._batch_axis] skip_states = states is None if skip_states: ...
Compute embedding of words in batch. Parameters ---------- words : mx.nd.NDArray Array of token indices.
def hybrid_forward(self, F, words, weight): """Compute embedding of words in batch. Parameters ---------- words : mx.nd.NDArray Array of token indices. """ #pylint: disable=arguments-differ embeddings = F.sparse.dot(words, weight) return embe...
Create an instance of the class and load weights. Load the weights from the fastText binary format created by https://github.com/facebookresearch/fastText Parameters ---------- path : str Path to the .bin model file. ctx : mx.Context, default mx.cpu() ...
def load_fasttext_format(cls, path, ctx=cpu(), **kwargs): """Create an instance of the class and load weights. Load the weights from the fastText binary format created by https://github.com/facebookresearch/fastText Parameters ---------- path : str Path to t...
Config the logging.
def logging_config(logpath=None, level=logging.DEBUG, console_level=logging.INFO, no_console=False): """ Config the logging. """ logger = logging.getLogger('nli') # Remove all the current handlers for handler in logger.handlers: lo...
Parse command line arguments.
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='GloVe with GluonNLP', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Data options group = parser.add_argument_group('Data arguments') group.add_argument( 'cooccurr...
Helper function to get training data.
def get_train_data(args): """Helper function to get training data.""" counter = dict() with io.open(args.vocab, 'r', encoding='utf-8') as f: for line in f: token, count = line.split('\t') counter[token] = int(count) vocab = nlp.Vocab(counter, unknown_token=None, padding_t...
Training helper.
def train(args): """Training helper.""" vocab, row, col, counts = get_train_data(args) model = GloVe(token_to_idx=vocab.token_to_idx, output_dim=args.emsize, dropout=args.dropout, x_max=args.x_max, alpha=args.alpha, weight_initializer=mx.init.Uniform(scale=1 / args.emsize...
Log to a file.
def log(args, kwargs): """Log to a file.""" logfile = os.path.join(args.logdir, 'log.tsv') if 'log_created' not in globals(): if os.path.exists(logfile): logging.error('Logfile %s already exists.', logfile) sys.exit(1) global log_created log_created = sorte...
Compute embedding of words in batch. Parameters ---------- row : mxnet.nd.NDArray or mxnet.sym.Symbol Array of token indices for source words. Shape (batch_size, ). row : mxnet.nd.NDArray or mxnet.sym.Symbol Array of token indices for context words. Shape (batch_...
def hybrid_forward(self, F, row, col, counts): """Compute embedding of words in batch. Parameters ---------- row : mxnet.nd.NDArray or mxnet.sym.Symbol Array of token indices for source words. Shape (batch_size, ). row : mxnet.nd.NDArray or mxnet.sym.Symbol ...
Updates the internal evaluation result. Parameters ---------- labels : list of `NDArray` The labels of the data with class indices as values, one per sample. preds : list of `NDArray` Prediction values for samples. Each prediction value can either be the class in...
def update(self, labels, preds, masks=None): # pylint: disable=arguments-differ """Updates the internal evaluation result. Parameters ---------- labels : list of `NDArray` The labels of the data with class indices as values, one per sample. preds : list of `N...
Predict the relation of two sentences. Parameters ---------- sentence1 : NDArray Shape (batch_size, length) sentence2 : NDArray Shape (batch_size, length) Returns ------- pred : NDArray Shape (batch_size, num_classes). num_cla...
def hybrid_forward(self, F, sentence1, sentence2): """ Predict the relation of two sentences. Parameters ---------- sentence1 : NDArray Shape (batch_size, length) sentence2 : NDArray Shape (batch_size, length) Returns ------- ...
Compute intra-sentence attention given embedded words. Parameters ---------- feature_a : NDArray Shape (batch_size, length, hidden_size) Returns ------- alpha : NDArray Shape (batch_size, length, hidden_size)
def hybrid_forward(self, F, feature_a): """ Compute intra-sentence attention given embedded words. Parameters ---------- feature_a : NDArray Shape (batch_size, length, hidden_size) Returns ------- alpha : NDArray Shape (batch_size...
Forward of Decomposable Attention layer
def hybrid_forward(self, F, a, b): """ Forward of Decomposable Attention layer """ # a.shape = [B, L1, H] # b.shape = [B, L2, H] # extract features tilde_a = self.f(a) # shape = [B, L1, H] tilde_b = self.f(b) # shape = [B, L2, H] # attention ...
r"""Counts tokens in the specified string. For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may look like:: (td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd) Parameters ---------- tokens : list of str A source list of tok...
def count_tokens(tokens, to_lower=False, counter=None): r"""Counts tokens in the specified string. For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may look like:: (td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd) Parameters ----...
Slice a flat sequence of tokens into sequences tokens, with each inner sequence's length equal to the specified `length`, taking into account the requested sequence overlap. Parameters ---------- sequence : list of object A flat list of tokens. length : int The length of each of...
def slice_sequence(sequence, length, pad_last=False, pad_val=C.PAD_TOKEN, overlap=0): """Slice a flat sequence of tokens into sequences tokens, with each inner sequence's length equal to the specified `length`, taking into account the requested sequence overlap. Parameters ---------- sequence :...
Calculate the padding length needed for sliced samples in order not to discard data. Parameters ---------- num_items : int Number of items in dataset before collating. length : int The length of each of the samples. overlap : int, default 0 The extra number of items in curre...
def _slice_pad_length(num_items, length, overlap=0): """Calculate the padding length needed for sliced samples in order not to discard data. Parameters ---------- num_items : int Number of items in dataset before collating. length : int The length of each of the samples. overlap...
Split the dataset into training and validation sets. Parameters ---------- dataset : list A list of training samples. valid_ratio : float, default 0.05 Proportion of training samples to use for validation set range: [0, 1] Returns ------- train : SimpleDataset v...
def train_valid_split(dataset, valid_ratio=0.05): """Split the dataset into training and validation sets. Parameters ---------- dataset : list A list of training samples. valid_ratio : float, default 0.05 Proportion of training samples to use for validation set range: [0, 1]...
Load the accompanying vocabulary object for pre-trained model. Parameters ---------- name : str Name of the vocabulary, usually the name of the dataset. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. cls...
def _load_pretrained_vocab(name, root=os.path.join(get_home_dir(), 'models'), cls=None): """Load the accompanying vocabulary object for pre-trained model. Parameters ---------- name : str Name of the vocabulary, usually the name of the dataset. root : str, default '$MXNET_HOME/models' ...
Extract archive file Parameters ---------- file : str Absolute path of the archive file. target_dir : str Target directory of the archive to be uncompressed
def _extract_archive(file, target_dir): """Extract archive file Parameters ---------- file : str Absolute path of the archive file. target_dir : str Target directory of the archive to be uncompressed """ if file.endswith('.gz') or file.endswith('.tar') or file.endswith('.tg...
Discards tokens with frequency below min_frequency and represents them as `unknown_token`. Parameters ---------- min_freq: int Tokens whose frequency is under min_freq is counted as `unknown_token` in the Counter returned. unknown_token: str T...
def discard(self, min_freq, unknown_token): """Discards tokens with frequency below min_frequency and represents them as `unknown_token`. Parameters ---------- min_freq: int Tokens whose frequency is under min_freq is counted as `unknown_token` in the Cou...
Training function.
def train(): """Training function.""" trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr, 'beta2': 0.98, 'epsilon': 1e-9}) train_data_loader, val_data_loader, test_data_loader \ = dataprocessor.make_dataloader(data_train, data_val, ...
r""" Forward computation for highway layer Parameters ---------- inputs: NDArray The input tensor is of shape `(..., input_size)`. Returns ---------- outputs: NDArray The output tensor is of the same shape with input tensor `(..., input_s...
def hybrid_forward(self, F, inputs, **kwargs): # pylint: disable=unused-argument r""" Forward computation for highway layer Parameters ---------- inputs: NDArray The input tensor is of shape `(..., input_size)`. Returns ---------- out...
Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_length) Input words for the sequences. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to i...
def forward(self, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ """Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_length) Input words for the sequences. ...
Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs : NDArray The input data layout='TNC'. states : Tuple[List[List[NDArray]]] The states. including: s...
def hybrid_forward(self, F, inputs, states=None, mask=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- ...
Read tokens from the provided parse tree in the SNLI dataset. Illegal examples are removed.
def main(args): """ Read tokens from the provided parse tree in the SNLI dataset. Illegal examples are removed. """ examples = [] with open(args.input, 'r') as fin: reader = csv.DictReader(fin, delimiter='\t') for cols in reader: s1 = read_tokens(cols['sentence1_parse...