Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def train(args):
train_file = args.input
test_file = args.validation
ngram_range = args.ngrams
logging.info('Ngrams range for the training run : %s', ngram_range)
logging.info('Loading Training data')
train_labels, train_data = read_input_data(tr... | [
"Training function that orchestrates the Classification! "
] |
Please provide a description of the function:def hybrid_forward(self, F, inputs, token_types, valid_length=None):
# pylint: disable=arguments-differ
# pylint: disable=unused-argument
bert_output = self.bert(inputs, token_types, valid_length)
output = self.span_classifier(bert_ou... | [
"Generate the unnormalized score for the given the input sequences.\n\n Parameters\n ----------\n inputs : NDArray, shape (batch_size, seq_length)\n Input words for the sequences.\n token_types : NDArray, shape (batch_size, seq_length)\n Token types for the sequence... |
Please provide a description of the function:def hybrid_forward(self, F, pred, label): # pylint: disable=arguments-differ
pred = F.split(pred, axis=2, num_outputs=2)
start_pred = pred[0].reshape((0, -3))
start_label = label[0]
end_pred = pred[1].reshape((0, -3))
end_lab... | [
"\n Parameters\n ----------\n pred : NDArray, shape (batch_size, seq_length, 2)\n BERTSquad forward output.\n label : list, length is 2, each shape is (batch_size,1)\n label[0] is the starting position of the answer,\n label[1] is the ending position of t... |
Please provide a description of the function:def encode(self, inputs, states=None, valid_length=None):
return self.encoder(self.src_embed(inputs), states, valid_length) | [
"Encode the input sequence.\n\n Parameters\n ----------\n inputs : NDArray\n states : list of NDArrays or None, default None\n valid_length : NDArray or None, default None\n\n Returns\n -------\n outputs : list\n Outputs of the encoder.\n "
] |
Please provide a description of the function:def decode_seq(self, inputs, states, valid_length=None):
outputs, states, additional_outputs =\
self.decoder.decode_seq(inputs=self.tgt_embed(inputs),
states=states,
valid_le... | [
"Decode given the input sequence.\n\n Parameters\n ----------\n inputs : NDArray\n states : list of NDArrays\n valid_length : NDArray or None, default None\n\n Returns\n -------\n output : NDArray\n The output of the decoder. Shape is (batch_size, l... |
Please provide a description of the function:def decode_step(self, step_input, states):
step_output, states, step_additional_outputs =\
self.decoder(self.tgt_embed(step_input), states)
step_output = self.tgt_proj(step_output)
return step_output, states, step_additional_outpu... | [
"One step decoding of the translation model.\n\n Parameters\n ----------\n step_input : NDArray\n Shape (batch_size,)\n states : list of NDArrays\n\n Returns\n -------\n step_output : NDArray\n Shape (batch_size, C_out)\n states : list\n ... |
Please provide a description of the function:def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): #pylint: disable=arguments-differ
additional_outputs = []
encoder_outputs, encoder_additional_outputs = self.encode(src_seq,
... | [
"Generate the prediction given the src_seq and tgt_seq.\n\n This is used in training an NMT model.\n\n Parameters\n ----------\n src_seq : NDArray\n tgt_seq : NDArray\n src_valid_length : NDArray or None\n tgt_valid_length : NDArray or None\n\n Returns\n ... |
Please provide a description of the function:def create_subword_function(subword_function_name, **kwargs):
create_ = registry.get_create_func(SubwordFunction, 'token embedding')
return create_(subword_function_name, **kwargs) | [
"Creates an instance of a subword function."
] |
Please provide a description of the function:def _index_special_tokens(self, unknown_token, special_tokens):
self._idx_to_token = [unknown_token] if unknown_token else []
if not special_tokens:
self._reserved_tokens = None
else:
self._reserved_tokens = special_t... | [
"Indexes unknown and reserved tokens."
] |
Please provide a description of the function:def _index_counter_keys(self, counter, unknown_token, special_tokens, max_size,
min_freq):
unknown_and_special_tokens = set(special_tokens) if special_tokens else set()
if unknown_token:
unknown_and_special_t... | [
"Indexes keys of `counter`.\n\n\n Indexes keys of `counter` according to frequency thresholds such as `max_size` and\n `min_freq`.\n "
] |
Please provide a description of the function:def set_embedding(self, *embeddings):
if len(embeddings) == 1 and embeddings[0] is None:
self._embedding = None
return
for embs in embeddings:
assert isinstance(embs, emb.TokenEmbedding), \
'The a... | [
"Attaches one or more embeddings to the indexed text tokens.\n\n\n Parameters\n ----------\n embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances\n The embedding to be attached to the indexed tokens. If a tuple of multiple embeddings\n are pro... |
Please provide a description of the function:def to_tokens(self, indices):
to_reduce = False
if not isinstance(indices, (list, tuple)):
indices = [indices]
to_reduce = True
max_idx = len(self._idx_to_token) - 1
tokens = []
for idx in indices:
... | [
"Converts token indices to tokens according to the vocabulary.\n\n\n Parameters\n ----------\n indices : int or list of ints\n A source token index or token indices to be converted.\n\n\n Returns\n -------\n str or list of strs\n A token or a list of t... |
Please provide a description of the function:def to_json(self):
if self._embedding:
warnings.warn('Serialization of attached embedding '
'to json is not supported. '
'You may serialize the embedding to a binary format '
... | [
"Serialize Vocab object to json string.\n\n This method does not serialize the underlying embedding.\n "
] |
Please provide a description of the function:def from_json(cls, json_str):
vocab_dict = json.loads(json_str)
unknown_token = vocab_dict.get('unknown_token')
vocab = cls(unknown_token=unknown_token)
vocab._idx_to_token = vocab_dict.get('idx_to_token')
vocab._token_to_idx... | [
"Deserialize Vocab object from json string.\n\n Parameters\n ----------\n json_str : str\n Serialized json string of a Vocab object.\n\n\n Returns\n -------\n Vocab\n "
] |
Please provide a description of the function:def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx):
hvd.broadcast_parameters(model.collect_params(), root_rank=0)
mlm_metric = nlp.metric.MaskedAccuracy()
nsp_metric = nlp.metric.MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
... | [
"Training function."
] |
Please provide a description of the function:def train():
log.info('Loader Train data...')
if version_2:
train_data = SQuAD('train', version='2.0')
else:
train_data = SQuAD('train', version='1.1')
log.info('Number of records in Train data:{}'.format(len(train_data)))
train_data... | [
"Training function.",
"set new learning rate"
] |
Please provide a description of the function:def evaluate():
log.info('Loader dev data...')
if version_2:
dev_data = SQuAD('dev', version='2.0')
else:
dev_data = SQuAD('dev', version='1.1')
log.info('Number of records in Train data:{}'.format(len(dev_data)))
dev_dataset = dev_d... | [
"Evaluate the model on validation dataset.\n "
] |
Please provide a description of the function:def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype):
if isinstance(arrs[0], mx.nd.NDArray):
dtype = arrs[0].dtype if dtype is None else dtype
arrs = [arr.asnumpy() for arr in arrs]
elif not isinstance(arrs[0], np.ndarray):... | [
"Inner Implementation of the Pad batchify\n\n Parameters\n ----------\n arrs : list\n pad_axis : int\n pad_val : number\n use_shared_mem : bool, default False\n\n Returns\n -------\n ret : NDArray\n original_length : NDArray\n "
] |
Please provide a description of the function:def train(self, train_file, dev_file, test_file, save_dir, pretrained_embeddings=None, min_occur_count=2,
lstm_layers=3, word_dims=100, tag_dims=100, dropout_emb=0.33, lstm_hiddens=400,
dropout_lstm_input=0.33, dropout_lstm_hidden=0.33, mlp_arc_si... | [
"Train a deep biaffine dependency parser\n\n Parameters\n ----------\n train_file : str\n path to training set\n dev_file : str\n path to dev set\n test_file : str\n path to test set\n save_dir : str\n a directory for saving model... |
Please provide a description of the function:def load(self, path):
config = _Config.load(os.path.join(path, 'config.pkl'))
config.save_dir = path # redirect root path to what user specified
self._vocab = vocab = ParserVocabulary.load(config.save_vocab_path)
with mx.Context(mxne... | [
"Load from disk\n\n Parameters\n ----------\n path : str\n path to the directory which typically contains a config.pkl file and a model.bin file\n\n Returns\n -------\n DepParser\n parser itself\n "
] |
Please provide a description of the function:def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000):
parser = self._parser
vocab = self._vocab
with mx.Context(mxnet_prefer_gpu()):
UAS, LAS, speed = evaluate_official_script(parser... | [
"Run evaluation on test set\n\n Parameters\n ----------\n test_file : str\n path to test set\n save_dir : str\n where to store intermediate results and log\n logger : logging.logger\n logger for printing results\n num_buckets_test : int\n ... |
Please provide a description of the function:def parse(self, sentence):
words = np.zeros((len(sentence) + 1, 1), np.int32)
tags = np.zeros((len(sentence) + 1, 1), np.int32)
words[0, 0] = ParserVocabulary.ROOT
tags[0, 0] = ParserVocabulary.ROOT
vocab = self._vocab
... | [
"Parse raw sentence into ConllSentence\n\n Parameters\n ----------\n sentence : list\n a list of (word, tag) tuples\n\n Returns\n -------\n ConllSentence\n ConllSentence object\n "
] |
Please provide a description of the function:def apply_weight_drop(block, local_param_regex, rate, axes=(),
weight_dropout_mode='training'):
if not rate:
return
existing_params = _find_params(block, local_param_regex)
for (local_param_name, param), \
(ref_para... | [
"Apply weight drop to the parameter of a block.\n\n Parameters\n ----------\n block : Block or HybridBlock\n The block whose parameter is to be applied weight-drop.\n local_param_regex : str\n The regex for parameter names used in the self.params.get(), such as 'weight'.\n rate : float\... |
Please provide a description of the function: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):
assert mode == '... | [
"create rnn cell given specs\n\n Parameters\n ----------\n mode : str\n The type of RNN cell to use. Options are 'lstmpc', 'rnn_tanh', 'rnn_relu', 'lstm', 'gru'.\n num_layers : int\n The number of RNN cells in the encoder.\n input_size : int\n The initial input size of in the RNN... |
Please provide a description of the function:def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout):
if mode == 'rnn_relu':
rnn_block = functools.partial(rnn.RNN, activation='relu')
elif mode == 'rnn_tanh':
rnn_block = functools.partial(rnn.RNN, activation='t... | [
"create rnn layer given specs"
] |
Please provide a description of the function:def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all):
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)... | [
"Forward computation."
] |
Please provide a description of the function:def hybrid_forward(self, F, x, sampled_values, label, weight, bias):
sampled_candidates, _, _ = sampled_values
# (batch_size,)
label = F.reshape(label, shape=(-1,))
# (num_sampled+batch_size,)
ids = F.concat(sampled_candidates... | [
"Forward computation."
] |
Please provide a description of the function:def forward(self, x, sampled_values, label):
sampled_candidates, _, _ = sampled_values
# (batch_size,)
label = label.reshape(shape=(-1,))
# (num_sampled+batch_size,)
ids = nd.concat(sampled_candidates, label, dim=0)
# ... | [
"Forward computation."
] |
Please provide a description of the function:def _extract_and_flatten_nested_structure(data, flattened=None):
if flattened is None:
flattened = []
structure = _extract_and_flatten_nested_structure(data, flattened)
return structure, flattened
if isinstance(data, list):
return... | [
"Flatten the structure of a nested container to a list.\n\n Parameters\n ----------\n data : A single NDArray/Symbol or nested container with NDArrays/Symbol.\n The nested container to be flattened.\n flattened : list or None\n The container thats holds flattened result.\n Returns\n ... |
Please provide a description of the function:def _reconstruct_flattened_structure(structure, flattened):
if isinstance(structure, list):
return list(_reconstruct_flattened_structure(x, flattened) for x in structure)
elif isinstance(structure, tuple):
return tuple(_reconstruct_flattened_stru... | [
"Reconstruct the flattened list back to (possibly) nested structure.\n\n Parameters\n ----------\n structure : An integer or a nested container with integers.\n The extracted structure of the container of `data`.\n flattened : list or None\n The container thats holds flattened result.\n ... |
Please provide a description of the function:def _expand_to_beam_size(data, beam_size, batch_size, state_info=None):
assert not state_info or isinstance(state_info, (type(data), dict)), \
'data and state_info doesn\'t match, ' \
'got: {} vs {}.'.format(type(state_info), type(data))
... | [
"Tile all the states to have batch_size * beam_size on the batch axis.\n\n Parameters\n ----------\n data : A single NDArray/Symbol or nested container with NDArrays/Symbol\n Each NDArray/Symbol should have shape (N, ...) when state_info is None,\n or same as the layout in state_info when it'... |
Please provide a description of the function:def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states):
beam_size = self._beam_size
# outputs: (batch_size, beam_size, vocab_size)
outputs = outputs.reshape(shape=(-4, -1, beam_size, 0))
smoothed_... | [
"\n Parameters\n ----------\n F\n samples : NDArray or Symbol\n The current samples generated by beam search. Shape (batch_size, beam_size, L)\n valid_length : NDArray or Symbol\n The current valid lengths of the samples\n outputs: NDArray or Symbol\n ... |
Please provide a description of the function:def hybrid_forward(self, F, inputs, states): # pylint: disable=arguments-differ
batch_size = self._batch_size
beam_size = self._beam_size
vocab_size = self._vocab_size
# Tile the states and inputs to have shape (batch_size * beam_si... | [
"Sample by beam search.\n\n Parameters\n ----------\n F\n inputs : NDArray or Symbol\n The initial input of the decoder. Shape is (batch_size,).\n states : Object that contains NDArrays or Symbols\n The initial states of the decoder.\n Returns\n ... |
Please provide a description of the function:def data(self, ctx=None):
d = self._check_and_get(self._data, ctx)
if self._rate:
d = nd.Dropout(d, self._rate, self._mode, self._axes)
return d | [
"Returns a copy of this parameter on one context. Must have been\n initialized on this context before.\n\n Parameters\n ----------\n ctx : Context\n Desired context.\n Returns\n -------\n NDArray on ctx\n "
] |
Please provide a description of the function:def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r
predefined_args = {'rnn_type': 'lstmpc',
'output_size': 12... | [
"ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer.\n\n Parameters\n ----------\n dataset_name : str or None, default None\n The dataset name on which the pre-trained model is trained.\n Options are 'gbw'.\n pretrained : bool, default False\n Whether t... |
Please provide a description of the function:def hybrid_forward(self, F, inputs):
# pylint: disable=arguments-differ
# the character id embedding
# (batch_size * sequence_length, max_chars_per_token, embed_dim)
character_embedding = self._char_embedding(inputs.reshape((-1, self.... | [
"\n Compute context insensitive token embeddings for ELMo representations.\n\n Parameters\n ----------\n inputs : NDArray\n Shape (batch_size, sequence_length, max_character_per_token)\n of character ids representing the current batch.\n\n Returns\n --... |
Please provide a description of the function:def hybrid_forward(self, F, inputs, states=None, mask=None):
# pylint: disable=arguments-differ
type_representation = self._elmo_char_encoder(inputs)
type_representation = type_representation.transpose(axes=(1, 0, 2))
lstm_outputs, s... | [
"\n Parameters\n ----------\n inputs : NDArray\n Shape (batch_size, sequence_length, max_character_per_token)\n of character ids representing the current batch.\n states : (list of list of NDArray, list of list of NDArray)\n The states. First tuple elemen... |
Please provide a description of the function:def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r
predefined_args = {'embed_size': 400,
'hidden_size': 1150,
'm... | [
"3-layer LSTM language model with weight-drop, variational dropout, and tied weights.\n\n Embedding size is 400, and hidden layer size is 1150.\n\n Parameters\n ----------\n dataset_name : str or None, default None\n The dataset name on which the pre-trained model is trained.\n Options are... |
Please provide a description of the function:def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r
predefined_args = {'embed_size': 200,
'hidden_size': 200,
... | [
"Standard 2-layer LSTM language model with tied embedding and output weights.\n\n Both embedding and hidden dimensions are 200.\n\n Parameters\n ----------\n dataset_name : str or None, default None\n The dataset name on which the pre-trained model is trained.\n Options are 'wikitext-2'. I... |
Please provide a description of the function: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
predefined_args = {'embed_size': 512,
'hidden_size': 2048,
... | [
"Big 1-layer LSTMP language model.\n\n Both embedding and projection size are 512. Hidden size is 2048.\n\n Parameters\n ----------\n dataset_name : str or None, default None\n The dataset name on which the pre-trained model is trained.\n Options are 'gbw'. If specified, then the returned ... |
Please provide a description of the function:def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ
encoded = self.embedding(inputs)
if begin_state is None:
begin_state = self.begin_state(batch_size=inputs.shape[1])
out_states = []
for i, (e,... | [
"Implement forward computation.\n\n Parameters\n -----------\n inputs : NDArray\n input tensor with shape `(sequence_length, batch_size)`\n when `layout` is \"TNC\".\n begin_state : list\n initial recurrent state tensor with length equals to num_layers.\n... |
Please provide a description of the function:def forward(self, inputs, begin_state): # pylint: disable=arguments-differ
encoded = self.embedding(inputs)
length = inputs.shape[0]
batch_size = inputs.shape[1]
encoded, state = self.encoder.unroll(length, encoded, begin_state,
... | [
"Implement forward computation.\n\n Parameters\n -----------\n inputs : NDArray\n input tensor with shape `(sequence_length, batch_size)`\n when `layout` is \"TNC\".\n begin_state : list\n initial recurrent state tensor with length equals to num_layers*2.... |
Please provide a description of the function:def _get_cell_type(cell_type):
if isinstance(cell_type, str):
if cell_type == 'lstm':
return rnn.LSTMCell
elif cell_type == 'gru':
return rnn.GRUCell
elif cell_type == 'relu_rnn':
return partial(rnn.RNNCell... | [
"Get the object type of the cell by parsing the input\n\n Parameters\n ----------\n cell_type : str or type\n\n Returns\n -------\n cell_constructor: type\n The constructor of the RNNCell\n "
] |
Please provide a description of the function:def _get_context(center_idx, sentence_boundaries, window_size,
random_window_size, seed):
random.seed(seed + center_idx)
sentence_index = np.searchsorted(sentence_boundaries, center_idx)
sentence_start, sentence_end = _get_sentence_start_en... | [
"Compute the context with respect to a center word in a sentence.\n\n Takes an numpy array of sentences boundaries.\n\n "
] |
Please provide a description of the function:def model(dropout, vocab, model_mode, output_size):
textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\
output_size=output_size)
textCNN.hybridize()
return textCNN | [
"Construct the model."
] |
Please provide a description of the function:def init(textCNN, vocab, model_mode, context, lr):
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':
t... | [
"Initialize parameters."
] |
Please provide a description of the function:def preprocess_dataset(dataset, transform, num_workers=8):
worker_fn = partial(_worker_fn, transform=transform)
start = time.time()
pool = mp.Pool(num_workers)
dataset_transform = []
dataset_len = []
for data in pool.map(worker_fn, dataset):
... | [
"Use multiprocessing to perform transform for dataset.\n\n Parameters\n ----------\n dataset: dataset-like object\n Source dataset.\n transform: callable\n Transformer function.\n num_workers: int, default 8\n The number of multiprocessing workers to use for data preprocessing.\n... |
Please provide a description of the function:def get_model(name, dataset_name='wikitext-2', **kwargs):
models = {'standard_lstm_lm_200' : standard_lstm_lm_200,
'standard_lstm_lm_650' : standard_lstm_lm_650,
'standard_lstm_lm_1500': standard_lstm_lm_1500,
'awd_lstm_lm_1... | [
"Returns a pre-defined model by name.\n\n Parameters\n ----------\n name : str\n Name of the model.\n dataset_name : str or None, default 'wikitext-2'.\n The dataset name on which the pre-trained model is trained.\n For language model, options are 'wikitext-2'.\n For ELMo, Op... |
Please provide a description of the function:def _masked_softmax(F, att_score, mask, dtype):
if mask is not None:
# Fill in the masked scores with a very small value
neg = -1e4 if np.dtype(dtype) == np.float16 else -1e18
att_score = F.where(mask, att_score, neg * F.ones_like(att_score))... | [
"Ignore the masked elements when calculating the softmax\n\n Parameters\n ----------\n F : symbol or ndarray\n att_score : Symborl or NDArray\n Shape (batch_size, query_length, memory_length)\n mask : Symbol or NDArray or None\n Shape (batch_size, query_length, memory_length)\n Retur... |
Please provide a description of the function:def _read_by_weight(self, F, att_weights, value):
output = F.batch_dot(att_weights, value)
return output | [
"Read from the value matrix given the attention weights.\n\n Parameters\n ----------\n F : symbol or ndarray\n att_weights : Symbol or NDArray\n Attention weights.\n For single-head attention,\n Shape (batch_size, query_length, memory_length).\n ... |
Please provide a description of the function:def translate(self, src_seq, src_valid_length):
batch_size = src_seq.shape[0]
encoder_outputs, _ = self._model.encode(src_seq, valid_length=src_valid_length)
decoder_states = self._model.decoder.init_state_from_encoder(encoder_outputs,
... | [
"Get the translation result given the input sentence.\n\n Parameters\n ----------\n src_seq : mx.nd.NDArray\n Shape (batch_size, length)\n src_valid_length : mx.nd.NDArray\n Shape (batch_size,)\n\n Returns\n -------\n samples : NDArray\n ... |
Please provide a description of the function:def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file,
debug=False):
if output_file is None:
output_file = tempfile.NamedTemporaryFile().name
data_loader = DataLoader(test_file,... | [
"Evaluate parser on a data set\n\n Parameters\n ----------\n parser : BiaffineParser\n biaffine parser\n vocab : ParserVocabulary\n vocabulary built from data set\n num_buckets_test : int\n size of buckets (cluster sentences into this number of clusters)\n test_batch_size : in... |
Please provide a description of the function:def parameter_from_numpy(self, name, array):
p = self.params.get(name, shape=array.shape, init=mx.init.Constant(array))
return p | [
" Create parameter with its value initialized according to a numpy tensor\n\n Parameters\n ----------\n name : str\n parameter name\n array : np.ndarray\n initiation value\n\n Returns\n -------\n mxnet.gluon.parameter\n a parameter ob... |
Please provide a description of the function:def parameter_init(self, name, shape, init):
p = self.params.get(name, shape=shape, init=init)
return p | [
"Create parameter given name, shape and initiator\n\n Parameters\n ----------\n name : str\n parameter name\n shape : tuple\n parameter shape\n init : mxnet.initializer\n an initializer\n\n Returns\n -------\n mxnet.gluon.param... |
Please provide a description of the function:def forward(self, word_inputs, tag_inputs, arc_targets=None, rel_targets=None):
is_train = autograd.is_training()
def flatten_numpy(ndarray):
return np.reshape(ndarray, (-1,), 'F')
batch_size = word_inputs.shape[1]
... | [
"Run decoding\n\n Parameters\n ----------\n word_inputs : mxnet.ndarray.NDArray\n word indices of seq_len x batch_size\n tag_inputs : mxnet.ndarray.NDArray\n tag indices of seq_len x batch_size\n arc_targets : mxnet.ndarray.NDArray\n gold arc indic... |
Please provide a description of the function:def save_parameters(self, filename):
params = self._collect_params_with_prefix()
if self.pret_word_embs: # don't save word embeddings inside model
params.pop('pret_word_embs.weight', None)
arg_dict = {key: val._reduce() for key, ... | [
"Save model\n\n Parameters\n ----------\n filename : str\n path to model file\n "
] |
Please provide a description of the function:def _worker_fn(samples, batchify_fn, dataset=None):
# 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 in new pr... | [
"Function for processing data in worker process."
] |
Please provide a description of the function:def _thread_worker_fn(samples, batchify_fn, dataset):
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 batch | [
"Threadpool worker function for processing data."
] |
Please provide a description of the function:def create(embedding_name, **kwargs):
create_text_embedding = registry.get_create_func(TokenEmbedding, 'token embedding')
return create_text_embedding(embedding_name, **kwargs) | [
"Creates an instance of token embedding.\n\n\n Creates a token embedding instance by loading embedding vectors from an externally hosted\n pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid\n `embedding_name` and `source`, use :func:`gluonnlp.embedding.list_sources`... |
Please provide a description of the function:def list_sources(embedding_name=None):
text_embedding_reg = registry.get_registry(TokenEmbedding)
if embedding_name is not None:
embedding_name = embedding_name.lower()
if embedding_name not in text_embedding_reg:
raise KeyError('Ca... | [
"Get valid token embedding names and their pre-trained file names.\n\n\n To load token embedding vectors from an externally hosted pre-trained token embedding file,\n such as those of GloVe and FastText, one should use\n `gluonnlp.embedding.create(embedding_name, source)`. This method returns all the\n ... |
Please provide a description of the function:def _load_embedding(self, pretrained_file_path, elem_delim,
encoding='utf8'):
pretrained_file_path = os.path.expanduser(pretrained_file_path)
if not os.path.isfile(pretrained_file_path):
raise ValueError('`pretra... | [
"Load embedding vectors from a pre-trained token embedding file.\n\n Both text files and TokenEmbedding serialization files are supported.\n elem_delim and encoding are ignored for non-text files.\n\n For every unknown token, if its representation `self.unknown_token` is encountered in the\n ... |
Please provide a description of the function:def _load_embedding_txt(self, pretrained_file_path, elem_delim, encoding='utf8'):
vec_len = None
all_elems = []
tokens = set()
loaded_unknown_vec = None
with io.open(pretrained_file_path, 'rb') as f:
for line_num,... | [
"Load embedding vectors from a pre-trained token embedding file.\n\n For every unknown token, if its representation `self.unknown_token` is encountered in the\n pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token\n embedding vector loaded from the file; ... |
Please provide a description of the function:def _load_embedding_serialized(self, pretrained_file_path):
deserialized_embedding = TokenEmbedding.deserialize(pretrained_file_path)
if deserialized_embedding.unknown_token:
# Some .npz files on S3 may contain an unknown token and its
... | [
"Load embedding vectors from a pre-trained token embedding file.\n\n For every unknown token, if its representation `self.unknown_token` is encountered in the\n pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token\n embedding vector loaded from the file; ... |
Please provide a description of the function:def _check_vector_update(self, tokens, new_embedding):
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 isinstance(new_embedding, nd.NDArra... | [
"Check that tokens and embedding are in the format for __setitem__."
] |
Please provide a description of the function:def _check_source(cls, source_file_hash, source):
embedding_name = cls.__name__.lower()
if source not in source_file_hash:
raise KeyError('Cannot find pre-trained source {} for token embedding {}. '
'Valid pre-t... | [
"Checks if a pre-trained token embedding source name is valid.\n\n\n Parameters\n ----------\n source : str\n The pre-trained token embedding source.\n "
] |
Please provide a description of the function:def from_file(file_path, elem_delim=' ', encoding='utf8', **kwargs):
embedding = TokenEmbedding(**kwargs)
embedding._load_embedding(file_path, elem_delim=elem_delim, encoding=encoding)
return embedding | [
"Creates a user-defined token embedding from a pre-trained embedding file.\n\n\n This is to load embedding vectors from a user-defined pre-trained token embedding file.\n For example, if `elem_delim` = ' ', the expected format of a custom pre-trained token\n embedding file may look like:\n\n ... |
Please provide a description of the function:def serialize(self, file_path, compress=True):
if self.unknown_lookup is not None:
warnings.warn(
'Serialization of `unknown_lookup` is not supported. '
'Save it manually and pass the loaded lookup object '
... | [
"Serializes the TokenEmbedding to a file specified by file_path.\n\n TokenEmbedding is serialized by converting the list of tokens, the\n array of word embeddings and other metadata to numpy arrays, saving all\n in a single (optionally compressed) Zipfile. See\n https://docs.scipy.org/do... |
Please provide a description of the function:def deserialize(cls, file_path, **kwargs):
# idx_to_token is of dtype 'O' so we need to allow pickle
npz_dict = np.load(file_path, allow_pickle=True)
unknown_token = npz_dict['unknown_token']
if not unknown_token:
unknown... | [
"Create a new TokenEmbedding from a serialized one.\n\n TokenEmbedding is serialized by converting the list of tokens, the\n array of word embeddings and other metadata to numpy arrays, saving all\n in a single (optionally compressed) Zipfile. See\n https://docs.scipy.org/doc/numpy-1.14.... |
Please provide a description of the function:def evaluate(data_source):
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').... | [
"Evaluate the model on a mini-batch.\n "
] |
Please provide a description of the function:def register(class_=None, **kwargs):
def _real_register(class_):
# Assert that the passed kwargs are meaningful
for kwarg_name, values in kwargs.items():
try:
real_args = inspect.getfullargspec(class_).args
ex... | [
"Registers a dataset with segment specific hyperparameters.\n\n When passing keyword arguments to `register`, they are checked to be valid\n keyword arguments for the registered Dataset class constructor and are\n saved in the registry. Registered keyword arguments can be retrieved with\n the `list_data... |
Please provide a description of the function:def create(name, **kwargs):
create_ = registry.get_create_func(Dataset, 'dataset')
return create_(name, **kwargs) | [
"Creates an instance of a registered dataset.\n\n Parameters\n ----------\n name : str\n The dataset name (case-insensitive).\n\n Returns\n -------\n An instance of :class:`mxnet.gluon.data.Dataset` constructed with the\n keyword arguments passed to the create function.\n\n "
] |
Please provide a description of the function:def list_datasets(name=None):
reg = registry.get_registry(Dataset)
if name is not None:
class_ = reg[name.lower()]
return _REGSITRY_NAME_KWARGS[class_]
else:
return {
dataset_name: _REGSITRY_NAME_KWARGS[class_]
... | [
"Get valid datasets and registered parameters.\n\n Parameters\n ----------\n name : str or None, default None\n Return names and registered parameters of registered datasets. If name\n is specified, only registered parameters of the respective dataset are\n returned.\n\n Returns\n ... |
Please provide a description of the function:def parse_args():
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=... | [
"Parse command line arguments."
] |
Please provide a description of the function:def get_vocab(args):
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')... | [
"Compute the vocabulary."
] |
Please provide a description of the function:def forward(self, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ
_, pooler_out = self.bert(inputs, token_types, valid_length)
return self.classifier(pooler_out) | [
"Generate the unnormalized score for the given the input sequences.\n\n Parameters\n ----------\n inputs : NDArray, shape (batch_size, seq_length)\n Input words for the sequences.\n token_types : NDArray, shape (batch_size, seq_length)\n Token types for the sequence... |
Please provide a description of the function:def add_parameters(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.data.wor... | [
"Add evaluation specific parameters to parser."
] |
Please provide a description of the function:def validate_args(args):
# 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_similarity_datas... | [
"Validate provided arguments and act on --help."
] |
Please provide a description of the function:def iterate_similarity_datasets(args):
for dataset_name in args.similarity_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_val... | [
"Generator over all similarity evaluation datasets.\n\n Iterates over dataset names, keyword arguments for their creation and the\n created dataset.\n\n "
] |
Please provide a description of the function:def iterate_analogy_datasets(args):
for dataset_name in args.analogy_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_values))
... | [
"Generator over all analogy evaluation datasets.\n\n Iterates over dataset names, keyword arguments for their creation and the\n created dataset.\n\n "
] |
Please provide a description of the function:def get_similarity_task_tokens(args):
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 occurring the evaluation datasets."
] |
Please provide a description of the function:def get_analogy_task_tokens(args):
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 tokens | [
"Returns a set of all tokens occuring the evaluation datasets."
] |
Please provide a description of the function:def evaluate_similarity(args, token_embedding, ctx, logfile=None,
global_step=0):
results = []
for similarity_function in args.similarity_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
idx_to... | [
"Evaluate on specified similarity datasets."
] |
Please provide a description of the function:def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
results = []
exclude_question_words = not args.analogy_dont_exclude_question_words
for analogy_function in args.analogy_functions:
evaluator = nlp.embedding.evaluation.Wor... | [
"Evaluate on specified analogy datasets.\n\n The analogy task is an open vocabulary task, make sure to pass a\n token_embedding with a sufficiently large number of supported tokens.\n\n "
] |
Please provide a description of the function:def log_similarity_result(logfile, result):
assert result['task'] == 'similarity'
if not logfile:
return
with open(logfile, 'a') as f:
f.write('\t'.join([
str(result['global_step']),
result['task'],
resul... | [
"Log a similarity evaluation result dictionary as TSV to logfile."
] |
Please provide a description of the function:def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
# model
model, vocabulary = nlp.model.get_model(model,
dataset_name=dataset_name,
... | [
"Get model for pre-training."
] |
Please provide a description of the function:def get_pretrain_dataset(data, batch_size, num_ctxes, shuffle, use_avg_len,
num_buckets, num_parts=1, part_idx=0, prefetch=True):
num_files = len(glob.glob(os.path.expanduser(data)))
logging.debug('%d files found.', num_files)
assert... | [
"create dataset for pretraining.",
"create data loader based on the dataset chunk"
] |
Please provide a description of the function:def get_dummy_dataloader(dataloader, 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_shape:
logging.debug('Skip b... | [
"Return a dummy data loader which returns a fixed data batch of target shape"
] |
Please provide a description of the function:def save_params(step_num, model, trainer, ckpt_dir):
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_num, ... | [
"Save the model parameter, marked by step_num."
] |
Please provide a description of the function:def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num,
mlm_metric, nsp_metric, trainer, log_interval):
end_time = time.time()
duration = end_time - begin_time
throughput = running_num_tks / duration / 1000.0
running_ml... | [
"Log training progress."
] |
Please provide a description of the function:def split_and_load(arrs, ctx):
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) | [
"split and load arrays to a list of contexts"
] |
Please provide a description of the function:def forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype):
(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)... | [
"forward computation for evaluation"
] |
Please provide a description of the function:def evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype):
mlm_metric = MaskedAccuracy()
nsp_metric = MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
eval_begin_time = time.time()
begin_time = time.time()
... | [
"Evaluation function."
] |
Please provide a description of the function:def get_argparser():
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,
... | [
"Argument parser"
] |
Please provide a description of the function:def _cache_dataset(dataset, prefix):
if not os.path.exists(_constants.CACHE_PATH):
os.makedirs(_constants.CACHE_PATH)
src_data = np.concatenate([e[0] for e in dataset])
tgt_data = np.concatenate([e[1] for e in dataset])
src_cumlen = np.cumsum([0]... | [
"Cache the processed npy dataset the dataset into a npz\n\n Parameters\n ----------\n dataset : SimpleDataset\n file_path : str\n "
] |
Please provide a description of the function:def load_translation_data(dataset, bleu, args):
src_lang, tgt_lang = args.src_lang, args.tgt_lang
if dataset == 'IWSLT2015':
common_prefix = 'IWSLT2015_{}_{}_{}_{}'.format(src_lang, tgt_lang,
args.sr... | [
"Load translation dataset\n\n Parameters\n ----------\n dataset : str\n args : argparse result\n\n Returns\n -------\n\n "
] |
Please provide a description of the function:def make_dataloader(data_train, data_val, data_test, args,
use_average_length=False, num_shards=0, num_workers=8):
data_train_lengths = get_data_lengths(data_train)
data_val_lengths = get_data_lengths(data_val)
data_test_lengths = get_dat... | [
"Create data loaders for training/validation/test."
] |
Please provide a description of the function:def run(self):
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 support
... | [
"Method representing the process’s activity."
] |
Please provide a description of the function:def forward(self, inputs, states=None): # pylint: disable=arguments-differ
batch_size = inputs.shape[self._batch_axis]
skip_states = states is None
if skip_states:
states = self.cell.begin_state(batch_size, ctx=inputs.context)
... | [
"Defines the forward computation. Arguments can be either\n :py:class:`NDArray` or :py:class:`Symbol`."
] |
Please provide a description of the function:def hybrid_forward(self, F, words, weight):
#pylint: disable=arguments-differ
embeddings = F.sparse.dot(words, weight)
return embeddings | [
"Compute embedding of words in batch.\n\n Parameters\n ----------\n words : mx.nd.NDArray\n Array of token indices.\n\n "
] |
Please provide a description of the function:def load_fasttext_format(cls, path, ctx=cpu(), **kwargs):
with open(path, 'rb') as f:
new_format, dim, bucket, minn, maxn, = cls._read_model_params(f)
idx_to_token = cls._read_vocab(f, new_format)
dim, matrix = cls._read_v... | [
"Create an instance of the class and load weights.\n\n Load the weights from the fastText binary format created by\n https://github.com/facebookresearch/fastText\n\n Parameters\n ----------\n path : str\n Path to the .bin model file.\n ctx : mx.Context, default m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.