repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
dmlc/gluon-nlp
src/gluonnlp/model/language_model.py
standard_lstm_lm_200
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 ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. The pre-trained model achieves 108.25/102.26 ppl on Val and Test of wikitext-2 respectively. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. Returns ------- gluon.Block, gluonnlp.Vocab """ predefined_args = {'embed_size': 200, 'hidden_size': 200, 'mode': 'lstm', 'num_layers': 2, 'tie_weights': True, 'dropout': 0.2} mutable_args = ['dropout'] assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \ 'Cannot override predefined model settings.' predefined_args.update(kwargs) return _get_rnn_model(StandardRNN, 'standard_lstm_lm_200', dataset_name, vocab, pretrained, ctx, root, **predefined_args)
python
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 ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. The pre-trained model achieves 108.25/102.26 ppl on Val and Test of wikitext-2 respectively. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. Returns ------- gluon.Block, gluonnlp.Vocab """ predefined_args = {'embed_size': 200, 'hidden_size': 200, 'mode': 'lstm', 'num_layers': 2, 'tie_weights': True, 'dropout': 0.2} mutable_args = ['dropout'] assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \ 'Cannot override predefined model settings.' predefined_args.update(kwargs) return _get_rnn_model(StandardRNN, 'standard_lstm_lm_200', dataset_name, vocab, pretrained, ctx, root, **predefined_args)
[ "def", "standard_lstm_lm_200", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ")", ",", "*", "*", "kwargs", ")", ":", "predefined_args", "=", "{", "'embed_size'", ":", "200", ",", "'hidden_size'", ":", "200", ",", "'mode'", ":", "'lstm'", ",", "'num_layers'", ":", "2", ",", "'tie_weights'", ":", "True", ",", "'dropout'", ":", "0.2", "}", "mutable_args", "=", "[", "'dropout'", "]", "assert", "all", "(", "(", "k", "not", "in", "kwargs", "or", "k", "in", "mutable_args", ")", "for", "k", "in", "predefined_args", ")", ",", "'Cannot override predefined model settings.'", "predefined_args", ".", "update", "(", "kwargs", ")", "return", "_get_rnn_model", "(", "StandardRNN", ",", "'standard_lstm_lm_200'", ",", "dataset_name", ",", "vocab", ",", "pretrained", ",", "ctx", ",", "root", ",", "*", "*", "predefined_args", ")" ]
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 specified, then the returned vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. The pre-trained model achieves 108.25/102.26 ppl on Val and Test of wikitext-2 respectively. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. Returns ------- gluon.Block, gluonnlp.Vocab
[ "r", "Standard", "2", "-", "layer", "LSTM", "language", "model", "with", "tied", "embedding", "and", "output", "weights", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L276-L317
train
dmlc/gluon-nlp
src/gluonnlp/model/language_model.py
big_rnn_lm_2048_512
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_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 vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. The pre-trained model achieves 44.05 ppl on Test of GBW dataset. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. Returns ------- gluon.Block, gluonnlp.Vocab """ predefined_args = {'embed_size': 512, 'hidden_size': 2048, 'projection_size': 512, 'num_layers': 1, 'embed_dropout': 0.1, 'encode_dropout': 0.1} mutable_args = ['embed_dropout', 'encode_dropout'] assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \ 'Cannot override predefined model settings.' predefined_args.update(kwargs) return _get_rnn_model(BigRNN, 'big_rnn_lm_2048_512', dataset_name, vocab, pretrained, ctx, root, **predefined_args)
python
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_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 vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. The pre-trained model achieves 44.05 ppl on Test of GBW dataset. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. Returns ------- gluon.Block, gluonnlp.Vocab """ predefined_args = {'embed_size': 512, 'hidden_size': 2048, 'projection_size': 512, 'num_layers': 1, 'embed_dropout': 0.1, 'encode_dropout': 0.1} mutable_args = ['embed_dropout', 'encode_dropout'] assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \ 'Cannot override predefined model settings.' predefined_args.update(kwargs) return _get_rnn_model(BigRNN, 'big_rnn_lm_2048_512', dataset_name, vocab, pretrained, ctx, root, **predefined_args)
[ "def", "big_rnn_lm_2048_512", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ")", ",", "*", "*", "kwargs", ")", ":", "predefined_args", "=", "{", "'embed_size'", ":", "512", ",", "'hidden_size'", ":", "2048", ",", "'projection_size'", ":", "512", ",", "'num_layers'", ":", "1", ",", "'embed_dropout'", ":", "0.1", ",", "'encode_dropout'", ":", "0.1", "}", "mutable_args", "=", "[", "'embed_dropout'", ",", "'encode_dropout'", "]", "assert", "all", "(", "(", "k", "not", "in", "kwargs", "or", "k", "in", "mutable_args", ")", "for", "k", "in", "predefined_args", ")", ",", "'Cannot override predefined model settings.'", "predefined_args", ".", "update", "(", "kwargs", ")", "return", "_get_rnn_model", "(", "BigRNN", ",", "'big_rnn_lm_2048_512'", ",", "dataset_name", ",", "vocab", ",", "pretrained", ",", "ctx", ",", "root", ",", "*", "*", "predefined_args", ")" ]
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 vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. The pre-trained model achieves 44.05 ppl on Test of GBW dataset. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. Returns ------- gluon.Block, gluonnlp.Vocab
[ "r", "Big", "1", "-", "layer", "LSTMP", "language", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L512-L553
train
dmlc/gluon-nlp
src/gluonnlp/model/language_model.py
AWDRNN.forward
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 initial recurrent state tensor with length equals to num_layers. the initial state with shape `(1, batch_size, num_hidden)` Returns -------- out: NDArray output tensor with shape `(sequence_length, batch_size, input_size)` when `layout` is "TNC". out_states: list output recurrent state tensor with length equals to num_layers. the state with shape `(1, batch_size, num_hidden)` """ encoded = self.embedding(inputs) if begin_state is None: begin_state = self.begin_state(batch_size=inputs.shape[1]) out_states = [] for i, (e, s) in enumerate(zip(self.encoder, begin_state)): encoded, state = e(encoded, s) out_states.append(state) if self._drop_h and i != len(self.encoder)-1: encoded = nd.Dropout(encoded, p=self._drop_h, axes=(0,)) if self._dropout: encoded = nd.Dropout(encoded, p=self._dropout, axes=(0,)) with autograd.predict_mode(): out = self.decoder(encoded) return out, out_states
python
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 initial recurrent state tensor with length equals to num_layers. the initial state with shape `(1, batch_size, num_hidden)` Returns -------- out: NDArray output tensor with shape `(sequence_length, batch_size, input_size)` when `layout` is "TNC". out_states: list output recurrent state tensor with length equals to num_layers. the state with shape `(1, batch_size, num_hidden)` """ encoded = self.embedding(inputs) if begin_state is None: begin_state = self.begin_state(batch_size=inputs.shape[1]) out_states = [] for i, (e, s) in enumerate(zip(self.encoder, begin_state)): encoded, state = e(encoded, s) out_states.append(state) if self._drop_h and i != len(self.encoder)-1: encoded = nd.Dropout(encoded, p=self._drop_h, axes=(0,)) if self._dropout: encoded = nd.Dropout(encoded, p=self._dropout, axes=(0,)) with autograd.predict_mode(): out = self.decoder(encoded) return out, out_states
[ "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", ",", "s", ")", "in", "enumerate", "(", "zip", "(", "self", ".", "encoder", ",", "begin_state", ")", ")", ":", "encoded", ",", "state", "=", "e", "(", "encoded", ",", "s", ")", "out_states", ".", "append", "(", "state", ")", "if", "self", ".", "_drop_h", "and", "i", "!=", "len", "(", "self", ".", "encoder", ")", "-", "1", ":", "encoded", "=", "nd", ".", "Dropout", "(", "encoded", ",", "p", "=", "self", ".", "_drop_h", ",", "axes", "=", "(", "0", ",", ")", ")", "if", "self", ".", "_dropout", ":", "encoded", "=", "nd", ".", "Dropout", "(", "encoded", ",", "p", "=", "self", ".", "_dropout", ",", "axes", "=", "(", "0", ",", ")", ")", "with", "autograd", ".", "predict_mode", "(", ")", ":", "out", "=", "self", ".", "decoder", "(", "encoded", ")", "return", "out", ",", "out_states" ]
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 initial state with shape `(1, batch_size, num_hidden)` Returns -------- out: NDArray output tensor with shape `(sequence_length, batch_size, input_size)` when `layout` is "TNC". out_states: list output recurrent state tensor with length equals to num_layers. the state with shape `(1, batch_size, num_hidden)`
[ "Implement", "forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L74-L108
train
dmlc/gluon-nlp
src/gluonnlp/model/language_model.py
BigRNN.forward
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 initial recurrent state tensor with length equals to num_layers*2. For each layer the two initial states have shape `(batch_size, num_hidden)` and `(batch_size, num_projection)` Returns -------- out : NDArray output tensor with shape `(sequence_length, batch_size, vocab_size)` when `layout` is "TNC". out_states : list output recurrent state tensor with length equals to num_layers*2. For each layer the two initial states have shape `(batch_size, num_hidden)` and `(batch_size, num_projection)` """ encoded = self.embedding(inputs) length = inputs.shape[0] batch_size = inputs.shape[1] encoded, state = self.encoder.unroll(length, encoded, begin_state, layout='TNC', merge_outputs=True) encoded = encoded.reshape((-1, self._projection_size)) out = self.decoder(encoded) out = out.reshape((length, batch_size, -1)) return out, state
python
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 initial recurrent state tensor with length equals to num_layers*2. For each layer the two initial states have shape `(batch_size, num_hidden)` and `(batch_size, num_projection)` Returns -------- out : NDArray output tensor with shape `(sequence_length, batch_size, vocab_size)` when `layout` is "TNC". out_states : list output recurrent state tensor with length equals to num_layers*2. For each layer the two initial states have shape `(batch_size, num_hidden)` and `(batch_size, num_projection)` """ encoded = self.embedding(inputs) length = inputs.shape[0] batch_size = inputs.shape[1] encoded, state = self.encoder.unroll(length, encoded, begin_state, layout='TNC', merge_outputs=True) encoded = encoded.reshape((-1, self._projection_size)) out = self.decoder(encoded) out = out.reshape((length, batch_size, -1)) return out, state
[ "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", ",", "layout", "=", "'TNC'", ",", "merge_outputs", "=", "True", ")", "encoded", "=", "encoded", ".", "reshape", "(", "(", "-", "1", ",", "self", ".", "_projection_size", ")", ")", "out", "=", "self", ".", "decoder", "(", "encoded", ")", "out", "=", "out", ".", "reshape", "(", "(", "length", ",", "batch_size", ",", "-", "1", ")", ")", "return", "out", ",", "state" ]
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. For each layer the two initial states have shape `(batch_size, num_hidden)` and `(batch_size, num_projection)` Returns -------- out : NDArray output tensor with shape `(sequence_length, batch_size, vocab_size)` when `layout` is "TNC". out_states : list output recurrent state tensor with length equals to num_layers*2. For each layer the two initial states have shape `(batch_size, num_hidden)` and `(batch_size, num_projection)`
[ "Implement", "forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L479-L510
train
dmlc/gluon-nlp
src/gluonnlp/model/seq2seq_encoder_decoder.py
_get_cell_type
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': return rnn.LSTMCell elif cell_type == 'gru': return rnn.GRUCell elif cell_type == 'relu_rnn': return partial(rnn.RNNCell, activation='relu') elif cell_type == 'tanh_rnn': return partial(rnn.RNNCell, activation='tanh') else: raise NotImplementedError else: return cell_type
python
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': return rnn.LSTMCell elif cell_type == 'gru': return rnn.GRUCell elif cell_type == 'relu_rnn': return partial(rnn.RNNCell, activation='relu') elif cell_type == 'tanh_rnn': return partial(rnn.RNNCell, activation='tanh') else: raise NotImplementedError else: return cell_type
[ "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", ",", "activation", "=", "'relu'", ")", "elif", "cell_type", "==", "'tanh_rnn'", ":", "return", "partial", "(", "rnn", ".", "RNNCell", ",", "activation", "=", "'tanh'", ")", "else", ":", "raise", "NotImplementedError", "else", ":", "return", "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
[ "Get", "the", "object", "type", "of", "the", "cell", "by", "parsing", "the", "input" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/seq2seq_encoder_decoder.py#L30-L54
train
dmlc/gluon-nlp
src/gluonnlp/data/batchify/embedding.py
_get_context
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_boundaries, center_idx) sentence_start, sentence_end = _get_sentence_start_end( sentence_boundaries, sentence_index) if random_window_size: window_size = random.randint(1, window_size) start_idx = max(sentence_start, center_idx - window_size) end_idx = min(sentence_end, center_idx + window_size + 1) if start_idx != center_idx and center_idx + 1 != end_idx: context = np.concatenate((np.arange(start_idx, center_idx), np.arange(center_idx + 1, end_idx))) elif start_idx != center_idx: context = np.arange(start_idx, center_idx) elif center_idx + 1 != end_idx: context = np.arange(center_idx + 1, end_idx) else: context = None return context
python
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_boundaries, center_idx) sentence_start, sentence_end = _get_sentence_start_end( sentence_boundaries, sentence_index) if random_window_size: window_size = random.randint(1, window_size) start_idx = max(sentence_start, center_idx - window_size) end_idx = min(sentence_end, center_idx + window_size + 1) if start_idx != center_idx and center_idx + 1 != end_idx: context = np.concatenate((np.arange(start_idx, center_idx), np.arange(center_idx + 1, end_idx))) elif start_idx != center_idx: context = np.arange(start_idx, center_idx) elif center_idx + 1 != end_idx: context = np.arange(center_idx + 1, end_idx) else: context = None return context
[ "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_end", "(", "sentence_boundaries", ",", "sentence_index", ")", "if", "random_window_size", ":", "window_size", "=", "random", ".", "randint", "(", "1", ",", "window_size", ")", "start_idx", "=", "max", "(", "sentence_start", ",", "center_idx", "-", "window_size", ")", "end_idx", "=", "min", "(", "sentence_end", ",", "center_idx", "+", "window_size", "+", "1", ")", "if", "start_idx", "!=", "center_idx", "and", "center_idx", "+", "1", "!=", "end_idx", ":", "context", "=", "np", ".", "concatenate", "(", "(", "np", ".", "arange", "(", "start_idx", ",", "center_idx", ")", ",", "np", ".", "arange", "(", "center_idx", "+", "1", ",", "end_idx", ")", ")", ")", "elif", "start_idx", "!=", "center_idx", ":", "context", "=", "np", ".", "arange", "(", "start_idx", ",", "center_idx", ")", "elif", "center_idx", "+", "1", "!=", "end_idx", ":", "context", "=", "np", ".", "arange", "(", "center_idx", "+", "1", ",", "end_idx", ")", "else", ":", "context", "=", "None", "return", "context" ]
Compute the context with respect to a center word in a sentence. Takes an numpy array of sentences boundaries.
[ "Compute", "the", "context", "with", "respect", "to", "a", "center", "word", "in", "a", "sentence", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/batchify/embedding.py#L246-L274
train
dmlc/gluon-nlp
scripts/sentiment_analysis/text_cnn.py
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
python
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
[ "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.
[ "Construct", "the", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L40-L46
train
dmlc/gluon-nlp
scripts/sentiment_analysis/text_cnn.py
init
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_extend.weight.set_data(vocab.embedding.idx_to_vec) if model_mode == 'static' or model_mode == 'multichannel': # Parameters of textCNN.embedding are not updated during training. textCNN.embedding.collect_params().setattr('grad_req', 'null') trainer = gluon.Trainer(textCNN.collect_params(), 'adam', {'learning_rate': lr}) return textCNN, trainer
python
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_extend.weight.set_data(vocab.embedding.idx_to_vec) if model_mode == 'static' or model_mode == 'multichannel': # Parameters of textCNN.embedding are not updated during training. textCNN.embedding.collect_params().setattr('grad_req', 'null') trainer = gluon.Trainer(textCNN.collect_params(), 'adam', {'learning_rate': lr}) return textCNN, trainer
[ "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'", ":", "textCNN", ".", "embedding_extend", ".", "weight", ".", "set_data", "(", "vocab", ".", "embedding", ".", "idx_to_vec", ")", "if", "model_mode", "==", "'static'", "or", "model_mode", "==", "'multichannel'", ":", "# Parameters of textCNN.embedding are not updated during training.", "textCNN", ".", "embedding", ".", "collect_params", "(", ")", ".", "setattr", "(", "'grad_req'", ",", "'null'", ")", "trainer", "=", "gluon", ".", "Trainer", "(", "textCNN", ".", "collect_params", "(", ")", ",", "'adam'", ",", "{", "'learning_rate'", ":", "lr", "}", ")", "return", "textCNN", ",", "trainer" ]
Initialize parameters.
[ "Initialize", "parameters", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L48-L60
train
dmlc/gluon-nlp
scripts/bert/bert_qa_dataset.py
preprocess_dataset
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 multiprocessing workers to use for data preprocessing. """ 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): if data: for _data in data: dataset_transform.append(_data[:-1]) dataset_len.append(_data[-1]) dataset = SimpleDataset(dataset_transform).transform( lambda x: (x[0], x[1], x[2], x[3], x[4], x[5])) end = time.time() pool.close() print('Done! Transform dataset costs %.2f seconds.' % (end-start)) return dataset, dataset_len
python
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 multiprocessing workers to use for data preprocessing. """ 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): if data: for _data in data: dataset_transform.append(_data[:-1]) dataset_len.append(_data[-1]) dataset = SimpleDataset(dataset_transform).transform( lambda x: (x[0], x[1], x[2], x[3], x[4], x[5])) end = time.time() pool.close() print('Done! Transform dataset costs %.2f seconds.' % (end-start)) return dataset, dataset_len
[ "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", ")", ":", "if", "data", ":", "for", "_data", "in", "data", ":", "dataset_transform", ".", "append", "(", "_data", "[", ":", "-", "1", "]", ")", "dataset_len", ".", "append", "(", "_data", "[", "-", "1", "]", ")", "dataset", "=", "SimpleDataset", "(", "dataset_transform", ")", ".", "transform", "(", "lambda", "x", ":", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ",", "x", "[", "2", "]", ",", "x", "[", "3", "]", ",", "x", "[", "4", "]", ",", "x", "[", "5", "]", ")", ")", "end", "=", "time", ".", "time", "(", ")", "pool", ".", "close", "(", ")", "print", "(", "'Done! Transform dataset costs %.2f seconds.'", "%", "(", "end", "-", "start", ")", ")", "return", "dataset", ",", "dataset_len" ]
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.
[ "Use", "multiprocessing", "to", "perform", "transform", "for", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_dataset.py#L56-L86
train
dmlc/gluon-nlp
src/gluonnlp/model/__init__.py
get_model
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 model, options are 'wikitext-2'. For ELMo, Options are 'gbw' and '5bw'. 'gbw' represents 1 Billion Word Language Model Benchmark http://www.statmt.org/lm-benchmark/; '5bw' represents a dataset of 5.5B tokens consisting of Wikipedia (1.9B) and all of the monolingual news crawl data from WMT 2008-2012 (3.6B). If specified, then the returned vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. None Vocabulary object is required with the ELMo model. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters. Returns ------- gluon.Block, gluonnlp.Vocab, (optional) gluonnlp.Vocab """ 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_1150': awd_lstm_lm_1150, 'awd_lstm_lm_600': awd_lstm_lm_600, 'big_rnn_lm_2048_512': big_rnn_lm_2048_512, 'elmo_2x1024_128_2048cnn_1xhighway': elmo_2x1024_128_2048cnn_1xhighway, 'elmo_2x2048_256_2048cnn_1xhighway': elmo_2x2048_256_2048cnn_1xhighway, 'elmo_2x4096_512_2048cnn_2xhighway': elmo_2x4096_512_2048cnn_2xhighway, 'transformer_en_de_512': transformer_en_de_512, 'bert_12_768_12' : bert_12_768_12, 'bert_24_1024_16' : bert_24_1024_16} name = name.lower() if name not in models: raise ValueError( 'Model %s is not supported. Available options are\n\t%s'%( name, '\n\t'.join(sorted(models.keys())))) kwargs['dataset_name'] = dataset_name return models[name](**kwargs)
python
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 model, options are 'wikitext-2'. For ELMo, Options are 'gbw' and '5bw'. 'gbw' represents 1 Billion Word Language Model Benchmark http://www.statmt.org/lm-benchmark/; '5bw' represents a dataset of 5.5B tokens consisting of Wikipedia (1.9B) and all of the monolingual news crawl data from WMT 2008-2012 (3.6B). If specified, then the returned vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. None Vocabulary object is required with the ELMo model. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters. Returns ------- gluon.Block, gluonnlp.Vocab, (optional) gluonnlp.Vocab """ 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_1150': awd_lstm_lm_1150, 'awd_lstm_lm_600': awd_lstm_lm_600, 'big_rnn_lm_2048_512': big_rnn_lm_2048_512, 'elmo_2x1024_128_2048cnn_1xhighway': elmo_2x1024_128_2048cnn_1xhighway, 'elmo_2x2048_256_2048cnn_1xhighway': elmo_2x2048_256_2048cnn_1xhighway, 'elmo_2x4096_512_2048cnn_2xhighway': elmo_2x4096_512_2048cnn_2xhighway, 'transformer_en_de_512': transformer_en_de_512, 'bert_12_768_12' : bert_12_768_12, 'bert_24_1024_16' : bert_24_1024_16} name = name.lower() if name not in models: raise ValueError( 'Model %s is not supported. Available options are\n\t%s'%( name, '\n\t'.join(sorted(models.keys())))) kwargs['dataset_name'] = dataset_name return models[name](**kwargs)
[ "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_1150'", ":", "awd_lstm_lm_1150", ",", "'awd_lstm_lm_600'", ":", "awd_lstm_lm_600", ",", "'big_rnn_lm_2048_512'", ":", "big_rnn_lm_2048_512", ",", "'elmo_2x1024_128_2048cnn_1xhighway'", ":", "elmo_2x1024_128_2048cnn_1xhighway", ",", "'elmo_2x2048_256_2048cnn_1xhighway'", ":", "elmo_2x2048_256_2048cnn_1xhighway", ",", "'elmo_2x4096_512_2048cnn_2xhighway'", ":", "elmo_2x4096_512_2048cnn_2xhighway", ",", "'transformer_en_de_512'", ":", "transformer_en_de_512", ",", "'bert_12_768_12'", ":", "bert_12_768_12", ",", "'bert_24_1024_16'", ":", "bert_24_1024_16", "}", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "not", "in", "models", ":", "raise", "ValueError", "(", "'Model %s is not supported. Available options are\\n\\t%s'", "%", "(", "name", ",", "'\\n\\t'", ".", "join", "(", "sorted", "(", "models", ".", "keys", "(", ")", ")", ")", ")", ")", "kwargs", "[", "'dataset_name'", "]", "=", "dataset_name", "return", "models", "[", "name", "]", "(", "*", "*", "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 model, options are 'wikitext-2'. For ELMo, Options are 'gbw' and '5bw'. 'gbw' represents 1 Billion Word Language Model Benchmark http://www.statmt.org/lm-benchmark/; '5bw' represents a dataset of 5.5B tokens consisting of Wikipedia (1.9B) and all of the monolingual news crawl data from WMT 2008-2012 (3.6B). If specified, then the returned vocabulary is extracted from the training set of the dataset. If None, then vocab is required, for specifying embedding weight size, and is directly returned. vocab : gluonnlp.Vocab or None, default None Vocabulary object to be used with the language model. Required when dataset_name is not specified. None Vocabulary object is required with the ELMo model. pretrained : bool, default False Whether to load the pre-trained weights for model. ctx : Context, default CPU The context in which to load the pre-trained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters. Returns ------- gluon.Block, gluonnlp.Vocab, (optional) gluonnlp.Vocab
[ "Returns", "a", "pre", "-", "defined", "model", "by", "name", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/__init__.py#L99-L151
train
dmlc/gluon-nlp
src/gluonnlp/model/attention_cell.py
_masked_softmax
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_size, query_length, memory_length) Returns ------- att_weights : Symborl or NDArray Shape (batch_size, query_length, memory_length) """ 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)) att_weights = F.softmax(att_score, axis=-1) * mask else: att_weights = F.softmax(att_score, axis=-1) return att_weights
python
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_size, query_length, memory_length) Returns ------- att_weights : Symborl or NDArray Shape (batch_size, query_length, memory_length) """ 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)) att_weights = F.softmax(att_score, axis=-1) * mask else: att_weights = F.softmax(att_score, axis=-1) return att_weights
[ "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", ")", ")", "att_weights", "=", "F", ".", "softmax", "(", "att_score", ",", "axis", "=", "-", "1", ")", "*", "mask", "else", ":", "att_weights", "=", "F", ".", "softmax", "(", "att_score", ",", "axis", "=", "-", "1", ")", "return", "att_weights" ]
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 ------- att_weights : Symborl or NDArray Shape (batch_size, query_length, memory_length)
[ "Ignore", "the", "masked", "elements", "when", "calculating", "the", "softmax" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L33-L55
train
dmlc/gluon-nlp
src/gluonnlp/model/attention_cell.py
AttentionCell._read_by_weight
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 (batch_size, query_length, memory_length). For multi-head attention, Shape (batch_size, num_heads, query_length, memory_length). value : Symbol or NDArray Value of the memory. Shape (batch_size, memory_length, total_value_dim) Returns ------- context_vec: Symbol or NDArray Shape (batch_size, query_length, context_vec_dim) """ output = F.batch_dot(att_weights, value) return output
python
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 (batch_size, query_length, memory_length). For multi-head attention, Shape (batch_size, num_heads, query_length, memory_length). value : Symbol or NDArray Value of the memory. Shape (batch_size, memory_length, total_value_dim) Returns ------- context_vec: Symbol or NDArray Shape (batch_size, query_length, context_vec_dim) """ output = F.batch_dot(att_weights, value) return output
[ "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. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (batch_size, query_length, memory_length). For multi-head attention, Shape (batch_size, num_heads, query_length, memory_length). value : Symbol or NDArray Value of the memory. Shape (batch_size, memory_length, total_value_dim) Returns ------- context_vec: Symbol or NDArray Shape (batch_size, query_length, context_vec_dim)
[ "Read", "from", "the", "value", "matrix", "given", "the", "attention", "weights", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L99-L120
train
dmlc/gluon-nlp
scripts/machine_translation/translation.py
BeamSearchTranslator.translate
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 ------- samples : NDArray Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32. scores : NDArray Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are in descending order. valid_length : NDArray The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32. """ 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, src_valid_length) inputs = mx.nd.full(shape=(batch_size,), ctx=src_seq.context, dtype=np.float32, val=self._model.tgt_vocab.token_to_idx[self._model.tgt_vocab.bos_token]) samples, scores, sample_valid_length = self._sampler(inputs, decoder_states) return samples, scores, sample_valid_length
python
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 ------- samples : NDArray Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32. scores : NDArray Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are in descending order. valid_length : NDArray The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32. """ 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, src_valid_length) inputs = mx.nd.full(shape=(batch_size,), ctx=src_seq.context, dtype=np.float32, val=self._model.tgt_vocab.token_to_idx[self._model.tgt_vocab.bos_token]) samples, scores, sample_valid_length = self._sampler(inputs, decoder_states) return samples, scores, sample_valid_length
[ "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", ",", "src_valid_length", ")", "inputs", "=", "mx", ".", "nd", ".", "full", "(", "shape", "=", "(", "batch_size", ",", ")", ",", "ctx", "=", "src_seq", ".", "context", ",", "dtype", "=", "np", ".", "float32", ",", "val", "=", "self", ".", "_model", ".", "tgt_vocab", ".", "token_to_idx", "[", "self", ".", "_model", ".", "tgt_vocab", ".", "bos_token", "]", ")", "samples", ",", "scores", ",", "sample_valid_length", "=", "self", ".", "_sampler", "(", "inputs", ",", "decoder_states", ")", "return", "samples", ",", "scores", ",", "sample_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 ------- samples : NDArray Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32. scores : NDArray Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are in descending order. valid_length : NDArray The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32.
[ "Get", "the", "translation", "result", "given", "the", "input", "sentence", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/translation.py#L55-L82
train
dmlc/gluon-nlp
scripts/parsing/parser/evaluate/evaluate.py
evaluate_official_script
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 from data set num_buckets_test : int size of buckets (cluster sentences into this number of clusters) test_batch_size : int batch size test_file : str gold test file output_file : str output result to this file debug : bool only evaluate first 1000 sentences for debugging Returns ------- tuple UAS, LAS, speed """ if output_file is None: output_file = tempfile.NamedTemporaryFile().name data_loader = DataLoader(test_file, num_buckets_test, vocab) record = data_loader.idx_sequence results = [None] * len(record) idx = 0 seconds = time.time() for words, tags, arcs, rels in data_loader.get_batches(batch_size=test_batch_size, shuffle=False): outputs = parser.forward(words, tags) for output in outputs: sent_idx = record[idx] results[sent_idx] = output idx += 1 assert idx == len(results), 'parser swallowed some sentences' seconds = time.time() - seconds speed = len(record) / seconds arcs = reduce(lambda x, y: x + y, [list(result[0]) for result in results]) rels = reduce(lambda x, y: x + y, [list(result[1]) for result in results]) idx = 0 with open(test_file) as f: if debug: f = f.readlines()[:1000] with open(output_file, 'w') as fo: for line in f: info = line.strip().split() if info: arc_offset = 5 rel_offset = 6 if len(info) == 10: # conll or conllx arc_offset = 6 rel_offset = 7 # assert len(info) == 10, 'Illegal line: %s' % line info[arc_offset] = str(arcs[idx]) info[rel_offset] = vocab.id2rel(rels[idx]) fo.write('\t'.join(info) + '\n') idx += 1 else: fo.write('\n') os.system('perl %s -q -b -g %s -s %s -o tmp' % ( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'eval.pl'), test_file, output_file)) os.system('tail -n 3 tmp > score_tmp') LAS, UAS = [float(line.strip().split()[-2]) for line in open('score_tmp').readlines()[:2]] # print('UAS %.2f, LAS %.2f' % (UAS, LAS)) os.system('rm tmp score_tmp') os.remove(output_file) return UAS, LAS, speed
python
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 from data set num_buckets_test : int size of buckets (cluster sentences into this number of clusters) test_batch_size : int batch size test_file : str gold test file output_file : str output result to this file debug : bool only evaluate first 1000 sentences for debugging Returns ------- tuple UAS, LAS, speed """ if output_file is None: output_file = tempfile.NamedTemporaryFile().name data_loader = DataLoader(test_file, num_buckets_test, vocab) record = data_loader.idx_sequence results = [None] * len(record) idx = 0 seconds = time.time() for words, tags, arcs, rels in data_loader.get_batches(batch_size=test_batch_size, shuffle=False): outputs = parser.forward(words, tags) for output in outputs: sent_idx = record[idx] results[sent_idx] = output idx += 1 assert idx == len(results), 'parser swallowed some sentences' seconds = time.time() - seconds speed = len(record) / seconds arcs = reduce(lambda x, y: x + y, [list(result[0]) for result in results]) rels = reduce(lambda x, y: x + y, [list(result[1]) for result in results]) idx = 0 with open(test_file) as f: if debug: f = f.readlines()[:1000] with open(output_file, 'w') as fo: for line in f: info = line.strip().split() if info: arc_offset = 5 rel_offset = 6 if len(info) == 10: # conll or conllx arc_offset = 6 rel_offset = 7 # assert len(info) == 10, 'Illegal line: %s' % line info[arc_offset] = str(arcs[idx]) info[rel_offset] = vocab.id2rel(rels[idx]) fo.write('\t'.join(info) + '\n') idx += 1 else: fo.write('\n') os.system('perl %s -q -b -g %s -s %s -o tmp' % ( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'eval.pl'), test_file, output_file)) os.system('tail -n 3 tmp > score_tmp') LAS, UAS = [float(line.strip().split()[-2]) for line in open('score_tmp').readlines()[:2]] # print('UAS %.2f, LAS %.2f' % (UAS, LAS)) os.system('rm tmp score_tmp') os.remove(output_file) return UAS, LAS, speed
[ "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", ",", "num_buckets_test", ",", "vocab", ")", "record", "=", "data_loader", ".", "idx_sequence", "results", "=", "[", "None", "]", "*", "len", "(", "record", ")", "idx", "=", "0", "seconds", "=", "time", ".", "time", "(", ")", "for", "words", ",", "tags", ",", "arcs", ",", "rels", "in", "data_loader", ".", "get_batches", "(", "batch_size", "=", "test_batch_size", ",", "shuffle", "=", "False", ")", ":", "outputs", "=", "parser", ".", "forward", "(", "words", ",", "tags", ")", "for", "output", "in", "outputs", ":", "sent_idx", "=", "record", "[", "idx", "]", "results", "[", "sent_idx", "]", "=", "output", "idx", "+=", "1", "assert", "idx", "==", "len", "(", "results", ")", ",", "'parser swallowed some sentences'", "seconds", "=", "time", ".", "time", "(", ")", "-", "seconds", "speed", "=", "len", "(", "record", ")", "/", "seconds", "arcs", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "[", "list", "(", "result", "[", "0", "]", ")", "for", "result", "in", "results", "]", ")", "rels", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "[", "list", "(", "result", "[", "1", "]", ")", "for", "result", "in", "results", "]", ")", "idx", "=", "0", "with", "open", "(", "test_file", ")", "as", "f", ":", "if", "debug", ":", "f", "=", "f", ".", "readlines", "(", ")", "[", ":", "1000", "]", "with", "open", "(", "output_file", ",", "'w'", ")", "as", "fo", ":", "for", "line", "in", "f", ":", "info", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "if", "info", ":", "arc_offset", "=", "5", "rel_offset", "=", "6", "if", "len", "(", "info", ")", "==", "10", ":", "# conll or conllx", "arc_offset", "=", "6", "rel_offset", "=", "7", "# assert len(info) == 10, 'Illegal line: %s' % line", "info", "[", "arc_offset", "]", "=", "str", "(", "arcs", "[", "idx", "]", ")", "info", "[", "rel_offset", "]", "=", "vocab", ".", "id2rel", "(", "rels", "[", "idx", "]", ")", "fo", ".", "write", "(", "'\\t'", ".", "join", "(", "info", ")", "+", "'\\n'", ")", "idx", "+=", "1", "else", ":", "fo", ".", "write", "(", "'\\n'", ")", "os", ".", "system", "(", "'perl %s -q -b -g %s -s %s -o tmp'", "%", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "'eval.pl'", ")", ",", "test_file", ",", "output_file", ")", ")", "os", ".", "system", "(", "'tail -n 3 tmp > score_tmp'", ")", "LAS", ",", "UAS", "=", "[", "float", "(", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "[", "-", "2", "]", ")", "for", "line", "in", "open", "(", "'score_tmp'", ")", ".", "readlines", "(", ")", "[", ":", "2", "]", "]", "# print('UAS %.2f, LAS %.2f' % (UAS, LAS))", "os", ".", "system", "(", "'rm tmp score_tmp'", ")", "os", ".", "remove", "(", "output_file", ")", "return", "UAS", ",", "LAS", ",", "speed" ]
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 size test_file : str gold test file output_file : str output result to this file debug : bool only evaluate first 1000 sentences for debugging Returns ------- tuple UAS, LAS, speed
[ "Evaluate", "parser", "on", "a", "data", "set" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/evaluate/evaluate.py#L28-L102
train
dmlc/gluon-nlp
scripts/parsing/parser/biaffine_parser.py
BiaffineParser.parameter_from_numpy
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.gluon.parameter a parameter object """ p = self.params.get(name, shape=array.shape, init=mx.init.Constant(array)) return p
python
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.gluon.parameter a parameter object """ p = self.params.get(name, shape=array.shape, init=mx.init.Constant(array)) return p
[ "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 Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.gluon.parameter a parameter object
[ "Create", "parameter", "with", "its", "value", "initialized", "according", "to", "a", "numpy", "tensor" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L122-L138
train
dmlc/gluon-nlp
scripts/parsing/parser/biaffine_parser.py
BiaffineParser.parameter_init
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 ------- mxnet.gluon.parameter a parameter object """ p = self.params.get(name, shape=shape, init=init) return p
python
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 ------- mxnet.gluon.parameter a parameter object """ p = self.params.get(name, shape=shape, init=init) return p
[ "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 Parameters ---------- name : str parameter name shape : tuple parameter shape init : mxnet.initializer an initializer Returns ------- mxnet.gluon.parameter a parameter object
[ "Create", "parameter", "given", "name", "shape", "and", "initiator" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L140-L158
train
dmlc/gluon-nlp
scripts/parsing/parser/biaffine_parser.py
BiaffineParser.forward
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 batch_size arc_targets : mxnet.ndarray.NDArray gold arc indices of seq_len x batch_size rel_targets : mxnet.ndarray.NDArray gold rel indices of seq_len x batch_size Returns ------- tuple (arc_accuracy, rel_accuracy, overall_accuracy, loss) when training, else if given gold target then return arc_accuracy, rel_accuracy, overall_accuracy, outputs, otherwise return outputs, where outputs is a list of (arcs, rels). """ is_train = autograd.is_training() def flatten_numpy(ndarray): """Flatten nd-array to 1-d column vector Parameters ---------- ndarray : numpy.ndarray input tensor Returns ------- numpy.ndarray A column vector """ return np.reshape(ndarray, (-1,), 'F') batch_size = word_inputs.shape[1] seq_len = word_inputs.shape[0] mask = np.greater(word_inputs, self._vocab.ROOT).astype(np.float32) num_tokens = int(np.sum(mask)) # non padding, non root token number if is_train or arc_targets is not None: mask_1D = flatten_numpy(mask) mask_1D_tensor = nd.array(mask_1D) unked_words = np.where(word_inputs < self._vocab.words_in_train, word_inputs, self._vocab.UNK) word_embs = self.word_embs(nd.array(unked_words, dtype='int')) if self.pret_word_embs: word_embs = word_embs + self.pret_word_embs(nd.array(word_inputs)) tag_embs = self.tag_embs(nd.array(tag_inputs)) # Dropout emb_inputs = nd.concat(word_embs, tag_embs, dim=2) # seq_len x batch_size top_recur = biLSTM(self.f_lstm, self.b_lstm, emb_inputs, batch_size, dropout_x=self.dropout_lstm_input if is_train else 0) top_recur = nd.Dropout(data=top_recur, axes=[0], p=self.dropout_mlp) W_dep, b_dep = self.mlp_dep_W.data(), self.mlp_dep_b.data() W_head, b_head = self.mlp_head_W.data(), self.mlp_head_b.data() dep, head = leaky_relu(nd.dot(top_recur, W_dep.T) + b_dep), leaky_relu(nd.dot(top_recur, W_head.T) + b_head) dep, head = nd.Dropout(data=dep, axes=[0], p=self.dropout_mlp), nd.Dropout(data=head, axes=[0], p=self.dropout_mlp) dep, head = nd.transpose(dep, axes=[2, 0, 1]), nd.transpose(head, axes=[2, 0, 1]) dep_arc, dep_rel = dep[:self.mlp_arc_size], dep[self.mlp_arc_size:] head_arc, head_rel = head[:self.mlp_arc_size], head[self.mlp_arc_size:] W_arc = self.arc_W.data() arc_logits = bilinear(dep_arc, W_arc, head_arc, self.mlp_arc_size, seq_len, batch_size, num_outputs=1, bias_x=True, bias_y=False) # (#head x #dep) x batch_size flat_arc_logits = reshape_fortran(arc_logits, (seq_len, seq_len * batch_size)) # (#head ) x (#dep x batch_size) arc_preds = arc_logits.argmax(0) # seq_len x batch_size if is_train or arc_targets is not None: correct = np.equal(arc_preds.asnumpy(), arc_targets) arc_correct = correct.astype(np.float32) * mask arc_accuracy = np.sum(arc_correct) / num_tokens targets_1D = flatten_numpy(arc_targets) losses = self.softmax_loss(flat_arc_logits, nd.array(targets_1D)) arc_loss = nd.sum(losses * mask_1D_tensor) / num_tokens if not is_train: arc_probs = np.transpose( np.reshape(nd.softmax(flat_arc_logits, axis=0).asnumpy(), (seq_len, seq_len, batch_size), 'F')) # #batch_size x #dep x #head W_rel = self.rel_W.data() rel_logits = bilinear(dep_rel, W_rel, head_rel, self.mlp_rel_size, seq_len, batch_size, num_outputs=self._vocab.rel_size, bias_x=True, bias_y=True) # (#head x rel_size x #dep) x batch_size flat_rel_logits = reshape_fortran(rel_logits, (seq_len, self._vocab.rel_size, seq_len * batch_size)) # (#head x rel_size) x (#dep x batch_size) _target_vec = nd.array(targets_1D if is_train else flatten_numpy(arc_preds.asnumpy())).reshape( seq_len * batch_size, 1) _target_mat = _target_vec * nd.ones((1, self._vocab.rel_size)) partial_rel_logits = nd.pick(flat_rel_logits, _target_mat.T, axis=0) # (rel_size) x (#dep x batch_size) if is_train or arc_targets is not None: rel_preds = partial_rel_logits.argmax(0) targets_1D = flatten_numpy(rel_targets) rel_correct = np.equal(rel_preds.asnumpy(), targets_1D).astype(np.float32) * mask_1D rel_accuracy = np.sum(rel_correct) / num_tokens losses = self.softmax_loss(partial_rel_logits, nd.array(targets_1D)) rel_loss = nd.sum(losses * mask_1D_tensor) / num_tokens if not is_train: rel_probs = np.transpose(np.reshape(nd.softmax(flat_rel_logits.transpose([1, 0, 2]), axis=0).asnumpy(), (self._vocab.rel_size, seq_len, seq_len, batch_size), 'F')) # batch_size x #dep x #head x #nclasses if is_train or arc_targets is not None: loss = arc_loss + rel_loss correct = rel_correct * flatten_numpy(arc_correct) overall_accuracy = np.sum(correct) / num_tokens if is_train: return arc_accuracy, rel_accuracy, overall_accuracy, loss outputs = [] for msk, arc_prob, rel_prob in zip(np.transpose(mask), arc_probs, rel_probs): # parse sentences one by one msk[0] = 1. sent_len = int(np.sum(msk)) arc_pred = arc_argmax(arc_prob, sent_len, msk) rel_prob = rel_prob[np.arange(len(arc_pred)), arc_pred] rel_pred = rel_argmax(rel_prob, sent_len) outputs.append((arc_pred[1:sent_len], rel_pred[1:sent_len])) if arc_targets is not None: return arc_accuracy, rel_accuracy, overall_accuracy, outputs return outputs
python
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 batch_size arc_targets : mxnet.ndarray.NDArray gold arc indices of seq_len x batch_size rel_targets : mxnet.ndarray.NDArray gold rel indices of seq_len x batch_size Returns ------- tuple (arc_accuracy, rel_accuracy, overall_accuracy, loss) when training, else if given gold target then return arc_accuracy, rel_accuracy, overall_accuracy, outputs, otherwise return outputs, where outputs is a list of (arcs, rels). """ is_train = autograd.is_training() def flatten_numpy(ndarray): """Flatten nd-array to 1-d column vector Parameters ---------- ndarray : numpy.ndarray input tensor Returns ------- numpy.ndarray A column vector """ return np.reshape(ndarray, (-1,), 'F') batch_size = word_inputs.shape[1] seq_len = word_inputs.shape[0] mask = np.greater(word_inputs, self._vocab.ROOT).astype(np.float32) num_tokens = int(np.sum(mask)) # non padding, non root token number if is_train or arc_targets is not None: mask_1D = flatten_numpy(mask) mask_1D_tensor = nd.array(mask_1D) unked_words = np.where(word_inputs < self._vocab.words_in_train, word_inputs, self._vocab.UNK) word_embs = self.word_embs(nd.array(unked_words, dtype='int')) if self.pret_word_embs: word_embs = word_embs + self.pret_word_embs(nd.array(word_inputs)) tag_embs = self.tag_embs(nd.array(tag_inputs)) # Dropout emb_inputs = nd.concat(word_embs, tag_embs, dim=2) # seq_len x batch_size top_recur = biLSTM(self.f_lstm, self.b_lstm, emb_inputs, batch_size, dropout_x=self.dropout_lstm_input if is_train else 0) top_recur = nd.Dropout(data=top_recur, axes=[0], p=self.dropout_mlp) W_dep, b_dep = self.mlp_dep_W.data(), self.mlp_dep_b.data() W_head, b_head = self.mlp_head_W.data(), self.mlp_head_b.data() dep, head = leaky_relu(nd.dot(top_recur, W_dep.T) + b_dep), leaky_relu(nd.dot(top_recur, W_head.T) + b_head) dep, head = nd.Dropout(data=dep, axes=[0], p=self.dropout_mlp), nd.Dropout(data=head, axes=[0], p=self.dropout_mlp) dep, head = nd.transpose(dep, axes=[2, 0, 1]), nd.transpose(head, axes=[2, 0, 1]) dep_arc, dep_rel = dep[:self.mlp_arc_size], dep[self.mlp_arc_size:] head_arc, head_rel = head[:self.mlp_arc_size], head[self.mlp_arc_size:] W_arc = self.arc_W.data() arc_logits = bilinear(dep_arc, W_arc, head_arc, self.mlp_arc_size, seq_len, batch_size, num_outputs=1, bias_x=True, bias_y=False) # (#head x #dep) x batch_size flat_arc_logits = reshape_fortran(arc_logits, (seq_len, seq_len * batch_size)) # (#head ) x (#dep x batch_size) arc_preds = arc_logits.argmax(0) # seq_len x batch_size if is_train or arc_targets is not None: correct = np.equal(arc_preds.asnumpy(), arc_targets) arc_correct = correct.astype(np.float32) * mask arc_accuracy = np.sum(arc_correct) / num_tokens targets_1D = flatten_numpy(arc_targets) losses = self.softmax_loss(flat_arc_logits, nd.array(targets_1D)) arc_loss = nd.sum(losses * mask_1D_tensor) / num_tokens if not is_train: arc_probs = np.transpose( np.reshape(nd.softmax(flat_arc_logits, axis=0).asnumpy(), (seq_len, seq_len, batch_size), 'F')) # #batch_size x #dep x #head W_rel = self.rel_W.data() rel_logits = bilinear(dep_rel, W_rel, head_rel, self.mlp_rel_size, seq_len, batch_size, num_outputs=self._vocab.rel_size, bias_x=True, bias_y=True) # (#head x rel_size x #dep) x batch_size flat_rel_logits = reshape_fortran(rel_logits, (seq_len, self._vocab.rel_size, seq_len * batch_size)) # (#head x rel_size) x (#dep x batch_size) _target_vec = nd.array(targets_1D if is_train else flatten_numpy(arc_preds.asnumpy())).reshape( seq_len * batch_size, 1) _target_mat = _target_vec * nd.ones((1, self._vocab.rel_size)) partial_rel_logits = nd.pick(flat_rel_logits, _target_mat.T, axis=0) # (rel_size) x (#dep x batch_size) if is_train or arc_targets is not None: rel_preds = partial_rel_logits.argmax(0) targets_1D = flatten_numpy(rel_targets) rel_correct = np.equal(rel_preds.asnumpy(), targets_1D).astype(np.float32) * mask_1D rel_accuracy = np.sum(rel_correct) / num_tokens losses = self.softmax_loss(partial_rel_logits, nd.array(targets_1D)) rel_loss = nd.sum(losses * mask_1D_tensor) / num_tokens if not is_train: rel_probs = np.transpose(np.reshape(nd.softmax(flat_rel_logits.transpose([1, 0, 2]), axis=0).asnumpy(), (self._vocab.rel_size, seq_len, seq_len, batch_size), 'F')) # batch_size x #dep x #head x #nclasses if is_train or arc_targets is not None: loss = arc_loss + rel_loss correct = rel_correct * flatten_numpy(arc_correct) overall_accuracy = np.sum(correct) / num_tokens if is_train: return arc_accuracy, rel_accuracy, overall_accuracy, loss outputs = [] for msk, arc_prob, rel_prob in zip(np.transpose(mask), arc_probs, rel_probs): # parse sentences one by one msk[0] = 1. sent_len = int(np.sum(msk)) arc_pred = arc_argmax(arc_prob, sent_len, msk) rel_prob = rel_prob[np.arange(len(arc_pred)), arc_pred] rel_pred = rel_argmax(rel_prob, sent_len) outputs.append((arc_pred[1:sent_len], rel_pred[1:sent_len])) if arc_targets is not None: return arc_accuracy, rel_accuracy, overall_accuracy, outputs return outputs
[ "def", "forward", "(", "self", ",", "word_inputs", ",", "tag_inputs", ",", "arc_targets", "=", "None", ",", "rel_targets", "=", "None", ")", ":", "is_train", "=", "autograd", ".", "is_training", "(", ")", "def", "flatten_numpy", "(", "ndarray", ")", ":", "\"\"\"Flatten nd-array to 1-d column vector\n\n Parameters\n ----------\n ndarray : numpy.ndarray\n input tensor\n\n Returns\n -------\n numpy.ndarray\n A column vector\n\n \"\"\"", "return", "np", ".", "reshape", "(", "ndarray", ",", "(", "-", "1", ",", ")", ",", "'F'", ")", "batch_size", "=", "word_inputs", ".", "shape", "[", "1", "]", "seq_len", "=", "word_inputs", ".", "shape", "[", "0", "]", "mask", "=", "np", ".", "greater", "(", "word_inputs", ",", "self", ".", "_vocab", ".", "ROOT", ")", ".", "astype", "(", "np", ".", "float32", ")", "num_tokens", "=", "int", "(", "np", ".", "sum", "(", "mask", ")", ")", "# non padding, non root token number", "if", "is_train", "or", "arc_targets", "is", "not", "None", ":", "mask_1D", "=", "flatten_numpy", "(", "mask", ")", "mask_1D_tensor", "=", "nd", ".", "array", "(", "mask_1D", ")", "unked_words", "=", "np", ".", "where", "(", "word_inputs", "<", "self", ".", "_vocab", ".", "words_in_train", ",", "word_inputs", ",", "self", ".", "_vocab", ".", "UNK", ")", "word_embs", "=", "self", ".", "word_embs", "(", "nd", ".", "array", "(", "unked_words", ",", "dtype", "=", "'int'", ")", ")", "if", "self", ".", "pret_word_embs", ":", "word_embs", "=", "word_embs", "+", "self", ".", "pret_word_embs", "(", "nd", ".", "array", "(", "word_inputs", ")", ")", "tag_embs", "=", "self", ".", "tag_embs", "(", "nd", ".", "array", "(", "tag_inputs", ")", ")", "# Dropout", "emb_inputs", "=", "nd", ".", "concat", "(", "word_embs", ",", "tag_embs", ",", "dim", "=", "2", ")", "# seq_len x batch_size", "top_recur", "=", "biLSTM", "(", "self", ".", "f_lstm", ",", "self", ".", "b_lstm", ",", "emb_inputs", ",", "batch_size", ",", "dropout_x", "=", "self", ".", "dropout_lstm_input", "if", "is_train", "else", "0", ")", "top_recur", "=", "nd", ".", "Dropout", "(", "data", "=", "top_recur", ",", "axes", "=", "[", "0", "]", ",", "p", "=", "self", ".", "dropout_mlp", ")", "W_dep", ",", "b_dep", "=", "self", ".", "mlp_dep_W", ".", "data", "(", ")", ",", "self", ".", "mlp_dep_b", ".", "data", "(", ")", "W_head", ",", "b_head", "=", "self", ".", "mlp_head_W", ".", "data", "(", ")", ",", "self", ".", "mlp_head_b", ".", "data", "(", ")", "dep", ",", "head", "=", "leaky_relu", "(", "nd", ".", "dot", "(", "top_recur", ",", "W_dep", ".", "T", ")", "+", "b_dep", ")", ",", "leaky_relu", "(", "nd", ".", "dot", "(", "top_recur", ",", "W_head", ".", "T", ")", "+", "b_head", ")", "dep", ",", "head", "=", "nd", ".", "Dropout", "(", "data", "=", "dep", ",", "axes", "=", "[", "0", "]", ",", "p", "=", "self", ".", "dropout_mlp", ")", ",", "nd", ".", "Dropout", "(", "data", "=", "head", ",", "axes", "=", "[", "0", "]", ",", "p", "=", "self", ".", "dropout_mlp", ")", "dep", ",", "head", "=", "nd", ".", "transpose", "(", "dep", ",", "axes", "=", "[", "2", ",", "0", ",", "1", "]", ")", ",", "nd", ".", "transpose", "(", "head", ",", "axes", "=", "[", "2", ",", "0", ",", "1", "]", ")", "dep_arc", ",", "dep_rel", "=", "dep", "[", ":", "self", ".", "mlp_arc_size", "]", ",", "dep", "[", "self", ".", "mlp_arc_size", ":", "]", "head_arc", ",", "head_rel", "=", "head", "[", ":", "self", ".", "mlp_arc_size", "]", ",", "head", "[", "self", ".", "mlp_arc_size", ":", "]", "W_arc", "=", "self", ".", "arc_W", ".", "data", "(", ")", "arc_logits", "=", "bilinear", "(", "dep_arc", ",", "W_arc", ",", "head_arc", ",", "self", ".", "mlp_arc_size", ",", "seq_len", ",", "batch_size", ",", "num_outputs", "=", "1", ",", "bias_x", "=", "True", ",", "bias_y", "=", "False", ")", "# (#head x #dep) x batch_size", "flat_arc_logits", "=", "reshape_fortran", "(", "arc_logits", ",", "(", "seq_len", ",", "seq_len", "*", "batch_size", ")", ")", "# (#head ) x (#dep x batch_size)", "arc_preds", "=", "arc_logits", ".", "argmax", "(", "0", ")", "# seq_len x batch_size", "if", "is_train", "or", "arc_targets", "is", "not", "None", ":", "correct", "=", "np", ".", "equal", "(", "arc_preds", ".", "asnumpy", "(", ")", ",", "arc_targets", ")", "arc_correct", "=", "correct", ".", "astype", "(", "np", ".", "float32", ")", "*", "mask", "arc_accuracy", "=", "np", ".", "sum", "(", "arc_correct", ")", "/", "num_tokens", "targets_1D", "=", "flatten_numpy", "(", "arc_targets", ")", "losses", "=", "self", ".", "softmax_loss", "(", "flat_arc_logits", ",", "nd", ".", "array", "(", "targets_1D", ")", ")", "arc_loss", "=", "nd", ".", "sum", "(", "losses", "*", "mask_1D_tensor", ")", "/", "num_tokens", "if", "not", "is_train", ":", "arc_probs", "=", "np", ".", "transpose", "(", "np", ".", "reshape", "(", "nd", ".", "softmax", "(", "flat_arc_logits", ",", "axis", "=", "0", ")", ".", "asnumpy", "(", ")", ",", "(", "seq_len", ",", "seq_len", ",", "batch_size", ")", ",", "'F'", ")", ")", "# #batch_size x #dep x #head", "W_rel", "=", "self", ".", "rel_W", ".", "data", "(", ")", "rel_logits", "=", "bilinear", "(", "dep_rel", ",", "W_rel", ",", "head_rel", ",", "self", ".", "mlp_rel_size", ",", "seq_len", ",", "batch_size", ",", "num_outputs", "=", "self", ".", "_vocab", ".", "rel_size", ",", "bias_x", "=", "True", ",", "bias_y", "=", "True", ")", "# (#head x rel_size x #dep) x batch_size", "flat_rel_logits", "=", "reshape_fortran", "(", "rel_logits", ",", "(", "seq_len", ",", "self", ".", "_vocab", ".", "rel_size", ",", "seq_len", "*", "batch_size", ")", ")", "# (#head x rel_size) x (#dep x batch_size)", "_target_vec", "=", "nd", ".", "array", "(", "targets_1D", "if", "is_train", "else", "flatten_numpy", "(", "arc_preds", ".", "asnumpy", "(", ")", ")", ")", ".", "reshape", "(", "seq_len", "*", "batch_size", ",", "1", ")", "_target_mat", "=", "_target_vec", "*", "nd", ".", "ones", "(", "(", "1", ",", "self", ".", "_vocab", ".", "rel_size", ")", ")", "partial_rel_logits", "=", "nd", ".", "pick", "(", "flat_rel_logits", ",", "_target_mat", ".", "T", ",", "axis", "=", "0", ")", "# (rel_size) x (#dep x batch_size)", "if", "is_train", "or", "arc_targets", "is", "not", "None", ":", "rel_preds", "=", "partial_rel_logits", ".", "argmax", "(", "0", ")", "targets_1D", "=", "flatten_numpy", "(", "rel_targets", ")", "rel_correct", "=", "np", ".", "equal", "(", "rel_preds", ".", "asnumpy", "(", ")", ",", "targets_1D", ")", ".", "astype", "(", "np", ".", "float32", ")", "*", "mask_1D", "rel_accuracy", "=", "np", ".", "sum", "(", "rel_correct", ")", "/", "num_tokens", "losses", "=", "self", ".", "softmax_loss", "(", "partial_rel_logits", ",", "nd", ".", "array", "(", "targets_1D", ")", ")", "rel_loss", "=", "nd", ".", "sum", "(", "losses", "*", "mask_1D_tensor", ")", "/", "num_tokens", "if", "not", "is_train", ":", "rel_probs", "=", "np", ".", "transpose", "(", "np", ".", "reshape", "(", "nd", ".", "softmax", "(", "flat_rel_logits", ".", "transpose", "(", "[", "1", ",", "0", ",", "2", "]", ")", ",", "axis", "=", "0", ")", ".", "asnumpy", "(", ")", ",", "(", "self", ".", "_vocab", ".", "rel_size", ",", "seq_len", ",", "seq_len", ",", "batch_size", ")", ",", "'F'", ")", ")", "# batch_size x #dep x #head x #nclasses", "if", "is_train", "or", "arc_targets", "is", "not", "None", ":", "loss", "=", "arc_loss", "+", "rel_loss", "correct", "=", "rel_correct", "*", "flatten_numpy", "(", "arc_correct", ")", "overall_accuracy", "=", "np", ".", "sum", "(", "correct", ")", "/", "num_tokens", "if", "is_train", ":", "return", "arc_accuracy", ",", "rel_accuracy", ",", "overall_accuracy", ",", "loss", "outputs", "=", "[", "]", "for", "msk", ",", "arc_prob", ",", "rel_prob", "in", "zip", "(", "np", ".", "transpose", "(", "mask", ")", ",", "arc_probs", ",", "rel_probs", ")", ":", "# parse sentences one by one", "msk", "[", "0", "]", "=", "1.", "sent_len", "=", "int", "(", "np", ".", "sum", "(", "msk", ")", ")", "arc_pred", "=", "arc_argmax", "(", "arc_prob", ",", "sent_len", ",", "msk", ")", "rel_prob", "=", "rel_prob", "[", "np", ".", "arange", "(", "len", "(", "arc_pred", ")", ")", ",", "arc_pred", "]", "rel_pred", "=", "rel_argmax", "(", "rel_prob", ",", "sent_len", ")", "outputs", ".", "append", "(", "(", "arc_pred", "[", "1", ":", "sent_len", "]", ",", "rel_pred", "[", "1", ":", "sent_len", "]", ")", ")", "if", "arc_targets", "is", "not", "None", ":", "return", "arc_accuracy", ",", "rel_accuracy", ",", "overall_accuracy", ",", "outputs", "return", "outputs" ]
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 x batch_size rel_targets : mxnet.ndarray.NDArray gold rel indices of seq_len x batch_size Returns ------- tuple (arc_accuracy, rel_accuracy, overall_accuracy, loss) when training, else if given gold target then return arc_accuracy, rel_accuracy, overall_accuracy, outputs, otherwise return outputs, where outputs is a list of (arcs, rels).
[ "Run", "decoding" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L160-L302
train
dmlc/gluon-nlp
scripts/parsing/parser/biaffine_parser.py
BiaffineParser.save_parameters
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_word_embs.weight', None) arg_dict = {key: val._reduce() for key, val in params.items()} ndarray.save(filename, arg_dict)
python
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_word_embs.weight', None) arg_dict = {key: val._reduce() for key, val in params.items()} ndarray.save(filename, arg_dict)
[ "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", ",", "val", "in", "params", ".", "items", "(", ")", "}", "ndarray", ".", "save", "(", "filename", ",", "arg_dict", ")" ]
Save model Parameters ---------- filename : str path to model file
[ "Save", "model" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L304-L316
train
dmlc/gluon-nlp
src/gluonnlp/data/dataloader.py
_worker_fn
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 in new process global _worker_dataset if isinstance(samples[0], (list, tuple)): batch = [batchify_fn([_worker_dataset[i] for i in shard]) for shard in samples] else: batch = batchify_fn([_worker_dataset[i] for i in samples]) buf = io.BytesIO() ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(batch) return buf.getvalue()
python
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 in new process global _worker_dataset if isinstance(samples[0], (list, tuple)): batch = [batchify_fn([_worker_dataset[i] for i in shard]) for shard in samples] else: batch = batchify_fn([_worker_dataset[i] for i in samples]) buf = io.BytesIO() ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(batch) return buf.getvalue()
[ "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 process", "global", "_worker_dataset", "if", "isinstance", "(", "samples", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "batch", "=", "[", "batchify_fn", "(", "[", "_worker_dataset", "[", "i", "]", "for", "i", "in", "shard", "]", ")", "for", "shard", "in", "samples", "]", "else", ":", "batch", "=", "batchify_fn", "(", "[", "_worker_dataset", "[", "i", "]", "for", "i", "in", "samples", "]", ")", "buf", "=", "io", ".", "BytesIO", "(", ")", "ForkingPickler", "(", "buf", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", ".", "dump", "(", "batch", ")", "return", "buf", ".", "getvalue", "(", ")" ]
Function for processing data in worker process.
[ "Function", "for", "processing", "data", "in", "worker", "process", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataloader.py#L40-L52
train
dmlc/gluon-nlp
src/gluonnlp/data/dataloader.py
_thread_worker_fn
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 batch
python
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 batch
[ "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.
[ "Threadpool", "worker", "function", "for", "processing", "data", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataloader.py#L54-L60
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
create
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 :func:`gluonnlp.embedding.list_sources`. Parameters ---------- embedding_name : str The token embedding name (case-insensitive). kwargs : dict All other keyword arguments are passed to the initializer of token embedding class. For example `create(embedding_name='fasttext', source='wiki.simple', load_ngrams=True)` will return `FastText(source='wiki.simple', load_ngrams=True)`. Returns ------- An instance of :class:`gluonnlp.embedding.TokenEmbedding`: A token embedding instance that loads embedding vectors from an externally hosted pre-trained token embedding file. """ create_text_embedding = registry.get_create_func(TokenEmbedding, 'token embedding') return create_text_embedding(embedding_name, **kwargs)
python
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 :func:`gluonnlp.embedding.list_sources`. Parameters ---------- embedding_name : str The token embedding name (case-insensitive). kwargs : dict All other keyword arguments are passed to the initializer of token embedding class. For example `create(embedding_name='fasttext', source='wiki.simple', load_ngrams=True)` will return `FastText(source='wiki.simple', load_ngrams=True)`. Returns ------- An instance of :class:`gluonnlp.embedding.TokenEmbedding`: A token embedding instance that loads embedding vectors from an externally hosted pre-trained token embedding file. """ create_text_embedding = registry.get_create_func(TokenEmbedding, 'token embedding') return create_text_embedding(embedding_name, **kwargs)
[ "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. 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`. Parameters ---------- embedding_name : str The token embedding name (case-insensitive). kwargs : dict All other keyword arguments are passed to the initializer of token embedding class. For example `create(embedding_name='fasttext', source='wiki.simple', load_ngrams=True)` will return `FastText(source='wiki.simple', load_ngrams=True)`. Returns ------- An instance of :class:`gluonnlp.embedding.TokenEmbedding`: A token embedding instance that loads embedding vectors from an externally hosted pre-trained token embedding file.
[ "Creates", "an", "instance", "of", "token", "embedding", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L69-L97
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
list_sources
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)`. This method returns all the valid names of `source` for the specified `embedding_name`. If `embedding_name` is set to None, this method returns all the valid names of `embedding_name` with their associated `source`. Parameters ---------- embedding_name : str or None, default None The pre-trained token embedding name. Returns ------- dict or list: A list of all the valid pre-trained token embedding file names (`source`) for the specified token embedding name (`embedding_name`). If the text embedding name is set to None, returns a dict mapping each valid token embedding name to a list of valid pre-trained files (`source`). They can be plugged into `gluonnlp.embedding.create(embedding_name, source)`. """ 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('Cannot find `embedding_name` {}. Use ' '`list_sources(embedding_name=None).keys()` to get all the valid' 'embedding names.'.format(embedding_name)) return list(text_embedding_reg[embedding_name].source_file_hash.keys()) else: return {embedding_name: list(embedding_cls.source_file_hash.keys()) for embedding_name, embedding_cls in registry.get_registry(TokenEmbedding).items()}
python
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)`. This method returns all the valid names of `source` for the specified `embedding_name`. If `embedding_name` is set to None, this method returns all the valid names of `embedding_name` with their associated `source`. Parameters ---------- embedding_name : str or None, default None The pre-trained token embedding name. Returns ------- dict or list: A list of all the valid pre-trained token embedding file names (`source`) for the specified token embedding name (`embedding_name`). If the text embedding name is set to None, returns a dict mapping each valid token embedding name to a list of valid pre-trained files (`source`). They can be plugged into `gluonnlp.embedding.create(embedding_name, source)`. """ 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('Cannot find `embedding_name` {}. Use ' '`list_sources(embedding_name=None).keys()` to get all the valid' 'embedding names.'.format(embedding_name)) return list(text_embedding_reg[embedding_name].source_file_hash.keys()) else: return {embedding_name: list(embedding_cls.source_file_hash.keys()) for embedding_name, embedding_cls in registry.get_registry(TokenEmbedding).items()}
[ "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", "(", "'Cannot find `embedding_name` {}. Use '", "'`list_sources(embedding_name=None).keys()` to get all the valid'", "'embedding names.'", ".", "format", "(", "embedding_name", ")", ")", "return", "list", "(", "text_embedding_reg", "[", "embedding_name", "]", ".", "source_file_hash", ".", "keys", "(", ")", ")", "else", ":", "return", "{", "embedding_name", ":", "list", "(", "embedding_cls", ".", "source_file_hash", ".", "keys", "(", ")", ")", "for", "embedding_name", ",", "embedding_cls", "in", "registry", ".", "get_registry", "(", "TokenEmbedding", ")", ".", "items", "(", ")", "}" ]
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 of `source` for the specified `embedding_name`. If `embedding_name` is set to None, this method returns all the valid names of `embedding_name` with their associated `source`. Parameters ---------- embedding_name : str or None, default None The pre-trained token embedding name. Returns ------- dict or list: A list of all the valid pre-trained token embedding file names (`source`) for the specified token embedding name (`embedding_name`). If the text embedding name is set to None, returns a dict mapping each valid token embedding name to a list of valid pre-trained files (`source`). They can be plugged into `gluonnlp.embedding.create(embedding_name, source)`.
[ "Get", "valid", "token", "embedding", "names", "and", "their", "pre", "-", "trained", "file", "names", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L100-L139
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding._load_embedding
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. 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, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. If a token is encountered multiple times in the pre-trained text embedding file, only the first-encountered token embedding vector will be loaded and the rest will be skipped. """ pretrained_file_path = os.path.expanduser(pretrained_file_path) if not os.path.isfile(pretrained_file_path): raise ValueError('`pretrained_file_path` must be a valid path ' 'to the pre-trained token embedding file.') logging.info('Loading pre-trained token embedding vectors from %s', pretrained_file_path) if pretrained_file_path.endswith('.npz'): self._load_embedding_serialized( pretrained_file_path=pretrained_file_path) else: self._load_embedding_txt( pretrained_file_path=pretrained_file_path, elem_delim=elem_delim, encoding=encoding)
python
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. 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, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. If a token is encountered multiple times in the pre-trained text embedding file, only the first-encountered token embedding vector will be loaded and the rest will be skipped. """ pretrained_file_path = os.path.expanduser(pretrained_file_path) if not os.path.isfile(pretrained_file_path): raise ValueError('`pretrained_file_path` must be a valid path ' 'to the pre-trained token embedding file.') logging.info('Loading pre-trained token embedding vectors from %s', pretrained_file_path) if pretrained_file_path.endswith('.npz'): self._load_embedding_serialized( pretrained_file_path=pretrained_file_path) else: self._load_embedding_txt( pretrained_file_path=pretrained_file_path, elem_delim=elem_delim, encoding=encoding)
[ "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", "(", "'`pretrained_file_path` must be a valid path '", "'to the pre-trained token embedding file.'", ")", "logging", ".", "info", "(", "'Loading pre-trained token embedding vectors from %s'", ",", "pretrained_file_path", ")", "if", "pretrained_file_path", ".", "endswith", "(", "'.npz'", ")", ":", "self", ".", "_load_embedding_serialized", "(", "pretrained_file_path", "=", "pretrained_file_path", ")", "else", ":", "self", ".", "_load_embedding_txt", "(", "pretrained_file_path", "=", "pretrained_file_path", ",", "elem_delim", "=", "elem_delim", ",", "encoding", "=", "encoding", ")" ]
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-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherwise, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. If a token is encountered multiple times in the pre-trained text embedding file, only the first-encountered token embedding vector will be loaded and the rest will be skipped.
[ "Load", "embedding", "vectors", "from", "a", "pre", "-", "trained", "token", "embedding", "file", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L221-L253
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding._load_embedding_txt
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_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherwise, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. If a token is encountered multiple times in the pre-trained text embedding file, only the first-encountered token embedding vector will be loaded and the rest will be skipped. """ vec_len = None all_elems = [] tokens = set() loaded_unknown_vec = None with io.open(pretrained_file_path, 'rb') as f: for line_num, line in enumerate(f): try: line = line.decode(encoding) except ValueError: warnings.warn('line {} in {}: failed to decode. Skipping.' .format(line_num, pretrained_file_path)) continue elems = line.rstrip().split(elem_delim) assert len(elems) > 1, 'line {} in {}: unexpected data format.'.format( line_num, pretrained_file_path) token, elems = elems[0], [float(i) for i in elems[1:]] if token == self.unknown_token and loaded_unknown_vec is None: loaded_unknown_vec = elems tokens.add(self.unknown_token) elif token in tokens: warnings.warn('line {} in {}: duplicate embedding found for ' 'token "{}". Skipped.'.format(line_num, pretrained_file_path, token)) elif len(elems) == 1 and line_num == 0: warnings.warn('line {} in {}: skipped likely header line.' .format(line_num, pretrained_file_path)) else: if not vec_len: vec_len = len(elems) if self.unknown_token: # Reserve a vector slot for the unknown token at the very beggining # because the unknown token index is 0. all_elems.extend([0] * vec_len) else: assert len(elems) == vec_len, \ 'line {} in {}: found vector of inconsistent dimension for token ' \ '"{}". expected dim: {}, found: {}'.format(line_num, pretrained_file_path, token, vec_len, len(elems)) all_elems.extend(elems) self._idx_to_token.append(token) self._token_to_idx[token] = len(self._idx_to_token) - 1 tokens.add(token) self._idx_to_vec = nd.array(all_elems).reshape((-1, vec_len)) if self.unknown_token: if loaded_unknown_vec is None: self._idx_to_vec[C.UNK_IDX] = self._init_unknown_vec(shape=vec_len) else: self._idx_to_vec[C.UNK_IDX] = nd.array(loaded_unknown_vec)
python
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_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherwise, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. If a token is encountered multiple times in the pre-trained text embedding file, only the first-encountered token embedding vector will be loaded and the rest will be skipped. """ vec_len = None all_elems = [] tokens = set() loaded_unknown_vec = None with io.open(pretrained_file_path, 'rb') as f: for line_num, line in enumerate(f): try: line = line.decode(encoding) except ValueError: warnings.warn('line {} in {}: failed to decode. Skipping.' .format(line_num, pretrained_file_path)) continue elems = line.rstrip().split(elem_delim) assert len(elems) > 1, 'line {} in {}: unexpected data format.'.format( line_num, pretrained_file_path) token, elems = elems[0], [float(i) for i in elems[1:]] if token == self.unknown_token and loaded_unknown_vec is None: loaded_unknown_vec = elems tokens.add(self.unknown_token) elif token in tokens: warnings.warn('line {} in {}: duplicate embedding found for ' 'token "{}". Skipped.'.format(line_num, pretrained_file_path, token)) elif len(elems) == 1 and line_num == 0: warnings.warn('line {} in {}: skipped likely header line.' .format(line_num, pretrained_file_path)) else: if not vec_len: vec_len = len(elems) if self.unknown_token: # Reserve a vector slot for the unknown token at the very beggining # because the unknown token index is 0. all_elems.extend([0] * vec_len) else: assert len(elems) == vec_len, \ 'line {} in {}: found vector of inconsistent dimension for token ' \ '"{}". expected dim: {}, found: {}'.format(line_num, pretrained_file_path, token, vec_len, len(elems)) all_elems.extend(elems) self._idx_to_token.append(token) self._token_to_idx[token] = len(self._idx_to_token) - 1 tokens.add(token) self._idx_to_vec = nd.array(all_elems).reshape((-1, vec_len)) if self.unknown_token: if loaded_unknown_vec is None: self._idx_to_vec[C.UNK_IDX] = self._init_unknown_vec(shape=vec_len) else: self._idx_to_vec[C.UNK_IDX] = nd.array(loaded_unknown_vec)
[ "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", ",", "line", "in", "enumerate", "(", "f", ")", ":", "try", ":", "line", "=", "line", ".", "decode", "(", "encoding", ")", "except", "ValueError", ":", "warnings", ".", "warn", "(", "'line {} in {}: failed to decode. Skipping.'", ".", "format", "(", "line_num", ",", "pretrained_file_path", ")", ")", "continue", "elems", "=", "line", ".", "rstrip", "(", ")", ".", "split", "(", "elem_delim", ")", "assert", "len", "(", "elems", ")", ">", "1", ",", "'line {} in {}: unexpected data format.'", ".", "format", "(", "line_num", ",", "pretrained_file_path", ")", "token", ",", "elems", "=", "elems", "[", "0", "]", ",", "[", "float", "(", "i", ")", "for", "i", "in", "elems", "[", "1", ":", "]", "]", "if", "token", "==", "self", ".", "unknown_token", "and", "loaded_unknown_vec", "is", "None", ":", "loaded_unknown_vec", "=", "elems", "tokens", ".", "add", "(", "self", ".", "unknown_token", ")", "elif", "token", "in", "tokens", ":", "warnings", ".", "warn", "(", "'line {} in {}: duplicate embedding found for '", "'token \"{}\". Skipped.'", ".", "format", "(", "line_num", ",", "pretrained_file_path", ",", "token", ")", ")", "elif", "len", "(", "elems", ")", "==", "1", "and", "line_num", "==", "0", ":", "warnings", ".", "warn", "(", "'line {} in {}: skipped likely header line.'", ".", "format", "(", "line_num", ",", "pretrained_file_path", ")", ")", "else", ":", "if", "not", "vec_len", ":", "vec_len", "=", "len", "(", "elems", ")", "if", "self", ".", "unknown_token", ":", "# Reserve a vector slot for the unknown token at the very beggining", "# because the unknown token index is 0.", "all_elems", ".", "extend", "(", "[", "0", "]", "*", "vec_len", ")", "else", ":", "assert", "len", "(", "elems", ")", "==", "vec_len", ",", "'line {} in {}: found vector of inconsistent dimension for token '", "'\"{}\". expected dim: {}, found: {}'", ".", "format", "(", "line_num", ",", "pretrained_file_path", ",", "token", ",", "vec_len", ",", "len", "(", "elems", ")", ")", "all_elems", ".", "extend", "(", "elems", ")", "self", ".", "_idx_to_token", ".", "append", "(", "token", ")", "self", ".", "_token_to_idx", "[", "token", "]", "=", "len", "(", "self", ".", "_idx_to_token", ")", "-", "1", "tokens", ".", "add", "(", "token", ")", "self", ".", "_idx_to_vec", "=", "nd", ".", "array", "(", "all_elems", ")", ".", "reshape", "(", "(", "-", "1", ",", "vec_len", ")", ")", "if", "self", ".", "unknown_token", ":", "if", "loaded_unknown_vec", "is", "None", ":", "self", ".", "_idx_to_vec", "[", "C", ".", "UNK_IDX", "]", "=", "self", ".", "_init_unknown_vec", "(", "shape", "=", "vec_len", ")", "else", ":", "self", ".", "_idx_to_vec", "[", "C", ".", "UNK_IDX", "]", "=", "nd", ".", "array", "(", "loaded_unknown_vec", ")" ]
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, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. If a token is encountered multiple times in the pre-trained text embedding file, only the first-encountered token embedding vector will be loaded and the rest will be skipped.
[ "Load", "embedding", "vectors", "from", "a", "pre", "-", "trained", "token", "embedding", "file", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L255-L321
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding._load_embedding_serialized
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-trained token embedding vector loaded from the file; otherwise, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. ValueError is raised if a token occurs multiple times. """ deserialized_embedding = TokenEmbedding.deserialize(pretrained_file_path) if deserialized_embedding.unknown_token: # Some .npz files on S3 may contain an unknown token and its # respective embedding. As a workaround, we assume that C.UNK_IDX # is the same now as it was when the .npz was generated. Under this # assumption we can safely overwrite the respective token and # vector from the npz. if deserialized_embedding.unknown_token: idx_to_token = deserialized_embedding.idx_to_token idx_to_vec = deserialized_embedding.idx_to_vec idx_to_token[C.UNK_IDX] = self.unknown_token if self._init_unknown_vec: vec_len = idx_to_vec.shape[1] idx_to_vec[C.UNK_IDX] = self._init_unknown_vec(shape=vec_len) else: # If the TokenEmbedding shall not have an unknown token, we # just delete the one in the npz. assert C.UNK_IDX == 0 idx_to_token = deserialized_embedding.idx_to_token[C.UNK_IDX + 1:] idx_to_vec = deserialized_embedding.idx_to_vec[C.UNK_IDX + 1:] else: idx_to_token = deserialized_embedding.idx_to_token idx_to_vec = deserialized_embedding.idx_to_vec if not len(set(idx_to_token)) == len(idx_to_token): raise ValueError('Serialized embedding invalid. ' 'It contains duplicate tokens.') if self.unknown_token: try: unknown_token_idx = deserialized_embedding.idx_to_token.index( self.unknown_token) idx_to_token[C.UNK_IDX], idx_to_token[ unknown_token_idx] = idx_to_token[ unknown_token_idx], idx_to_token[C.UNK_IDX] idxs = [C.UNK_IDX, unknown_token_idx] idx_to_vec[idxs] = idx_to_vec[idxs[::-1]] except ValueError: vec_len = idx_to_vec.shape[1] idx_to_token.insert(0, self.unknown_token) idx_to_vec = nd.concat( self._init_unknown_vec(shape=vec_len).reshape((1, -1)), idx_to_vec, dim=0) self._idx_to_token = idx_to_token self._idx_to_vec = idx_to_vec self._token_to_idx.update((token, idx) for idx, token in enumerate(self._idx_to_token))
python
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-trained token embedding vector loaded from the file; otherwise, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. ValueError is raised if a token occurs multiple times. """ deserialized_embedding = TokenEmbedding.deserialize(pretrained_file_path) if deserialized_embedding.unknown_token: # Some .npz files on S3 may contain an unknown token and its # respective embedding. As a workaround, we assume that C.UNK_IDX # is the same now as it was when the .npz was generated. Under this # assumption we can safely overwrite the respective token and # vector from the npz. if deserialized_embedding.unknown_token: idx_to_token = deserialized_embedding.idx_to_token idx_to_vec = deserialized_embedding.idx_to_vec idx_to_token[C.UNK_IDX] = self.unknown_token if self._init_unknown_vec: vec_len = idx_to_vec.shape[1] idx_to_vec[C.UNK_IDX] = self._init_unknown_vec(shape=vec_len) else: # If the TokenEmbedding shall not have an unknown token, we # just delete the one in the npz. assert C.UNK_IDX == 0 idx_to_token = deserialized_embedding.idx_to_token[C.UNK_IDX + 1:] idx_to_vec = deserialized_embedding.idx_to_vec[C.UNK_IDX + 1:] else: idx_to_token = deserialized_embedding.idx_to_token idx_to_vec = deserialized_embedding.idx_to_vec if not len(set(idx_to_token)) == len(idx_to_token): raise ValueError('Serialized embedding invalid. ' 'It contains duplicate tokens.') if self.unknown_token: try: unknown_token_idx = deserialized_embedding.idx_to_token.index( self.unknown_token) idx_to_token[C.UNK_IDX], idx_to_token[ unknown_token_idx] = idx_to_token[ unknown_token_idx], idx_to_token[C.UNK_IDX] idxs = [C.UNK_IDX, unknown_token_idx] idx_to_vec[idxs] = idx_to_vec[idxs[::-1]] except ValueError: vec_len = idx_to_vec.shape[1] idx_to_token.insert(0, self.unknown_token) idx_to_vec = nd.concat( self._init_unknown_vec(shape=vec_len).reshape((1, -1)), idx_to_vec, dim=0) self._idx_to_token = idx_to_token self._idx_to_vec = idx_to_vec self._token_to_idx.update((token, idx) for idx, token in enumerate(self._idx_to_token))
[ "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", "# respective embedding. As a workaround, we assume that C.UNK_IDX", "# is the same now as it was when the .npz was generated. Under this", "# assumption we can safely overwrite the respective token and", "# vector from the npz.", "if", "deserialized_embedding", ".", "unknown_token", ":", "idx_to_token", "=", "deserialized_embedding", ".", "idx_to_token", "idx_to_vec", "=", "deserialized_embedding", ".", "idx_to_vec", "idx_to_token", "[", "C", ".", "UNK_IDX", "]", "=", "self", ".", "unknown_token", "if", "self", ".", "_init_unknown_vec", ":", "vec_len", "=", "idx_to_vec", ".", "shape", "[", "1", "]", "idx_to_vec", "[", "C", ".", "UNK_IDX", "]", "=", "self", ".", "_init_unknown_vec", "(", "shape", "=", "vec_len", ")", "else", ":", "# If the TokenEmbedding shall not have an unknown token, we", "# just delete the one in the npz.", "assert", "C", ".", "UNK_IDX", "==", "0", "idx_to_token", "=", "deserialized_embedding", ".", "idx_to_token", "[", "C", ".", "UNK_IDX", "+", "1", ":", "]", "idx_to_vec", "=", "deserialized_embedding", ".", "idx_to_vec", "[", "C", ".", "UNK_IDX", "+", "1", ":", "]", "else", ":", "idx_to_token", "=", "deserialized_embedding", ".", "idx_to_token", "idx_to_vec", "=", "deserialized_embedding", ".", "idx_to_vec", "if", "not", "len", "(", "set", "(", "idx_to_token", ")", ")", "==", "len", "(", "idx_to_token", ")", ":", "raise", "ValueError", "(", "'Serialized embedding invalid. '", "'It contains duplicate tokens.'", ")", "if", "self", ".", "unknown_token", ":", "try", ":", "unknown_token_idx", "=", "deserialized_embedding", ".", "idx_to_token", ".", "index", "(", "self", ".", "unknown_token", ")", "idx_to_token", "[", "C", ".", "UNK_IDX", "]", ",", "idx_to_token", "[", "unknown_token_idx", "]", "=", "idx_to_token", "[", "unknown_token_idx", "]", ",", "idx_to_token", "[", "C", ".", "UNK_IDX", "]", "idxs", "=", "[", "C", ".", "UNK_IDX", ",", "unknown_token_idx", "]", "idx_to_vec", "[", "idxs", "]", "=", "idx_to_vec", "[", "idxs", "[", ":", ":", "-", "1", "]", "]", "except", "ValueError", ":", "vec_len", "=", "idx_to_vec", ".", "shape", "[", "1", "]", "idx_to_token", ".", "insert", "(", "0", ",", "self", ".", "unknown_token", ")", "idx_to_vec", "=", "nd", ".", "concat", "(", "self", ".", "_init_unknown_vec", "(", "shape", "=", "vec_len", ")", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", ",", "idx_to_vec", ",", "dim", "=", "0", ")", "self", ".", "_idx_to_token", "=", "idx_to_token", "self", ".", "_idx_to_vec", "=", "idx_to_vec", "self", ".", "_token_to_idx", ".", "update", "(", "(", "token", ",", "idx", ")", "for", "idx", ",", "token", "in", "enumerate", "(", "self", ".", "_idx_to_token", ")", ")" ]
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, index 0 of `self.idx_to_vec` maps to the text embedding vector initialized by `self._init_unknown_vec`. ValueError is raised if a token occurs multiple times.
[ "Load", "embedding", "vectors", "from", "a", "pre", "-", "trained", "token", "embedding", "file", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L323-L380
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding._check_vector_update
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 isinstance(new_embedding, nd.NDArray) and len(new_embedding.shape) in [1, 2], \ '`new_embedding` must be a 1-D or 2-D NDArray if `tokens` is a single token.' if not isinstance(tokens, (list, tuple)): tokens = [tokens] if len(new_embedding.shape) == 1: new_embedding = new_embedding.expand_dims(0) else: assert isinstance(new_embedding, nd.NDArray) and len(new_embedding.shape) == 2, \ '`new_embedding` must be a 2-D NDArray if `tokens` is a list of multiple strings.' if self._idx_to_vec is not None: assert new_embedding.shape == (len(tokens), self._idx_to_vec.shape[1]), \ 'The length of `new_embedding` must be equal to the number ' \ 'of tokens and the width of new_embedding must be equal ' \ 'to the dimension of embedding of the glossary.' else: assert new_embedding.shape[0] == len(tokens), \ 'The length of `new_embedding` must be equal to the number of tokens' return tokens
python
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 isinstance(new_embedding, nd.NDArray) and len(new_embedding.shape) in [1, 2], \ '`new_embedding` must be a 1-D or 2-D NDArray if `tokens` is a single token.' if not isinstance(tokens, (list, tuple)): tokens = [tokens] if len(new_embedding.shape) == 1: new_embedding = new_embedding.expand_dims(0) else: assert isinstance(new_embedding, nd.NDArray) and len(new_embedding.shape) == 2, \ '`new_embedding` must be a 2-D NDArray if `tokens` is a list of multiple strings.' if self._idx_to_vec is not None: assert new_embedding.shape == (len(tokens), self._idx_to_vec.shape[1]), \ 'The length of `new_embedding` must be equal to the number ' \ 'of tokens and the width of new_embedding must be equal ' \ 'to the dimension of embedding of the glossary.' else: assert new_embedding.shape[0] == len(tokens), \ 'The length of `new_embedding` must be equal to the number of tokens' return tokens
[ "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", ".", "NDArray", ")", "and", "len", "(", "new_embedding", ".", "shape", ")", "in", "[", "1", ",", "2", "]", ",", "'`new_embedding` must be a 1-D or 2-D NDArray if `tokens` is a single token.'", "if", "not", "isinstance", "(", "tokens", ",", "(", "list", ",", "tuple", ")", ")", ":", "tokens", "=", "[", "tokens", "]", "if", "len", "(", "new_embedding", ".", "shape", ")", "==", "1", ":", "new_embedding", "=", "new_embedding", ".", "expand_dims", "(", "0", ")", "else", ":", "assert", "isinstance", "(", "new_embedding", ",", "nd", ".", "NDArray", ")", "and", "len", "(", "new_embedding", ".", "shape", ")", "==", "2", ",", "'`new_embedding` must be a 2-D NDArray if `tokens` is a list of multiple strings.'", "if", "self", ".", "_idx_to_vec", "is", "not", "None", ":", "assert", "new_embedding", ".", "shape", "==", "(", "len", "(", "tokens", ")", ",", "self", ".", "_idx_to_vec", ".", "shape", "[", "1", "]", ")", ",", "'The length of `new_embedding` must be equal to the number '", "'of tokens and the width of new_embedding must be equal '", "'to the dimension of embedding of the glossary.'", "else", ":", "assert", "new_embedding", ".", "shape", "[", "0", "]", "==", "len", "(", "tokens", ")", ",", "'The length of `new_embedding` must be equal to the number of tokens'", "return", "tokens" ]
Check that tokens and embedding are in the format for __setitem__.
[ "Check", "that", "tokens", "and", "embedding", "are", "in", "the", "format", "for", "__setitem__", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L553-L576
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding._check_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 source_file_hash: raise KeyError('Cannot find pre-trained source {} for token embedding {}. ' 'Valid pre-trained file names for embedding {}: {}'.format( source, embedding_name, embedding_name, ', '.join(source_file_hash.keys())))
python
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 source_file_hash: raise KeyError('Cannot find pre-trained source {} for token embedding {}. ' 'Valid pre-trained file names for embedding {}: {}'.format( source, embedding_name, embedding_name, ', '.join(source_file_hash.keys())))
[ "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-trained file names for embedding {}: {}'", ".", "format", "(", "source", ",", "embedding_name", ",", "embedding_name", ",", "', '", ".", "join", "(", "source_file_hash", ".", "keys", "(", ")", ")", ")", ")" ]
Checks if a pre-trained token embedding source name is valid. Parameters ---------- source : str The pre-trained token embedding source.
[ "Checks", "if", "a", "pre", "-", "trained", "token", "embedding", "source", "name", "is", "valid", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L643-L657
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding.from_file
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 custom pre-trained token embedding file may look like: 'hello 0.1 0.2 0.3 0.4 0.5\\\\nworld 1.1 1.2 1.3 1.4 1.5\\\\n' where embedding vectors of words `hello` and `world` are [0.1, 0.2, 0.3, 0.4, 0.5] and [1.1, 1.2, 1.3, 1.4, 1.5] respectively. Parameters ---------- file_path : str The path to the user-defined pre-trained token embedding file. elem_delim : str, default ' ' The delimiter for splitting a token and every embedding vector element value on the same line of the custom pre-trained token embedding file. encoding : str, default 'utf8' The encoding scheme for reading the custom pre-trained token embedding file. kwargs : dict All other keyword arguments are passed to the TokenEmbedding initializer. Returns ------- instance of :class:`gluonnlp.embedding.TokenEmbedding` The user-defined token embedding instance. """ embedding = TokenEmbedding(**kwargs) embedding._load_embedding(file_path, elem_delim=elem_delim, encoding=encoding) return embedding
python
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 custom pre-trained token embedding file may look like: 'hello 0.1 0.2 0.3 0.4 0.5\\\\nworld 1.1 1.2 1.3 1.4 1.5\\\\n' where embedding vectors of words `hello` and `world` are [0.1, 0.2, 0.3, 0.4, 0.5] and [1.1, 1.2, 1.3, 1.4, 1.5] respectively. Parameters ---------- file_path : str The path to the user-defined pre-trained token embedding file. elem_delim : str, default ' ' The delimiter for splitting a token and every embedding vector element value on the same line of the custom pre-trained token embedding file. encoding : str, default 'utf8' The encoding scheme for reading the custom pre-trained token embedding file. kwargs : dict All other keyword arguments are passed to the TokenEmbedding initializer. Returns ------- instance of :class:`gluonnlp.embedding.TokenEmbedding` The user-defined token embedding instance. """ embedding = TokenEmbedding(**kwargs) embedding._load_embedding(file_path, elem_delim=elem_delim, encoding=encoding) return embedding
[ "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. 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 0.1 0.2 0.3 0.4 0.5\\\\nworld 1.1 1.2 1.3 1.4 1.5\\\\n' where embedding vectors of words `hello` and `world` are [0.1, 0.2, 0.3, 0.4, 0.5] and [1.1, 1.2, 1.3, 1.4, 1.5] respectively. Parameters ---------- file_path : str The path to the user-defined pre-trained token embedding file. elem_delim : str, default ' ' The delimiter for splitting a token and every embedding vector element value on the same line of the custom pre-trained token embedding file. encoding : str, default 'utf8' The encoding scheme for reading the custom pre-trained token embedding file. kwargs : dict All other keyword arguments are passed to the TokenEmbedding initializer. Returns ------- instance of :class:`gluonnlp.embedding.TokenEmbedding` The user-defined token embedding instance.
[ "Creates", "a", "user", "-", "defined", "token", "embedding", "from", "a", "pre", "-", "trained", "embedding", "file", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L660-L694
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding.serialize
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) Zipfile. See https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more information on the format. Parameters ---------- file_path : str or file The path at which to create the file holding the serialized TokenEmbedding. If file is a string or a Path, the .npz extension will be appended to the file name if it is not already there. compress : bool, default True Compress the Zipfile or leave it uncompressed. """ 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 ' 'during deserialization.') unknown_token = np.array(self.unknown_token) idx_to_token = np.array(self.idx_to_token, dtype='O') idx_to_vec = self.idx_to_vec.asnumpy() if not unknown_token: # Store empty string instead of None unknown_token = '' else: assert unknown_token == idx_to_token[C.UNK_IDX] if not compress: np.savez(file=file_path, unknown_token=unknown_token, idx_to_token=idx_to_token, idx_to_vec=idx_to_vec) else: np.savez_compressed(file=file_path, unknown_token=unknown_token, idx_to_token=idx_to_token, idx_to_vec=idx_to_vec)
python
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) Zipfile. See https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more information on the format. Parameters ---------- file_path : str or file The path at which to create the file holding the serialized TokenEmbedding. If file is a string or a Path, the .npz extension will be appended to the file name if it is not already there. compress : bool, default True Compress the Zipfile or leave it uncompressed. """ 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 ' 'during deserialization.') unknown_token = np.array(self.unknown_token) idx_to_token = np.array(self.idx_to_token, dtype='O') idx_to_vec = self.idx_to_vec.asnumpy() if not unknown_token: # Store empty string instead of None unknown_token = '' else: assert unknown_token == idx_to_token[C.UNK_IDX] if not compress: np.savez(file=file_path, unknown_token=unknown_token, idx_to_token=idx_to_token, idx_to_vec=idx_to_vec) else: np.savez_compressed(file=file_path, unknown_token=unknown_token, idx_to_token=idx_to_token, idx_to_vec=idx_to_vec)
[ "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 '", "'during deserialization.'", ")", "unknown_token", "=", "np", ".", "array", "(", "self", ".", "unknown_token", ")", "idx_to_token", "=", "np", ".", "array", "(", "self", ".", "idx_to_token", ",", "dtype", "=", "'O'", ")", "idx_to_vec", "=", "self", ".", "idx_to_vec", ".", "asnumpy", "(", ")", "if", "not", "unknown_token", ":", "# Store empty string instead of None", "unknown_token", "=", "''", "else", ":", "assert", "unknown_token", "==", "idx_to_token", "[", "C", ".", "UNK_IDX", "]", "if", "not", "compress", ":", "np", ".", "savez", "(", "file", "=", "file_path", ",", "unknown_token", "=", "unknown_token", ",", "idx_to_token", "=", "idx_to_token", ",", "idx_to_vec", "=", "idx_to_vec", ")", "else", ":", "np", ".", "savez_compressed", "(", "file", "=", "file_path", ",", "unknown_token", "=", "unknown_token", ",", "idx_to_token", "=", "idx_to_token", ",", "idx_to_vec", "=", "idx_to_vec", ")" ]
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.14.2/neps/npy-format.html for more information on the format. Parameters ---------- file_path : str or file The path at which to create the file holding the serialized TokenEmbedding. If file is a string or a Path, the .npz extension will be appended to the file name if it is not already there. compress : bool, default True Compress the Zipfile or leave it uncompressed.
[ "Serializes", "the", "TokenEmbedding", "to", "a", "file", "specified", "by", "file_path", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L696-L737
train
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
TokenEmbedding.deserialize
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 https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more information on the format. Parameters ---------- file_path : str or file The path to a file that holds the serialized TokenEmbedding. kwargs : dict Keyword arguments are passed to the TokenEmbedding initializer. Useful for attaching unknown_lookup. """ # 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_token = None else: if isinstance(unknown_token, np.ndarray): if unknown_token.dtype.kind == 'S': unknown_token = unknown_token.tobytes().decode() else: unknown_token = str(unknown_token) idx_to_token = npz_dict['idx_to_token'].tolist() idx_to_vec = nd.array(npz_dict['idx_to_vec']) embedding = cls(unknown_token=unknown_token, **kwargs) if unknown_token: assert unknown_token == idx_to_token[C.UNK_IDX] embedding._token_to_idx = DefaultLookupDict(C.UNK_IDX) else: embedding._token_to_idx = {} embedding._idx_to_token = idx_to_token embedding._idx_to_vec = idx_to_vec embedding._token_to_idx.update((token, idx) for idx, token in enumerate(idx_to_token)) return embedding
python
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 https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more information on the format. Parameters ---------- file_path : str or file The path to a file that holds the serialized TokenEmbedding. kwargs : dict Keyword arguments are passed to the TokenEmbedding initializer. Useful for attaching unknown_lookup. """ # 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_token = None else: if isinstance(unknown_token, np.ndarray): if unknown_token.dtype.kind == 'S': unknown_token = unknown_token.tobytes().decode() else: unknown_token = str(unknown_token) idx_to_token = npz_dict['idx_to_token'].tolist() idx_to_vec = nd.array(npz_dict['idx_to_vec']) embedding = cls(unknown_token=unknown_token, **kwargs) if unknown_token: assert unknown_token == idx_to_token[C.UNK_IDX] embedding._token_to_idx = DefaultLookupDict(C.UNK_IDX) else: embedding._token_to_idx = {} embedding._idx_to_token = idx_to_token embedding._idx_to_vec = idx_to_vec embedding._token_to_idx.update((token, idx) for idx, token in enumerate(idx_to_token)) return embedding
[ "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_token", "=", "None", "else", ":", "if", "isinstance", "(", "unknown_token", ",", "np", ".", "ndarray", ")", ":", "if", "unknown_token", ".", "dtype", ".", "kind", "==", "'S'", ":", "unknown_token", "=", "unknown_token", ".", "tobytes", "(", ")", ".", "decode", "(", ")", "else", ":", "unknown_token", "=", "str", "(", "unknown_token", ")", "idx_to_token", "=", "npz_dict", "[", "'idx_to_token'", "]", ".", "tolist", "(", ")", "idx_to_vec", "=", "nd", ".", "array", "(", "npz_dict", "[", "'idx_to_vec'", "]", ")", "embedding", "=", "cls", "(", "unknown_token", "=", "unknown_token", ",", "*", "*", "kwargs", ")", "if", "unknown_token", ":", "assert", "unknown_token", "==", "idx_to_token", "[", "C", ".", "UNK_IDX", "]", "embedding", ".", "_token_to_idx", "=", "DefaultLookupDict", "(", "C", ".", "UNK_IDX", ")", "else", ":", "embedding", ".", "_token_to_idx", "=", "{", "}", "embedding", ".", "_idx_to_token", "=", "idx_to_token", "embedding", ".", "_idx_to_vec", "=", "idx_to_vec", "embedding", ".", "_token_to_idx", ".", "update", "(", "(", "token", ",", "idx", ")", "for", "idx", ",", "token", "in", "enumerate", "(", "idx_to_token", ")", ")", "return", "embedding" ]
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-format.html for more information on the format. Parameters ---------- file_path : str or file The path to a file that holds the serialized TokenEmbedding. kwargs : dict Keyword arguments are passed to the TokenEmbedding initializer. Useful for attaching unknown_lookup.
[ "Create", "a", "new", "TokenEmbedding", "from", "a", "serialized", "one", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L740-L784
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_export_squad.py
evaluate
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').as_in_context(ctx), valid_length.astype('float32').as_in_context(ctx)) toc = time.time() log.info('Inference time cost={:.2f} s, Thoughput={:.2f} samples/s' .format(toc - tic, len(data_source) / (toc - tic)))
python
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').as_in_context(ctx), valid_length.astype('float32').as_in_context(ctx)) toc = time.time() log.info('Inference time cost={:.2f} s, Thoughput={:.2f} samples/s' .format(toc - tic, len(data_source) / (toc - tic)))
[ "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'", ")", ".", "as_in_context", "(", "ctx", ")", ",", "valid_length", ".", "astype", "(", "'float32'", ")", ".", "as_in_context", "(", "ctx", ")", ")", "toc", "=", "time", ".", "time", "(", ")", "log", ".", "info", "(", "'Inference time cost={:.2f} s, Thoughput={:.2f} samples/s'", ".", "format", "(", "toc", "-", "tic", ",", "len", "(", "data_source", ")", "/", "(", "toc", "-", "tic", ")", ")", ")" ]
Evaluate the model on a mini-batch.
[ "Evaluate", "the", "model", "on", "a", "mini", "-", "batch", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_export_squad.py#L210-L223
train
dmlc/gluon-nlp
src/gluonnlp/data/registry.py
register
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 retrieved with the `list_datasets` function. All arguments that result in creation of separate datasets should be registered. Examples are datasets divided in different segments or categories, or datasets containing multiple languages. Once registered, an instance can be created by calling :func:`~gluonnlp.data.create` with the class name. Parameters ---------- **kwargs : list or tuple of allowed argument values For each keyword argument, it's value must be a list or tuple of the allowed argument values. Examples -------- >>> @gluonnlp.data.register(segment=['train', 'test', 'dev']) ... class MyDataset(gluon.data.Dataset): ... def __init__(self, segment='train'): ... pass >>> my_dataset = gluonnlp.data.create('MyDataset') >>> print(type(my_dataset)) <class 'MyDataset'> """ 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 except AttributeError: # pylint: disable=deprecated-method real_args = inspect.getargspec(class_.__init__).args if not kwarg_name in real_args: raise RuntimeError( ('{} is not a valid argument for {}. ' 'Only valid arguments can be registered.').format( kwarg_name, class_.__name__)) if not isinstance(values, (list, tuple)): raise RuntimeError(('{} should be a list of ' 'valid arguments for {}. ').format( values, kwarg_name)) # Save the kwargs associated with this class_ _REGSITRY_NAME_KWARGS[class_] = kwargs register_ = registry.get_register_func(Dataset, 'dataset') return register_(class_) if class_ is not None: # Decorator was called without arguments return _real_register(class_) return _real_register
python
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 retrieved with the `list_datasets` function. All arguments that result in creation of separate datasets should be registered. Examples are datasets divided in different segments or categories, or datasets containing multiple languages. Once registered, an instance can be created by calling :func:`~gluonnlp.data.create` with the class name. Parameters ---------- **kwargs : list or tuple of allowed argument values For each keyword argument, it's value must be a list or tuple of the allowed argument values. Examples -------- >>> @gluonnlp.data.register(segment=['train', 'test', 'dev']) ... class MyDataset(gluon.data.Dataset): ... def __init__(self, segment='train'): ... pass >>> my_dataset = gluonnlp.data.create('MyDataset') >>> print(type(my_dataset)) <class 'MyDataset'> """ 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 except AttributeError: # pylint: disable=deprecated-method real_args = inspect.getargspec(class_.__init__).args if not kwarg_name in real_args: raise RuntimeError( ('{} is not a valid argument for {}. ' 'Only valid arguments can be registered.').format( kwarg_name, class_.__name__)) if not isinstance(values, (list, tuple)): raise RuntimeError(('{} should be a list of ' 'valid arguments for {}. ').format( values, kwarg_name)) # Save the kwargs associated with this class_ _REGSITRY_NAME_KWARGS[class_] = kwargs register_ = registry.get_register_func(Dataset, 'dataset') return register_(class_) if class_ is not None: # Decorator was called without arguments return _real_register(class_) return _real_register
[ "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", "except", "AttributeError", ":", "# pylint: disable=deprecated-method", "real_args", "=", "inspect", ".", "getargspec", "(", "class_", ".", "__init__", ")", ".", "args", "if", "not", "kwarg_name", "in", "real_args", ":", "raise", "RuntimeError", "(", "(", "'{} is not a valid argument for {}. '", "'Only valid arguments can be registered.'", ")", ".", "format", "(", "kwarg_name", ",", "class_", ".", "__name__", ")", ")", "if", "not", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "RuntimeError", "(", "(", "'{} should be a list of '", "'valid arguments for {}. '", ")", ".", "format", "(", "values", ",", "kwarg_name", ")", ")", "# Save the kwargs associated with this class_", "_REGSITRY_NAME_KWARGS", "[", "class_", "]", "=", "kwargs", "register_", "=", "registry", ".", "get_register_func", "(", "Dataset", ",", "'dataset'", ")", "return", "register_", "(", "class_", ")", "if", "class_", "is", "not", "None", ":", "# Decorator was called without arguments", "return", "_real_register", "(", "class_", ")", "return", "_real_register" ]
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` function. All arguments that result in creation of separate datasets should be registered. Examples are datasets divided in different segments or categories, or datasets containing multiple languages. Once registered, an instance can be created by calling :func:`~gluonnlp.data.create` with the class name. Parameters ---------- **kwargs : list or tuple of allowed argument values For each keyword argument, it's value must be a list or tuple of the allowed argument values. Examples -------- >>> @gluonnlp.data.register(segment=['train', 'test', 'dev']) ... class MyDataset(gluon.data.Dataset): ... def __init__(self, segment='train'): ... pass >>> my_dataset = gluonnlp.data.create('MyDataset') >>> print(type(my_dataset)) <class 'MyDataset'>
[ "Registers", "a", "dataset", "with", "segment", "specific", "hyperparameters", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L34-L97
train
dmlc/gluon-nlp
src/gluonnlp/data/registry.py
create
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 function. """ create_ = registry.get_create_func(Dataset, 'dataset') return create_(name, **kwargs)
python
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 function. """ create_ = registry.get_create_func(Dataset, 'dataset') return create_(name, **kwargs)
[ "def", "create", "(", "name", ",", "*", "*", "kwargs", ")", ":", "create_", "=", "registry", ".", "get_create_func", "(", "Dataset", ",", "'dataset'", ")", "return", "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 function.
[ "Creates", "an", "instance", "of", "a", "registered", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L100-L115
train
dmlc/gluon-nlp
src/gluonnlp/data/registry.py
list_datasets
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 returned. Returns ------- dict: A dict of all the valid keyword parameters names for the specified dataset. If name is set to None, returns a dict mapping each valid name to its respective keyword parameter dict. The valid names can be plugged in `gluonnlp.model.word_evaluation_model.create(name)`. """ 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_] for dataset_name, class_ in registry.get_registry(Dataset).items() }
python
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 returned. Returns ------- dict: A dict of all the valid keyword parameters names for the specified dataset. If name is set to None, returns a dict mapping each valid name to its respective keyword parameter dict. The valid names can be plugged in `gluonnlp.model.word_evaluation_model.create(name)`. """ 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_] for dataset_name, class_ in registry.get_registry(Dataset).items() }
[ "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_", "]", "for", "dataset_name", ",", "class_", "in", "registry", ".", "get_registry", "(", "Dataset", ")", ".", "items", "(", ")", "}" ]
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 ------- dict: A dict of all the valid keyword parameters names for the specified dataset. If name is set to None, returns a dict mapping each valid name to its respective keyword parameter dict. The valid names can be plugged in `gluonnlp.model.word_evaluation_model.create(name)`.
[ "Get", "valid", "datasets", "and", "registered", "parameters", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L118-L146
train
dmlc/gluon-nlp
scripts/word_embeddings/extract_vocab.py
parse_args
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, default=5) parser.add_argument('--max-word-length', type=int, default=50) parser.add_argument('files', type=str, nargs='+') parser.add_argument('--vocab-output', type=str, default='vocab.json') parser.add_argument('--counts-output', type=str, default='counts.json') args = parser.parse_args() return args
python
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, default=5) parser.add_argument('--max-word-length', type=int, default=50) parser.add_argument('files', type=str, nargs='+') parser.add_argument('--vocab-output', type=str, default='vocab.json') parser.add_argument('--counts-output', type=str, default='counts.json') args = parser.parse_args() return args
[ "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", "=", "int", ",", "default", "=", "5", ")", "parser", ".", "add_argument", "(", "'--max-word-length'", ",", "type", "=", "int", ",", "default", "=", "50", ")", "parser", ".", "add_argument", "(", "'files'", ",", "type", "=", "str", ",", "nargs", "=", "'+'", ")", "parser", ".", "add_argument", "(", "'--vocab-output'", ",", "type", "=", "str", ",", "default", "=", "'vocab.json'", ")", "parser", ".", "add_argument", "(", "'--counts-output'", ",", "type", "=", "str", ",", "default", "=", "'counts.json'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "return", "args" ]
Parse command line arguments.
[ "Parse", "command", "line", "arguments", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/extract_vocab.py#L32-L44
train
dmlc/gluon-nlp
scripts/word_embeddings/extract_vocab.py
get_vocab
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: tokens = itertools.chain.from_iterable((l.split() for l in f)) counter.update(tokens) if args.max_word_length: counter = { w: c for w, c in counter.items() if len(w) < args.max_word_length } total_time = time.time() - start print('Finished after {:.1f} seconds.'.format(total_time)) num_words = sum(counter.values()) print('Got {} words. Processed {:.1f} per second.'.format( num_words, num_words / total_time)) start = time.time() print('Starting creation of vocabulary.') vocab = nlp.Vocab(counter, max_size=args.max_size, min_freq=args.min_freq, unknown_token=None, padding_token=None, bos_token=None, eos_token=None) with open(args.vocab_output, 'w') as f: f.write(vocab.to_json()) print('Finished creation of vocabulary after {:.1f} seconds.'.format( time.time() - start)) print('Writing word counts.') start = time.time() idx_to_counts = [counter[t] for t in vocab.idx_to_token] with open(args.counts_output, 'w') as f: json.dump(idx_to_counts, f) print('Finished writing word counts after {:.1f} seconds..'.format( time.time() - start))
python
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: tokens = itertools.chain.from_iterable((l.split() for l in f)) counter.update(tokens) if args.max_word_length: counter = { w: c for w, c in counter.items() if len(w) < args.max_word_length } total_time = time.time() - start print('Finished after {:.1f} seconds.'.format(total_time)) num_words = sum(counter.values()) print('Got {} words. Processed {:.1f} per second.'.format( num_words, num_words / total_time)) start = time.time() print('Starting creation of vocabulary.') vocab = nlp.Vocab(counter, max_size=args.max_size, min_freq=args.min_freq, unknown_token=None, padding_token=None, bos_token=None, eos_token=None) with open(args.vocab_output, 'w') as f: f.write(vocab.to_json()) print('Finished creation of vocabulary after {:.1f} seconds.'.format( time.time() - start)) print('Writing word counts.') start = time.time() idx_to_counts = [counter[t] for t in vocab.idx_to_token] with open(args.counts_output, 'w') as f: json.dump(idx_to_counts, f) print('Finished writing word counts after {:.1f} seconds..'.format( time.time() - start))
[ "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'", ")", "as", "f", ":", "tokens", "=", "itertools", ".", "chain", ".", "from_iterable", "(", "(", "l", ".", "split", "(", ")", "for", "l", "in", "f", ")", ")", "counter", ".", "update", "(", "tokens", ")", "if", "args", ".", "max_word_length", ":", "counter", "=", "{", "w", ":", "c", "for", "w", ",", "c", "in", "counter", ".", "items", "(", ")", "if", "len", "(", "w", ")", "<", "args", ".", "max_word_length", "}", "total_time", "=", "time", ".", "time", "(", ")", "-", "start", "print", "(", "'Finished after {:.1f} seconds.'", ".", "format", "(", "total_time", ")", ")", "num_words", "=", "sum", "(", "counter", ".", "values", "(", ")", ")", "print", "(", "'Got {} words. Processed {:.1f} per second.'", ".", "format", "(", "num_words", ",", "num_words", "/", "total_time", ")", ")", "start", "=", "time", ".", "time", "(", ")", "print", "(", "'Starting creation of vocabulary.'", ")", "vocab", "=", "nlp", ".", "Vocab", "(", "counter", ",", "max_size", "=", "args", ".", "max_size", ",", "min_freq", "=", "args", ".", "min_freq", ",", "unknown_token", "=", "None", ",", "padding_token", "=", "None", ",", "bos_token", "=", "None", ",", "eos_token", "=", "None", ")", "with", "open", "(", "args", ".", "vocab_output", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "vocab", ".", "to_json", "(", ")", ")", "print", "(", "'Finished creation of vocabulary after {:.1f} seconds.'", ".", "format", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "print", "(", "'Writing word counts.'", ")", "start", "=", "time", ".", "time", "(", ")", "idx_to_counts", "=", "[", "counter", "[", "t", "]", "for", "t", "in", "vocab", ".", "idx_to_token", "]", "with", "open", "(", "args", ".", "counts_output", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "idx_to_counts", ",", "f", ")", "print", "(", "'Finished writing word counts after {:.1f} seconds..'", ".", "format", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")" ]
Compute the vocabulary.
[ "Compute", "the", "vocabulary", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/extract_vocab.py#L47-L87
train
dmlc/gluon-nlp
scripts/bert/bert.py
BERTClassifier.forward
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. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to indicate whether the word belongs to the first sentence or the second one. valid_length : NDArray or None, shape (batch_size) Valid length of the sequence. This is used to mask the padded tokens. Returns ------- outputs : NDArray Shape (batch_size, num_classes) """ _, pooler_out = self.bert(inputs, token_types, valid_length) return self.classifier(pooler_out)
python
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. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to indicate whether the word belongs to the first sentence or the second one. valid_length : NDArray or None, shape (batch_size) Valid length of the sequence. This is used to mask the padded tokens. Returns ------- outputs : NDArray Shape (batch_size, num_classes) """ _, pooler_out = self.bert(inputs, token_types, valid_length) return self.classifier(pooler_out)
[ "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. 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 indicate whether the word belongs to the first sentence or the second one. valid_length : NDArray or None, shape (batch_size) Valid length of the sequence. This is used to mask the padded tokens. Returns ------- outputs : NDArray Shape (batch_size, num_classes)
[ "Generate", "the", "unnormalized", "score", "for", "the", "given", "the", "input", "sequences", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert.py#L111-L130
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
add_parameters
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.data.word_embedding_evaluation.word_similarity_datasets, nargs='*', help='Word similarity datasets to use for intrinsic evaluation.') group.add_argument( '--similarity-functions', type=str, default=nlp.embedding.evaluation.list_evaluation_functions( 'similarity'), nargs='+', help='Word similarity functions to use for intrinsic evaluation.') group.add_argument( '--analogy-datasets', type=str, default=['GoogleAnalogyTestSet'], nargs='*', help='Word similarity datasets to use for intrinsic evaluation.') group.add_argument( '--analogy-functions', type=str, default=nlp.embedding.evaluation.list_evaluation_functions('analogy'), nargs='+', help='Word analogy functions to use for intrinsic evaluation. ') ## Analogy evaluation specific arguments group.add_argument( '--analogy-dont-exclude-question-words', action='store_true', help=('Exclude input words from valid output analogies.' 'The performance of word embeddings on the analogy task ' 'is around 0% accuracy if input words are not excluded.'))
python
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.data.word_embedding_evaluation.word_similarity_datasets, nargs='*', help='Word similarity datasets to use for intrinsic evaluation.') group.add_argument( '--similarity-functions', type=str, default=nlp.embedding.evaluation.list_evaluation_functions( 'similarity'), nargs='+', help='Word similarity functions to use for intrinsic evaluation.') group.add_argument( '--analogy-datasets', type=str, default=['GoogleAnalogyTestSet'], nargs='*', help='Word similarity datasets to use for intrinsic evaluation.') group.add_argument( '--analogy-functions', type=str, default=nlp.embedding.evaluation.list_evaluation_functions('analogy'), nargs='+', help='Word analogy functions to use for intrinsic evaluation. ') ## Analogy evaluation specific arguments group.add_argument( '--analogy-dont-exclude-question-words', action='store_true', help=('Exclude input words from valid output analogies.' 'The performance of word embeddings on the analogy task ' 'is around 0% accuracy if input words are not excluded.'))
[ "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", ".", "word_embedding_evaluation", ".", "word_similarity_datasets", ",", "nargs", "=", "'*'", ",", "help", "=", "'Word similarity datasets to use for intrinsic evaluation.'", ")", "group", ".", "add_argument", "(", "'--similarity-functions'", ",", "type", "=", "str", ",", "default", "=", "nlp", ".", "embedding", ".", "evaluation", ".", "list_evaluation_functions", "(", "'similarity'", ")", ",", "nargs", "=", "'+'", ",", "help", "=", "'Word similarity functions to use for intrinsic evaluation.'", ")", "group", ".", "add_argument", "(", "'--analogy-datasets'", ",", "type", "=", "str", ",", "default", "=", "[", "'GoogleAnalogyTestSet'", "]", ",", "nargs", "=", "'*'", ",", "help", "=", "'Word similarity datasets to use for intrinsic evaluation.'", ")", "group", ".", "add_argument", "(", "'--analogy-functions'", ",", "type", "=", "str", ",", "default", "=", "nlp", ".", "embedding", ".", "evaluation", ".", "list_evaluation_functions", "(", "'analogy'", ")", ",", "nargs", "=", "'+'", ",", "help", "=", "'Word analogy functions to use for intrinsic evaluation. '", ")", "## Analogy evaluation specific arguments", "group", ".", "add_argument", "(", "'--analogy-dont-exclude-question-words'", ",", "action", "=", "'store_true'", ",", "help", "=", "(", "'Exclude input words from valid output analogies.'", "'The performance of word embeddings on the analogy task '", "'is around 0% accuracy if input words are not excluded.'", ")", ")" ]
Add evaluation specific parameters to parser.
[ "Add", "evaluation", "specific", "parameters", "to", "parser", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L38-L70
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
validate_args
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_similarity_datasets): print('{} is not a supported dataset.'.format(dataset_name)) sys.exit(1) # Check correctness of analogy dataset names for dataset_name in args.analogy_datasets: if dataset_name.lower() not in map( str.lower, nlp.data.word_embedding_evaluation.word_analogy_datasets): print('{} is not a supported dataset.'.format(dataset_name)) sys.exit(1)
python
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_similarity_datasets): print('{} is not a supported dataset.'.format(dataset_name)) sys.exit(1) # Check correctness of analogy dataset names for dataset_name in args.analogy_datasets: if dataset_name.lower() not in map( str.lower, nlp.data.word_embedding_evaluation.word_analogy_datasets): print('{} is not a supported dataset.'.format(dataset_name)) sys.exit(1)
[ "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_datasets", ")", ":", "print", "(", "'{} is not a supported dataset.'", ".", "format", "(", "dataset_name", ")", ")", "sys", ".", "exit", "(", "1", ")", "# Check correctness of analogy dataset names", "for", "dataset_name", "in", "args", ".", "analogy_datasets", ":", "if", "dataset_name", ".", "lower", "(", ")", "not", "in", "map", "(", "str", ".", "lower", ",", "nlp", ".", "data", ".", "word_embedding_evaluation", ".", "word_analogy_datasets", ")", ":", "print", "(", "'{} is not a supported dataset.'", ".", "format", "(", "dataset_name", ")", ")", "sys", ".", "exit", "(", "1", ")" ]
Validate provided arguments and act on --help.
[ "Validate", "provided", "arguments", "and", "act", "on", "--", "help", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L73-L89
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
iterate_similarity_datasets
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) for key_values in itertools.product(*parameters.values()): kwargs = dict(zip(parameters.keys(), key_values)) yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs)
python
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) for key_values in itertools.product(*parameters.values()): kwargs = dict(zip(parameters.keys(), key_values)) yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs)
[ "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_values", ")", ")", "yield", "dataset_name", ",", "kwargs", ",", "nlp", ".", "data", ".", "create", "(", "dataset_name", ",", "*", "*", "kwargs", ")" ]
Generator over all similarity evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
[ "Generator", "over", "all", "similarity", "evaluation", "datasets", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L92-L103
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
iterate_analogy_datasets
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_values in itertools.product(*parameters.values()): kwargs = dict(zip(parameters.keys(), key_values)) yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs)
python
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_values in itertools.product(*parameters.values()): kwargs = dict(zip(parameters.keys(), key_values)) yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs)
[ "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", ")", ")", "yield", "dataset_name", ",", "kwargs", ",", "nlp", ".", "data", ".", "create", "(", "dataset_name", ",", "*", "*", "kwargs", ")" ]
Generator over all analogy evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
[ "Generator", "over", "all", "analogy", "evaluation", "datasets", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L106-L117
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
get_similarity_task_tokens
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
python
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
[ "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.
[ "Returns", "a", "set", "of", "all", "tokens", "occurring", "the", "evaluation", "datasets", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L120-L126
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
get_analogy_task_tokens
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 tokens
python
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 tokens
[ "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.
[ "Returns", "a", "set", "of", "all", "tokens", "occuring", "the", "evaluation", "datasets", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L129-L136
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
evaluate_similarity
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_to_vec=token_embedding.idx_to_vec, similarity_function=similarity_function) evaluator.initialize(ctx=ctx) if not args.no_hybridize: evaluator.hybridize() # Evaluate all datasets for (dataset_name, dataset_kwargs, dataset) in iterate_similarity_datasets(args): initial_length = len(dataset) dataset_coded = [[ token_embedding.token_to_idx[d[0]], token_embedding.token_to_idx[d[1]], d[2] ] for d in dataset if d[0] in token_embedding.token_to_idx and d[1] in token_embedding.token_to_idx] num_dropped = initial_length - len(dataset_coded) # All words are unknown if not len(dataset_coded): correlation = 0 else: words1, words2, scores = zip(*dataset_coded) pred_similarity = evaluator( mx.nd.array(words1, ctx=ctx), mx.nd.array(words2, ctx=ctx)) sr = stats.spearmanr(pred_similarity.asnumpy(), np.array(scores)) correlation = sr.correlation logging.info( 'Spearman rank correlation on %s (%s pairs) %s with %s:\t%s', dataset.__class__.__name__, len(dataset_coded), str(dataset_kwargs), similarity_function, correlation) result = dict( task='similarity', dataset_name=dataset_name, dataset_kwargs=dataset_kwargs, similarity_function=similarity_function, spearmanr=correlation, num_dropped=num_dropped, global_step=global_step, ) log_similarity_result(logfile, result) results.append(result) return results
python
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_to_vec=token_embedding.idx_to_vec, similarity_function=similarity_function) evaluator.initialize(ctx=ctx) if not args.no_hybridize: evaluator.hybridize() # Evaluate all datasets for (dataset_name, dataset_kwargs, dataset) in iterate_similarity_datasets(args): initial_length = len(dataset) dataset_coded = [[ token_embedding.token_to_idx[d[0]], token_embedding.token_to_idx[d[1]], d[2] ] for d in dataset if d[0] in token_embedding.token_to_idx and d[1] in token_embedding.token_to_idx] num_dropped = initial_length - len(dataset_coded) # All words are unknown if not len(dataset_coded): correlation = 0 else: words1, words2, scores = zip(*dataset_coded) pred_similarity = evaluator( mx.nd.array(words1, ctx=ctx), mx.nd.array(words2, ctx=ctx)) sr = stats.spearmanr(pred_similarity.asnumpy(), np.array(scores)) correlation = sr.correlation logging.info( 'Spearman rank correlation on %s (%s pairs) %s with %s:\t%s', dataset.__class__.__name__, len(dataset_coded), str(dataset_kwargs), similarity_function, correlation) result = dict( task='similarity', dataset_name=dataset_name, dataset_kwargs=dataset_kwargs, similarity_function=similarity_function, spearmanr=correlation, num_dropped=num_dropped, global_step=global_step, ) log_similarity_result(logfile, result) results.append(result) return results
[ "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_vec", "=", "token_embedding", ".", "idx_to_vec", ",", "similarity_function", "=", "similarity_function", ")", "evaluator", ".", "initialize", "(", "ctx", "=", "ctx", ")", "if", "not", "args", ".", "no_hybridize", ":", "evaluator", ".", "hybridize", "(", ")", "# Evaluate all datasets", "for", "(", "dataset_name", ",", "dataset_kwargs", ",", "dataset", ")", "in", "iterate_similarity_datasets", "(", "args", ")", ":", "initial_length", "=", "len", "(", "dataset", ")", "dataset_coded", "=", "[", "[", "token_embedding", ".", "token_to_idx", "[", "d", "[", "0", "]", "]", ",", "token_embedding", ".", "token_to_idx", "[", "d", "[", "1", "]", "]", ",", "d", "[", "2", "]", "]", "for", "d", "in", "dataset", "if", "d", "[", "0", "]", "in", "token_embedding", ".", "token_to_idx", "and", "d", "[", "1", "]", "in", "token_embedding", ".", "token_to_idx", "]", "num_dropped", "=", "initial_length", "-", "len", "(", "dataset_coded", ")", "# All words are unknown", "if", "not", "len", "(", "dataset_coded", ")", ":", "correlation", "=", "0", "else", ":", "words1", ",", "words2", ",", "scores", "=", "zip", "(", "*", "dataset_coded", ")", "pred_similarity", "=", "evaluator", "(", "mx", ".", "nd", ".", "array", "(", "words1", ",", "ctx", "=", "ctx", ")", ",", "mx", ".", "nd", ".", "array", "(", "words2", ",", "ctx", "=", "ctx", ")", ")", "sr", "=", "stats", ".", "spearmanr", "(", "pred_similarity", ".", "asnumpy", "(", ")", ",", "np", ".", "array", "(", "scores", ")", ")", "correlation", "=", "sr", ".", "correlation", "logging", ".", "info", "(", "'Spearman rank correlation on %s (%s pairs) %s with %s:\\t%s'", ",", "dataset", ".", "__class__", ".", "__name__", ",", "len", "(", "dataset_coded", ")", ",", "str", "(", "dataset_kwargs", ")", ",", "similarity_function", ",", "correlation", ")", "result", "=", "dict", "(", "task", "=", "'similarity'", ",", "dataset_name", "=", "dataset_name", ",", "dataset_kwargs", "=", "dataset_kwargs", ",", "similarity_function", "=", "similarity_function", ",", "spearmanr", "=", "correlation", ",", "num_dropped", "=", "num_dropped", ",", "global_step", "=", "global_step", ",", ")", "log_similarity_result", "(", "logfile", ",", "result", ")", "results", ".", "append", "(", "result", ")", "return", "results" ]
Evaluate on specified similarity datasets.
[ "Evaluate", "on", "specified", "similarity", "datasets", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L145-L197
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
evaluate_analogy
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_words = not args.analogy_dont_exclude_question_words for analogy_function in args.analogy_functions: evaluator = nlp.embedding.evaluation.WordEmbeddingAnalogy( idx_to_vec=token_embedding.idx_to_vec, exclude_question_words=exclude_question_words, analogy_function=analogy_function) evaluator.initialize(ctx=ctx) if not args.no_hybridize: evaluator.hybridize() for (dataset_name, dataset_kwargs, dataset) in iterate_analogy_datasets(args): initial_length = len(dataset) dataset_coded = [[ token_embedding.token_to_idx[d[0]], token_embedding.token_to_idx[d[1]], token_embedding.token_to_idx[d[2]], token_embedding.token_to_idx[d[3]] ] for d in dataset if d[0] in token_embedding.token_to_idx and d[1] in token_embedding.token_to_idx and d[2] in token_embedding.token_to_idx and d[3] in token_embedding.token_to_idx] num_dropped = initial_length - len(dataset_coded) dataset_coded_batched = mx.gluon.data.DataLoader( dataset_coded, batch_size=args.eval_batch_size) acc = mx.metric.Accuracy() for batch in dataset_coded_batched: batch = batch.as_in_context(ctx) words1, words2, words3, words4 = (batch[:, 0], batch[:, 1], batch[:, 2], batch[:, 3]) pred_idxs = evaluator(words1, words2, words3) acc.update(pred_idxs[:, 0], words4.astype(np.float32)) logging.info('Accuracy on %s (%s quadruples) %s with %s:\t%s', dataset.__class__.__name__, len(dataset_coded), str(dataset_kwargs), analogy_function, acc.get()[1]) result = dict( task='analogy', dataset_name=dataset_name, dataset_kwargs=dataset_kwargs, analogy_function=analogy_function, accuracy=acc.get()[1], num_dropped=num_dropped, global_step=global_step, ) log_analogy_result(logfile, result) results.append(result) return results
python
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_words = not args.analogy_dont_exclude_question_words for analogy_function in args.analogy_functions: evaluator = nlp.embedding.evaluation.WordEmbeddingAnalogy( idx_to_vec=token_embedding.idx_to_vec, exclude_question_words=exclude_question_words, analogy_function=analogy_function) evaluator.initialize(ctx=ctx) if not args.no_hybridize: evaluator.hybridize() for (dataset_name, dataset_kwargs, dataset) in iterate_analogy_datasets(args): initial_length = len(dataset) dataset_coded = [[ token_embedding.token_to_idx[d[0]], token_embedding.token_to_idx[d[1]], token_embedding.token_to_idx[d[2]], token_embedding.token_to_idx[d[3]] ] for d in dataset if d[0] in token_embedding.token_to_idx and d[1] in token_embedding.token_to_idx and d[2] in token_embedding.token_to_idx and d[3] in token_embedding.token_to_idx] num_dropped = initial_length - len(dataset_coded) dataset_coded_batched = mx.gluon.data.DataLoader( dataset_coded, batch_size=args.eval_batch_size) acc = mx.metric.Accuracy() for batch in dataset_coded_batched: batch = batch.as_in_context(ctx) words1, words2, words3, words4 = (batch[:, 0], batch[:, 1], batch[:, 2], batch[:, 3]) pred_idxs = evaluator(words1, words2, words3) acc.update(pred_idxs[:, 0], words4.astype(np.float32)) logging.info('Accuracy on %s (%s quadruples) %s with %s:\t%s', dataset.__class__.__name__, len(dataset_coded), str(dataset_kwargs), analogy_function, acc.get()[1]) result = dict( task='analogy', dataset_name=dataset_name, dataset_kwargs=dataset_kwargs, analogy_function=analogy_function, accuracy=acc.get()[1], num_dropped=num_dropped, global_step=global_step, ) log_analogy_result(logfile, result) results.append(result) return results
[ "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", ".", "WordEmbeddingAnalogy", "(", "idx_to_vec", "=", "token_embedding", ".", "idx_to_vec", ",", "exclude_question_words", "=", "exclude_question_words", ",", "analogy_function", "=", "analogy_function", ")", "evaluator", ".", "initialize", "(", "ctx", "=", "ctx", ")", "if", "not", "args", ".", "no_hybridize", ":", "evaluator", ".", "hybridize", "(", ")", "for", "(", "dataset_name", ",", "dataset_kwargs", ",", "dataset", ")", "in", "iterate_analogy_datasets", "(", "args", ")", ":", "initial_length", "=", "len", "(", "dataset", ")", "dataset_coded", "=", "[", "[", "token_embedding", ".", "token_to_idx", "[", "d", "[", "0", "]", "]", ",", "token_embedding", ".", "token_to_idx", "[", "d", "[", "1", "]", "]", ",", "token_embedding", ".", "token_to_idx", "[", "d", "[", "2", "]", "]", ",", "token_embedding", ".", "token_to_idx", "[", "d", "[", "3", "]", "]", "]", "for", "d", "in", "dataset", "if", "d", "[", "0", "]", "in", "token_embedding", ".", "token_to_idx", "and", "d", "[", "1", "]", "in", "token_embedding", ".", "token_to_idx", "and", "d", "[", "2", "]", "in", "token_embedding", ".", "token_to_idx", "and", "d", "[", "3", "]", "in", "token_embedding", ".", "token_to_idx", "]", "num_dropped", "=", "initial_length", "-", "len", "(", "dataset_coded", ")", "dataset_coded_batched", "=", "mx", ".", "gluon", ".", "data", ".", "DataLoader", "(", "dataset_coded", ",", "batch_size", "=", "args", ".", "eval_batch_size", ")", "acc", "=", "mx", ".", "metric", ".", "Accuracy", "(", ")", "for", "batch", "in", "dataset_coded_batched", ":", "batch", "=", "batch", ".", "as_in_context", "(", "ctx", ")", "words1", ",", "words2", ",", "words3", ",", "words4", "=", "(", "batch", "[", ":", ",", "0", "]", ",", "batch", "[", ":", ",", "1", "]", ",", "batch", "[", ":", ",", "2", "]", ",", "batch", "[", ":", ",", "3", "]", ")", "pred_idxs", "=", "evaluator", "(", "words1", ",", "words2", ",", "words3", ")", "acc", ".", "update", "(", "pred_idxs", "[", ":", ",", "0", "]", ",", "words4", ".", "astype", "(", "np", ".", "float32", ")", ")", "logging", ".", "info", "(", "'Accuracy on %s (%s quadruples) %s with %s:\\t%s'", ",", "dataset", ".", "__class__", ".", "__name__", ",", "len", "(", "dataset_coded", ")", ",", "str", "(", "dataset_kwargs", ")", ",", "analogy_function", ",", "acc", ".", "get", "(", ")", "[", "1", "]", ")", "result", "=", "dict", "(", "task", "=", "'analogy'", ",", "dataset_name", "=", "dataset_name", ",", "dataset_kwargs", "=", "dataset_kwargs", ",", "analogy_function", "=", "analogy_function", ",", "accuracy", "=", "acc", ".", "get", "(", ")", "[", "1", "]", ",", "num_dropped", "=", "num_dropped", ",", "global_step", "=", "global_step", ",", ")", "log_analogy_result", "(", "logfile", ",", "result", ")", "results", ".", "append", "(", "result", ")", "return", "results" ]
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.
[ "Evaluate", "on", "specified", "analogy", "datasets", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L200-L259
train
dmlc/gluon-nlp
scripts/word_embeddings/evaluation.py
log_similarity_result
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['task'], result['dataset_name'], json.dumps(result['dataset_kwargs']), result['similarity_function'], str(result['spearmanr']), str(result['num_dropped']), ])) f.write('\n')
python
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['task'], result['dataset_name'], json.dumps(result['dataset_kwargs']), result['similarity_function'], str(result['spearmanr']), str(result['num_dropped']), ])) f.write('\n')
[ "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'", "]", ",", "result", "[", "'dataset_name'", "]", ",", "json", ".", "dumps", "(", "result", "[", "'dataset_kwargs'", "]", ")", ",", "result", "[", "'similarity_function'", "]", ",", "str", "(", "result", "[", "'spearmanr'", "]", ")", ",", "str", "(", "result", "[", "'num_dropped'", "]", ")", ",", "]", ")", ")", "f", ".", "write", "(", "'\\n'", ")" ]
Log a similarity evaluation result dictionary as TSV to logfile.
[ "Log", "a", "similarity", "evaluation", "result", "dictionary", "as", "TSV", "to", "logfile", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L262-L280
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
get_model_loss
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, pretrained=pretrained, ctx=ctx) if not pretrained: model.initialize(init=mx.init.Normal(0.02), ctx=ctx) model.cast(dtype) if ckpt_dir and start_step: param_path = os.path.join(ckpt_dir, '%07d.params'%start_step) model.load_parameters(param_path, ctx=ctx) logging.info('Loading step %d checkpoints from %s.', start_step, param_path) model.hybridize(static_alloc=True) # losses nsp_loss = mx.gluon.loss.SoftmaxCELoss() mlm_loss = mx.gluon.loss.SoftmaxCELoss() nsp_loss.hybridize(static_alloc=True) mlm_loss.hybridize(static_alloc=True) return model, nsp_loss, mlm_loss, vocabulary
python
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, pretrained=pretrained, ctx=ctx) if not pretrained: model.initialize(init=mx.init.Normal(0.02), ctx=ctx) model.cast(dtype) if ckpt_dir and start_step: param_path = os.path.join(ckpt_dir, '%07d.params'%start_step) model.load_parameters(param_path, ctx=ctx) logging.info('Loading step %d checkpoints from %s.', start_step, param_path) model.hybridize(static_alloc=True) # losses nsp_loss = mx.gluon.loss.SoftmaxCELoss() mlm_loss = mx.gluon.loss.SoftmaxCELoss() nsp_loss.hybridize(static_alloc=True) mlm_loss.hybridize(static_alloc=True) return model, nsp_loss, mlm_loss, vocabulary
[ "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", ",", "pretrained", "=", "pretrained", ",", "ctx", "=", "ctx", ")", "if", "not", "pretrained", ":", "model", ".", "initialize", "(", "init", "=", "mx", ".", "init", ".", "Normal", "(", "0.02", ")", ",", "ctx", "=", "ctx", ")", "model", ".", "cast", "(", "dtype", ")", "if", "ckpt_dir", "and", "start_step", ":", "param_path", "=", "os", ".", "path", ".", "join", "(", "ckpt_dir", ",", "'%07d.params'", "%", "start_step", ")", "model", ".", "load_parameters", "(", "param_path", ",", "ctx", "=", "ctx", ")", "logging", ".", "info", "(", "'Loading step %d checkpoints from %s.'", ",", "start_step", ",", "param_path", ")", "model", ".", "hybridize", "(", "static_alloc", "=", "True", ")", "# losses", "nsp_loss", "=", "mx", ".", "gluon", ".", "loss", ".", "SoftmaxCELoss", "(", ")", "mlm_loss", "=", "mx", ".", "gluon", ".", "loss", ".", "SoftmaxCELoss", "(", ")", "nsp_loss", ".", "hybridize", "(", "static_alloc", "=", "True", ")", "mlm_loss", ".", "hybridize", "(", "static_alloc", "=", "True", ")", "return", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocabulary" ]
Get model for pre-training.
[ "Get", "model", "for", "pre", "-", "training", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L36-L60
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
get_pretrain_dataset
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_files >= num_parts, \ 'Number of training files must be greater than the number of partitions' split_sampler = nlp.data.SplitSampler(num_files, num_parts=num_parts, part_index=part_idx) stream = nlp.data.SimpleDatasetStream(nlp.data.NumpyDataset, data, split_sampler) if prefetch: stream = nlp.data.PrefetchingStream(stream) def get_dataloader(dataset): """create data loader based on the dataset chunk""" lengths = dataset.get_field('valid_lengths') # A batch includes: input_id, masked_id, masked_position, masked_weight, # next_sentence_label, segment_id, valid_length batchify_fn = Tuple(Pad(), Pad(), Pad(), Pad(), Stack(), Pad(), Stack()) if use_avg_len: # sharded data loader sampler = nlp.data.FixedBucketSampler(lengths=lengths, # batch_size per shard batch_size=batch_size, num_buckets=num_buckets, shuffle=shuffle, use_average_length=True, num_shards=num_ctxes) dataloader = nlp.data.ShardedDataLoader(dataset, batch_sampler=sampler, batchify_fn=batchify_fn, num_workers=num_ctxes) else: sampler = nlp.data.FixedBucketSampler(lengths, batch_size=batch_size * num_ctxes, num_buckets=num_buckets, ratio=0, shuffle=shuffle) dataloader = DataLoader(dataset=dataset, batch_sampler=sampler, batchify_fn=batchify_fn, num_workers=1) logging.debug('Sampler created for a new dataset:\n%s', sampler.stats()) return dataloader stream = stream.transform(get_dataloader) return stream
python
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_files >= num_parts, \ 'Number of training files must be greater than the number of partitions' split_sampler = nlp.data.SplitSampler(num_files, num_parts=num_parts, part_index=part_idx) stream = nlp.data.SimpleDatasetStream(nlp.data.NumpyDataset, data, split_sampler) if prefetch: stream = nlp.data.PrefetchingStream(stream) def get_dataloader(dataset): """create data loader based on the dataset chunk""" lengths = dataset.get_field('valid_lengths') # A batch includes: input_id, masked_id, masked_position, masked_weight, # next_sentence_label, segment_id, valid_length batchify_fn = Tuple(Pad(), Pad(), Pad(), Pad(), Stack(), Pad(), Stack()) if use_avg_len: # sharded data loader sampler = nlp.data.FixedBucketSampler(lengths=lengths, # batch_size per shard batch_size=batch_size, num_buckets=num_buckets, shuffle=shuffle, use_average_length=True, num_shards=num_ctxes) dataloader = nlp.data.ShardedDataLoader(dataset, batch_sampler=sampler, batchify_fn=batchify_fn, num_workers=num_ctxes) else: sampler = nlp.data.FixedBucketSampler(lengths, batch_size=batch_size * num_ctxes, num_buckets=num_buckets, ratio=0, shuffle=shuffle) dataloader = DataLoader(dataset=dataset, batch_sampler=sampler, batchify_fn=batchify_fn, num_workers=1) logging.debug('Sampler created for a new dataset:\n%s', sampler.stats()) return dataloader stream = stream.transform(get_dataloader) return stream
[ "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", "num_files", ">=", "num_parts", ",", "'Number of training files must be greater than the number of partitions'", "split_sampler", "=", "nlp", ".", "data", ".", "SplitSampler", "(", "num_files", ",", "num_parts", "=", "num_parts", ",", "part_index", "=", "part_idx", ")", "stream", "=", "nlp", ".", "data", ".", "SimpleDatasetStream", "(", "nlp", ".", "data", ".", "NumpyDataset", ",", "data", ",", "split_sampler", ")", "if", "prefetch", ":", "stream", "=", "nlp", ".", "data", ".", "PrefetchingStream", "(", "stream", ")", "def", "get_dataloader", "(", "dataset", ")", ":", "\"\"\"create data loader based on the dataset chunk\"\"\"", "lengths", "=", "dataset", ".", "get_field", "(", "'valid_lengths'", ")", "# A batch includes: input_id, masked_id, masked_position, masked_weight,", "# next_sentence_label, segment_id, valid_length", "batchify_fn", "=", "Tuple", "(", "Pad", "(", ")", ",", "Pad", "(", ")", ",", "Pad", "(", ")", ",", "Pad", "(", ")", ",", "Stack", "(", ")", ",", "Pad", "(", ")", ",", "Stack", "(", ")", ")", "if", "use_avg_len", ":", "# sharded data loader", "sampler", "=", "nlp", ".", "data", ".", "FixedBucketSampler", "(", "lengths", "=", "lengths", ",", "# batch_size per shard", "batch_size", "=", "batch_size", ",", "num_buckets", "=", "num_buckets", ",", "shuffle", "=", "shuffle", ",", "use_average_length", "=", "True", ",", "num_shards", "=", "num_ctxes", ")", "dataloader", "=", "nlp", ".", "data", ".", "ShardedDataLoader", "(", "dataset", ",", "batch_sampler", "=", "sampler", ",", "batchify_fn", "=", "batchify_fn", ",", "num_workers", "=", "num_ctxes", ")", "else", ":", "sampler", "=", "nlp", ".", "data", ".", "FixedBucketSampler", "(", "lengths", ",", "batch_size", "=", "batch_size", "*", "num_ctxes", ",", "num_buckets", "=", "num_buckets", ",", "ratio", "=", "0", ",", "shuffle", "=", "shuffle", ")", "dataloader", "=", "DataLoader", "(", "dataset", "=", "dataset", ",", "batch_sampler", "=", "sampler", ",", "batchify_fn", "=", "batchify_fn", ",", "num_workers", "=", "1", ")", "logging", ".", "debug", "(", "'Sampler created for a new dataset:\\n%s'", ",", "sampler", ".", "stats", "(", ")", ")", "return", "dataloader", "stream", "=", "stream", ".", "transform", "(", "get_dataloader", ")", "return", "stream" ]
create dataset for pretraining.
[ "create", "dataset", "for", "pretraining", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L62-L107
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
get_dummy_dataloader
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_shape: logging.debug('Skip batch with shape %s', data_batch[0].shape) _, data_batch = next(data_iter) logging.debug('Found target dummy batch.') class DummyIter(): def __init__(self, batch): self._batch = batch def __iter__(self): while True: yield self._batch return DummyIter(data_batch)
python
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_shape: logging.debug('Skip batch with shape %s', data_batch[0].shape) _, data_batch = next(data_iter) logging.debug('Found target dummy batch.') class DummyIter(): def __init__(self, batch): self._batch = batch def __iter__(self): while True: yield self._batch return DummyIter(data_batch)
[ "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 batch with shape %s'", ",", "data_batch", "[", "0", "]", ".", "shape", ")", "_", ",", "data_batch", "=", "next", "(", "data_iter", ")", "logging", ".", "debug", "(", "'Found target dummy batch.'", ")", "class", "DummyIter", "(", ")", ":", "def", "__init__", "(", "self", ",", "batch", ")", ":", "self", ".", "_batch", "=", "batch", "def", "__iter__", "(", "self", ")", ":", "while", "True", ":", "yield", "self", ".", "_batch", "return", "DummyIter", "(", "data_batch", ")" ]
Return a dummy data loader which returns a fixed data batch of target shape
[ "Return", "a", "dummy", "data", "loader", "which", "returns", "a", "fixed", "data", "batch", "of", "target", "shape" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L109-L127
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
save_params
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_num, param_path, trainer_path) model.save_parameters(param_path) trainer.save_states(trainer_path)
python
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_num, param_path, trainer_path) model.save_parameters(param_path) trainer.save_states(trainer_path)
[ "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", ",", "param_path", ",", "trainer_path", ")", "model", ".", "save_parameters", "(", "param_path", ")", "trainer", ".", "save_states", "(", "trainer_path", ")" ]
Save the model parameter, marked by step_num.
[ "Save", "the", "model", "parameter", "marked", "by", "step_num", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L129-L136
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
log
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_mlm_loss / log_interval running_nsp_loss = running_nsp_loss / log_interval lr = trainer.learning_rate if trainer else 0 # pylint: disable=line-too-long logging.info('[step {}]\tmlm_loss={:.5f}\tmlm_acc={:.5f}\tnsp_loss={:.5f}\tnsp_acc={:.3f}\tthroughput={:.1f}K tks/s\tlr={:.7f} time={:.2f}, latency={:.1f} ms/batch' .format(step_num, running_mlm_loss.asscalar(), mlm_metric.get()[1] * 100, running_nsp_loss.asscalar(), nsp_metric.get()[1] * 100, throughput.asscalar(), lr, duration, duration*1000/log_interval))
python
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_mlm_loss / log_interval running_nsp_loss = running_nsp_loss / log_interval lr = trainer.learning_rate if trainer else 0 # pylint: disable=line-too-long logging.info('[step {}]\tmlm_loss={:.5f}\tmlm_acc={:.5f}\tnsp_loss={:.5f}\tnsp_acc={:.3f}\tthroughput={:.1f}K tks/s\tlr={:.7f} time={:.2f}, latency={:.1f} ms/batch' .format(step_num, running_mlm_loss.asscalar(), mlm_metric.get()[1] * 100, running_nsp_loss.asscalar(), nsp_metric.get()[1] * 100, throughput.asscalar(), lr, duration, duration*1000/log_interval))
[ "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_mlm_loss", "=", "running_mlm_loss", "/", "log_interval", "running_nsp_loss", "=", "running_nsp_loss", "/", "log_interval", "lr", "=", "trainer", ".", "learning_rate", "if", "trainer", "else", "0", "# pylint: disable=line-too-long", "logging", ".", "info", "(", "'[step {}]\\tmlm_loss={:.5f}\\tmlm_acc={:.5f}\\tnsp_loss={:.5f}\\tnsp_acc={:.3f}\\tthroughput={:.1f}K tks/s\\tlr={:.7f} time={:.2f}, latency={:.1f} ms/batch'", ".", "format", "(", "step_num", ",", "running_mlm_loss", ".", "asscalar", "(", ")", ",", "mlm_metric", ".", "get", "(", ")", "[", "1", "]", "*", "100", ",", "running_nsp_loss", ".", "asscalar", "(", ")", ",", "nsp_metric", ".", "get", "(", ")", "[", "1", "]", "*", "100", ",", "throughput", ".", "asscalar", "(", ")", ",", "lr", ",", "duration", ",", "duration", "*", "1000", "/", "log_interval", ")", ")" ]
Log training progress.
[ "Log", "training", "progress", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L138-L150
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
split_and_load
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)
python
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)
[ "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
[ "split", "and", "load", "arrays", "to", "a", "list", "of", "contexts" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L153-L158
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
forward
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) masked_id = masked_id.reshape(-1) valid_length_typed = valid_length.astype(dtype, copy=False) _, _, classified, decoded = model(input_id, segment_id, valid_length_typed, masked_position) decoded = decoded.reshape((-1, vocab_size)) ls1 = mlm_loss(decoded.astype('float32', copy=False), masked_id, masked_weight.reshape((-1, 1))) ls2 = nsp_loss(classified.astype('float32', copy=False), next_sentence_label) ls1 = ls1.sum() / num_masks ls2 = ls2.mean() ls = ls1 + ls2 return ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length.astype('float32', copy=False)
python
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) masked_id = masked_id.reshape(-1) valid_length_typed = valid_length.astype(dtype, copy=False) _, _, classified, decoded = model(input_id, segment_id, valid_length_typed, masked_position) decoded = decoded.reshape((-1, vocab_size)) ls1 = mlm_loss(decoded.astype('float32', copy=False), masked_id, masked_weight.reshape((-1, 1))) ls2 = nsp_loss(classified.astype('float32', copy=False), next_sentence_label) ls1 = ls1.sum() / num_masks ls2 = ls2.mean() ls = ls1 + ls2 return ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length.astype('float32', copy=False)
[ "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", ")", "masked_id", "=", "masked_id", ".", "reshape", "(", "-", "1", ")", "valid_length_typed", "=", "valid_length", ".", "astype", "(", "dtype", ",", "copy", "=", "False", ")", "_", ",", "_", ",", "classified", ",", "decoded", "=", "model", "(", "input_id", ",", "segment_id", ",", "valid_length_typed", ",", "masked_position", ")", "decoded", "=", "decoded", ".", "reshape", "(", "(", "-", "1", ",", "vocab_size", ")", ")", "ls1", "=", "mlm_loss", "(", "decoded", ".", "astype", "(", "'float32'", ",", "copy", "=", "False", ")", ",", "masked_id", ",", "masked_weight", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ")", "ls2", "=", "nsp_loss", "(", "classified", ".", "astype", "(", "'float32'", ",", "copy", "=", "False", ")", ",", "next_sentence_label", ")", "ls1", "=", "ls1", ".", "sum", "(", ")", "/", "num_masks", "ls2", "=", "ls2", ".", "mean", "(", ")", "ls", "=", "ls1", "+", "ls2", "return", "ls", ",", "next_sentence_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", "ls2", ",", "valid_length", ".", "astype", "(", "'float32'", ",", "copy", "=", "False", ")" ]
forward computation for evaluation
[ "forward", "computation", "for", "evaluation" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L161-L179
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
evaluate
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 running_mlm_loss = running_nsp_loss = 0 total_mlm_loss = total_nsp_loss = 0 running_num_tks = 0 for _, dataloader in enumerate(data_eval): for _, data_batch in enumerate(dataloader): step_num += 1 data_list = split_and_load(data_batch, ctx) loss_list = [] ns_label_list, ns_pred_list = [], [] mask_label_list, mask_pred_list, mask_weight_list = [], [], [] for data in data_list: out = forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype) (ls, next_sentence_label, classified, masked_id, decoded, masked_weight, ls1, ls2, valid_length) = out loss_list.append(ls) ns_label_list.append(next_sentence_label) ns_pred_list.append(classified) mask_label_list.append(masked_id) mask_pred_list.append(decoded) mask_weight_list.append(masked_weight) running_mlm_loss += ls1.as_in_context(mx.cpu()) running_nsp_loss += ls2.as_in_context(mx.cpu()) running_num_tks += valid_length.sum().as_in_context(mx.cpu()) nsp_metric.update(ns_label_list, ns_pred_list) mlm_metric.update(mask_label_list, mask_pred_list, mask_weight_list) # logging if (step_num + 1) % (log_interval) == 0: total_mlm_loss += running_mlm_loss total_nsp_loss += running_nsp_loss log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num, mlm_metric, nsp_metric, None, log_interval) begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 mlm_metric.reset_local() nsp_metric.reset_local() mx.nd.waitall() eval_end_time = time.time() total_mlm_loss /= step_num total_nsp_loss /= step_num logging.info('mlm_loss={:.3f}\tmlm_acc={:.1f}\tnsp_loss={:.3f}\tnsp_acc={:.1f}\t' .format(total_mlm_loss.asscalar(), mlm_metric.get_global()[1] * 100, total_nsp_loss.asscalar(), nsp_metric.get_global()[1] * 100)) logging.info('Eval cost={:.1f}s'.format(eval_end_time - eval_begin_time))
python
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 running_mlm_loss = running_nsp_loss = 0 total_mlm_loss = total_nsp_loss = 0 running_num_tks = 0 for _, dataloader in enumerate(data_eval): for _, data_batch in enumerate(dataloader): step_num += 1 data_list = split_and_load(data_batch, ctx) loss_list = [] ns_label_list, ns_pred_list = [], [] mask_label_list, mask_pred_list, mask_weight_list = [], [], [] for data in data_list: out = forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype) (ls, next_sentence_label, classified, masked_id, decoded, masked_weight, ls1, ls2, valid_length) = out loss_list.append(ls) ns_label_list.append(next_sentence_label) ns_pred_list.append(classified) mask_label_list.append(masked_id) mask_pred_list.append(decoded) mask_weight_list.append(masked_weight) running_mlm_loss += ls1.as_in_context(mx.cpu()) running_nsp_loss += ls2.as_in_context(mx.cpu()) running_num_tks += valid_length.sum().as_in_context(mx.cpu()) nsp_metric.update(ns_label_list, ns_pred_list) mlm_metric.update(mask_label_list, mask_pred_list, mask_weight_list) # logging if (step_num + 1) % (log_interval) == 0: total_mlm_loss += running_mlm_loss total_nsp_loss += running_nsp_loss log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num, mlm_metric, nsp_metric, None, log_interval) begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 mlm_metric.reset_local() nsp_metric.reset_local() mx.nd.waitall() eval_end_time = time.time() total_mlm_loss /= step_num total_nsp_loss /= step_num logging.info('mlm_loss={:.3f}\tmlm_acc={:.1f}\tnsp_loss={:.3f}\tnsp_acc={:.1f}\t' .format(total_mlm_loss.asscalar(), mlm_metric.get_global()[1] * 100, total_nsp_loss.asscalar(), nsp_metric.get_global()[1] * 100)) logging.info('Eval cost={:.1f}s'.format(eval_end_time - eval_begin_time))
[ "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", "(", ")", "step_num", "=", "0", "running_mlm_loss", "=", "running_nsp_loss", "=", "0", "total_mlm_loss", "=", "total_nsp_loss", "=", "0", "running_num_tks", "=", "0", "for", "_", ",", "dataloader", "in", "enumerate", "(", "data_eval", ")", ":", "for", "_", ",", "data_batch", "in", "enumerate", "(", "dataloader", ")", ":", "step_num", "+=", "1", "data_list", "=", "split_and_load", "(", "data_batch", ",", "ctx", ")", "loss_list", "=", "[", "]", "ns_label_list", ",", "ns_pred_list", "=", "[", "]", ",", "[", "]", "mask_label_list", ",", "mask_pred_list", ",", "mask_weight_list", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "data", "in", "data_list", ":", "out", "=", "forward", "(", "data", ",", "model", ",", "mlm_loss", ",", "nsp_loss", ",", "vocab_size", ",", "dtype", ")", "(", "ls", ",", "next_sentence_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", "ls2", ",", "valid_length", ")", "=", "out", "loss_list", ".", "append", "(", "ls", ")", "ns_label_list", ".", "append", "(", "next_sentence_label", ")", "ns_pred_list", ".", "append", "(", "classified", ")", "mask_label_list", ".", "append", "(", "masked_id", ")", "mask_pred_list", ".", "append", "(", "decoded", ")", "mask_weight_list", ".", "append", "(", "masked_weight", ")", "running_mlm_loss", "+=", "ls1", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "running_nsp_loss", "+=", "ls2", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "running_num_tks", "+=", "valid_length", ".", "sum", "(", ")", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "nsp_metric", ".", "update", "(", "ns_label_list", ",", "ns_pred_list", ")", "mlm_metric", ".", "update", "(", "mask_label_list", ",", "mask_pred_list", ",", "mask_weight_list", ")", "# logging", "if", "(", "step_num", "+", "1", ")", "%", "(", "log_interval", ")", "==", "0", ":", "total_mlm_loss", "+=", "running_mlm_loss", "total_nsp_loss", "+=", "running_nsp_loss", "log", "(", "begin_time", ",", "running_num_tks", ",", "running_mlm_loss", ",", "running_nsp_loss", ",", "step_num", ",", "mlm_metric", ",", "nsp_metric", ",", "None", ",", "log_interval", ")", "begin_time", "=", "time", ".", "time", "(", ")", "running_mlm_loss", "=", "running_nsp_loss", "=", "running_num_tks", "=", "0", "mlm_metric", ".", "reset_local", "(", ")", "nsp_metric", ".", "reset_local", "(", ")", "mx", ".", "nd", ".", "waitall", "(", ")", "eval_end_time", "=", "time", ".", "time", "(", ")", "total_mlm_loss", "/=", "step_num", "total_nsp_loss", "/=", "step_num", "logging", ".", "info", "(", "'mlm_loss={:.3f}\\tmlm_acc={:.1f}\\tnsp_loss={:.3f}\\tnsp_acc={:.1f}\\t'", ".", "format", "(", "total_mlm_loss", ".", "asscalar", "(", ")", ",", "mlm_metric", ".", "get_global", "(", ")", "[", "1", "]", "*", "100", ",", "total_nsp_loss", ".", "asscalar", "(", ")", ",", "nsp_metric", ".", "get_global", "(", ")", "[", "1", "]", "*", "100", ")", ")", "logging", ".", "info", "(", "'Eval cost={:.1f}s'", ".", "format", "(", "eval_end_time", "-", "eval_begin_time", ")", ")" ]
Evaluation function.
[ "Evaluation", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L182-L238
train
dmlc/gluon-nlp
scripts/bert/pretraining_utils.py
get_argparser
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='Number of buckets for variable length sequence sampling') parser.add_argument('--dtype', type=str, default='float32', help='data dtype') parser.add_argument('--batch_size', type=int, default=8, help='Batch size per GPU.') parser.add_argument('--accumulate', type=int, default=1, help='Number of batches for gradient accumulation. ' 'The effective batch size = batch_size * accumulate.') parser.add_argument('--use_avg_len', action='store_true', help='Use average length information for the bucket sampler. ' 'The batch size is approximately the number of tokens in the batch') parser.add_argument('--batch_size_eval', type=int, default=8, help='Batch size per GPU for evaluation.') parser.add_argument('--dataset_name', type=str, default='book_corpus_wiki_en_uncased', help='The dataset from which the vocabulary is created. Options include ' 'book_corpus_wiki_en_uncased, book_corpus_wiki_en_cased. ' 'Default is book_corpus_wiki_en_uncased') parser.add_argument('--pretrained', action='store_true', help='Load the pretrained model released by Google.') parser.add_argument('--model', type=str, default='bert_12_768_12', help='Model to run pre-training on. ' 'Options are bert_12_768_12, bert_24_1024_16') parser.add_argument('--data', type=str, default=None, help='Path to training data. Training is skipped if not set.') parser.add_argument('--data_eval', type=str, default=None, help='Path to evaluation data. Evaluation is skipped if not set.') parser.add_argument('--ckpt_dir', type=str, required=True, help='Path to checkpoint directory') parser.add_argument('--start_step', type=int, default=0, help='Start optimization step from the checkpoint.') parser.add_argument('--lr', type=float, default=1e-4, help='Learning rate') parser.add_argument('--warmup_ratio', type=float, default=0.1, help='ratio of warmup steps used in NOAM\'s stepsize schedule') parser.add_argument('--log_interval', type=int, default=10, help='Report interval') parser.add_argument('--ckpt_interval', type=int, default=250000, help='Checkpoint interval') parser.add_argument('--dummy_data_len', type=int, default=None, help='If provided, a data batch of target sequence length is ' 'used. For benchmarking purpuse only.') parser.add_argument('--seed', type=int, default=0, help='Random seed') parser.add_argument('--verbose', action='store_true', help='verbose logging') parser.add_argument('--profile', type=str, default=None, help='output profiling result to the target file') return parser
python
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='Number of buckets for variable length sequence sampling') parser.add_argument('--dtype', type=str, default='float32', help='data dtype') parser.add_argument('--batch_size', type=int, default=8, help='Batch size per GPU.') parser.add_argument('--accumulate', type=int, default=1, help='Number of batches for gradient accumulation. ' 'The effective batch size = batch_size * accumulate.') parser.add_argument('--use_avg_len', action='store_true', help='Use average length information for the bucket sampler. ' 'The batch size is approximately the number of tokens in the batch') parser.add_argument('--batch_size_eval', type=int, default=8, help='Batch size per GPU for evaluation.') parser.add_argument('--dataset_name', type=str, default='book_corpus_wiki_en_uncased', help='The dataset from which the vocabulary is created. Options include ' 'book_corpus_wiki_en_uncased, book_corpus_wiki_en_cased. ' 'Default is book_corpus_wiki_en_uncased') parser.add_argument('--pretrained', action='store_true', help='Load the pretrained model released by Google.') parser.add_argument('--model', type=str, default='bert_12_768_12', help='Model to run pre-training on. ' 'Options are bert_12_768_12, bert_24_1024_16') parser.add_argument('--data', type=str, default=None, help='Path to training data. Training is skipped if not set.') parser.add_argument('--data_eval', type=str, default=None, help='Path to evaluation data. Evaluation is skipped if not set.') parser.add_argument('--ckpt_dir', type=str, required=True, help='Path to checkpoint directory') parser.add_argument('--start_step', type=int, default=0, help='Start optimization step from the checkpoint.') parser.add_argument('--lr', type=float, default=1e-4, help='Learning rate') parser.add_argument('--warmup_ratio', type=float, default=0.1, help='ratio of warmup steps used in NOAM\'s stepsize schedule') parser.add_argument('--log_interval', type=int, default=10, help='Report interval') parser.add_argument('--ckpt_interval', type=int, default=250000, help='Checkpoint interval') parser.add_argument('--dummy_data_len', type=int, default=None, help='If provided, a data batch of target sequence length is ' 'used. For benchmarking purpuse only.') parser.add_argument('--seed', type=int, default=0, help='Random seed') parser.add_argument('--verbose', action='store_true', help='verbose logging') parser.add_argument('--profile', type=str, default=None, help='output profiling result to the target file') return parser
[ "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", ",", "help", "=", "'Number of buckets for variable length sequence sampling'", ")", "parser", ".", "add_argument", "(", "'--dtype'", ",", "type", "=", "str", ",", "default", "=", "'float32'", ",", "help", "=", "'data dtype'", ")", "parser", ".", "add_argument", "(", "'--batch_size'", ",", "type", "=", "int", ",", "default", "=", "8", ",", "help", "=", "'Batch size per GPU.'", ")", "parser", ".", "add_argument", "(", "'--accumulate'", ",", "type", "=", "int", ",", "default", "=", "1", ",", "help", "=", "'Number of batches for gradient accumulation. '", "'The effective batch size = batch_size * accumulate.'", ")", "parser", ".", "add_argument", "(", "'--use_avg_len'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Use average length information for the bucket sampler. '", "'The batch size is approximately the number of tokens in the batch'", ")", "parser", ".", "add_argument", "(", "'--batch_size_eval'", ",", "type", "=", "int", ",", "default", "=", "8", ",", "help", "=", "'Batch size per GPU for evaluation.'", ")", "parser", ".", "add_argument", "(", "'--dataset_name'", ",", "type", "=", "str", ",", "default", "=", "'book_corpus_wiki_en_uncased'", ",", "help", "=", "'The dataset from which the vocabulary is created. Options include '", "'book_corpus_wiki_en_uncased, book_corpus_wiki_en_cased. '", "'Default is book_corpus_wiki_en_uncased'", ")", "parser", ".", "add_argument", "(", "'--pretrained'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Load the pretrained model released by Google.'", ")", "parser", ".", "add_argument", "(", "'--model'", ",", "type", "=", "str", ",", "default", "=", "'bert_12_768_12'", ",", "help", "=", "'Model to run pre-training on. '", "'Options are bert_12_768_12, bert_24_1024_16'", ")", "parser", ".", "add_argument", "(", "'--data'", ",", "type", "=", "str", ",", "default", "=", "None", ",", "help", "=", "'Path to training data. Training is skipped if not set.'", ")", "parser", ".", "add_argument", "(", "'--data_eval'", ",", "type", "=", "str", ",", "default", "=", "None", ",", "help", "=", "'Path to evaluation data. Evaluation is skipped if not set.'", ")", "parser", ".", "add_argument", "(", "'--ckpt_dir'", ",", "type", "=", "str", ",", "required", "=", "True", ",", "help", "=", "'Path to checkpoint directory'", ")", "parser", ".", "add_argument", "(", "'--start_step'", ",", "type", "=", "int", ",", "default", "=", "0", ",", "help", "=", "'Start optimization step from the checkpoint.'", ")", "parser", ".", "add_argument", "(", "'--lr'", ",", "type", "=", "float", ",", "default", "=", "1e-4", ",", "help", "=", "'Learning rate'", ")", "parser", ".", "add_argument", "(", "'--warmup_ratio'", ",", "type", "=", "float", ",", "default", "=", "0.1", ",", "help", "=", "'ratio of warmup steps used in NOAM\\'s stepsize schedule'", ")", "parser", ".", "add_argument", "(", "'--log_interval'", ",", "type", "=", "int", ",", "default", "=", "10", ",", "help", "=", "'Report interval'", ")", "parser", ".", "add_argument", "(", "'--ckpt_interval'", ",", "type", "=", "int", ",", "default", "=", "250000", ",", "help", "=", "'Checkpoint interval'", ")", "parser", ".", "add_argument", "(", "'--dummy_data_len'", ",", "type", "=", "int", ",", "default", "=", "None", ",", "help", "=", "'If provided, a data batch of target sequence length is '", "'used. For benchmarking purpuse only.'", ")", "parser", ".", "add_argument", "(", "'--seed'", ",", "type", "=", "int", ",", "default", "=", "0", ",", "help", "=", "'Random seed'", ")", "parser", ".", "add_argument", "(", "'--verbose'", ",", "action", "=", "'store_true'", ",", "help", "=", "'verbose logging'", ")", "parser", ".", "add_argument", "(", "'--profile'", ",", "type", "=", "str", ",", "default", "=", "None", ",", "help", "=", "'output profiling result to the target file'", ")", "return", "parser" ]
Argument parser
[ "Argument", "parser" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L240-L285
train
dmlc/gluon-nlp
scripts/machine_translation/dataprocessor.py
_cache_dataset
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 in dataset]) tgt_data = np.concatenate([e[1] for e in dataset]) src_cumlen = np.cumsum([0]+[len(e[0]) for e in dataset]) tgt_cumlen = np.cumsum([0]+[len(e[1]) for e in dataset]) np.savez(os.path.join(_constants.CACHE_PATH, prefix + '.npz'), src_data=src_data, tgt_data=tgt_data, src_cumlen=src_cumlen, tgt_cumlen=tgt_cumlen)
python
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 in dataset]) tgt_data = np.concatenate([e[1] for e in dataset]) src_cumlen = np.cumsum([0]+[len(e[0]) for e in dataset]) tgt_cumlen = np.cumsum([0]+[len(e[1]) for e in dataset]) np.savez(os.path.join(_constants.CACHE_PATH, prefix + '.npz'), src_data=src_data, tgt_data=tgt_data, src_cumlen=src_cumlen, tgt_cumlen=tgt_cumlen)
[ "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", "]", "+", "[", "len", "(", "e", "[", "0", "]", ")", "for", "e", "in", "dataset", "]", ")", "tgt_cumlen", "=", "np", ".", "cumsum", "(", "[", "0", "]", "+", "[", "len", "(", "e", "[", "1", "]", ")", "for", "e", "in", "dataset", "]", ")", "np", ".", "savez", "(", "os", ".", "path", ".", "join", "(", "_constants", ".", "CACHE_PATH", ",", "prefix", "+", "'.npz'", ")", ",", "src_data", "=", "src_data", ",", "tgt_data", "=", "tgt_data", ",", "src_cumlen", "=", "src_cumlen", ",", "tgt_cumlen", "=", "tgt_cumlen", ")" ]
Cache the processed npy dataset the dataset into a npz Parameters ---------- dataset : SimpleDataset file_path : str
[ "Cache", "the", "processed", "npy", "dataset", "the", "dataset", "into", "a", "npz" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/dataprocessor.py#L33-L49
train
dmlc/gluon-nlp
scripts/machine_translation/dataprocessor.py
load_translation_data
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_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = nlp.data.IWSLT2015('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = nlp.data.IWSLT2015('val', src_lang=src_lang, tgt_lang=tgt_lang) data_test = nlp.data.IWSLT2015('test', src_lang=src_lang, tgt_lang=tgt_lang) elif dataset == 'WMT2016BPE': common_prefix = 'WMT2016BPE_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = nlp.data.WMT2016BPE('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = nlp.data.WMT2016BPE('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) data_test = nlp.data.WMT2016BPE('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang) elif dataset == 'WMT2014BPE': common_prefix = 'WMT2014BPE_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = nlp.data.WMT2014BPE('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = nlp.data.WMT2014BPE('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) data_test = nlp.data.WMT2014BPE('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang, full=args.full) elif dataset == 'TOY': common_prefix = 'TOY_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = _dataset.TOY('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = _dataset.TOY('val', src_lang=src_lang, tgt_lang=tgt_lang) data_test = _dataset.TOY('test', src_lang=src_lang, tgt_lang=tgt_lang) else: raise NotImplementedError src_vocab, tgt_vocab = data_train.src_vocab, data_train.tgt_vocab data_train_processed = _load_cached_dataset(common_prefix + '_train') if not data_train_processed: data_train_processed = process_dataset(data_train, src_vocab, tgt_vocab, args.src_max_len, args.tgt_max_len) _cache_dataset(data_train_processed, common_prefix + '_train') data_val_processed = _load_cached_dataset(common_prefix + '_val') if not data_val_processed: data_val_processed = process_dataset(data_val, src_vocab, tgt_vocab) _cache_dataset(data_val_processed, common_prefix + '_val') if dataset == 'WMT2014BPE': filename = common_prefix + '_' + str(args.full) + '_test' else: filename = common_prefix + '_test' data_test_processed = _load_cached_dataset(filename) if not data_test_processed: data_test_processed = process_dataset(data_test, src_vocab, tgt_vocab) _cache_dataset(data_test_processed, filename) if bleu == 'tweaked': fetch_tgt_sentence = lambda src, tgt: tgt.split() val_tgt_sentences = list(data_val.transform(fetch_tgt_sentence)) test_tgt_sentences = list(data_test.transform(fetch_tgt_sentence)) elif bleu == '13a' or bleu == 'intl': fetch_tgt_sentence = lambda src, tgt: tgt if dataset == 'WMT2016BPE': val_text = nlp.data.WMT2016('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) test_text = nlp.data.WMT2016('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang) elif dataset == 'WMT2014BPE': val_text = nlp.data.WMT2014('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) test_text = nlp.data.WMT2014('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang, full=args.full) elif dataset == 'IWSLT2015' or dataset == 'TOY': val_text = data_val test_text = data_test else: raise NotImplementedError val_tgt_sentences = list(val_text.transform(fetch_tgt_sentence)) test_tgt_sentences = list(test_text.transform(fetch_tgt_sentence)) else: raise NotImplementedError return data_train_processed, data_val_processed, data_test_processed, \ val_tgt_sentences, test_tgt_sentences, src_vocab, tgt_vocab
python
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_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = nlp.data.IWSLT2015('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = nlp.data.IWSLT2015('val', src_lang=src_lang, tgt_lang=tgt_lang) data_test = nlp.data.IWSLT2015('test', src_lang=src_lang, tgt_lang=tgt_lang) elif dataset == 'WMT2016BPE': common_prefix = 'WMT2016BPE_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = nlp.data.WMT2016BPE('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = nlp.data.WMT2016BPE('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) data_test = nlp.data.WMT2016BPE('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang) elif dataset == 'WMT2014BPE': common_prefix = 'WMT2014BPE_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = nlp.data.WMT2014BPE('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = nlp.data.WMT2014BPE('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) data_test = nlp.data.WMT2014BPE('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang, full=args.full) elif dataset == 'TOY': common_prefix = 'TOY_{}_{}_{}_{}'.format(src_lang, tgt_lang, args.src_max_len, args.tgt_max_len) data_train = _dataset.TOY('train', src_lang=src_lang, tgt_lang=tgt_lang) data_val = _dataset.TOY('val', src_lang=src_lang, tgt_lang=tgt_lang) data_test = _dataset.TOY('test', src_lang=src_lang, tgt_lang=tgt_lang) else: raise NotImplementedError src_vocab, tgt_vocab = data_train.src_vocab, data_train.tgt_vocab data_train_processed = _load_cached_dataset(common_prefix + '_train') if not data_train_processed: data_train_processed = process_dataset(data_train, src_vocab, tgt_vocab, args.src_max_len, args.tgt_max_len) _cache_dataset(data_train_processed, common_prefix + '_train') data_val_processed = _load_cached_dataset(common_prefix + '_val') if not data_val_processed: data_val_processed = process_dataset(data_val, src_vocab, tgt_vocab) _cache_dataset(data_val_processed, common_prefix + '_val') if dataset == 'WMT2014BPE': filename = common_prefix + '_' + str(args.full) + '_test' else: filename = common_prefix + '_test' data_test_processed = _load_cached_dataset(filename) if not data_test_processed: data_test_processed = process_dataset(data_test, src_vocab, tgt_vocab) _cache_dataset(data_test_processed, filename) if bleu == 'tweaked': fetch_tgt_sentence = lambda src, tgt: tgt.split() val_tgt_sentences = list(data_val.transform(fetch_tgt_sentence)) test_tgt_sentences = list(data_test.transform(fetch_tgt_sentence)) elif bleu == '13a' or bleu == 'intl': fetch_tgt_sentence = lambda src, tgt: tgt if dataset == 'WMT2016BPE': val_text = nlp.data.WMT2016('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) test_text = nlp.data.WMT2016('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang) elif dataset == 'WMT2014BPE': val_text = nlp.data.WMT2014('newstest2013', src_lang=src_lang, tgt_lang=tgt_lang) test_text = nlp.data.WMT2014('newstest2014', src_lang=src_lang, tgt_lang=tgt_lang, full=args.full) elif dataset == 'IWSLT2015' or dataset == 'TOY': val_text = data_val test_text = data_test else: raise NotImplementedError val_tgt_sentences = list(val_text.transform(fetch_tgt_sentence)) test_tgt_sentences = list(test_text.transform(fetch_tgt_sentence)) else: raise NotImplementedError return data_train_processed, data_val_processed, data_test_processed, \ val_tgt_sentences, test_tgt_sentences, src_vocab, tgt_vocab
[ "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", ".", "src_max_len", ",", "args", ".", "tgt_max_len", ")", "data_train", "=", "nlp", ".", "data", ".", "IWSLT2015", "(", "'train'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_val", "=", "nlp", ".", "data", ".", "IWSLT2015", "(", "'val'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_test", "=", "nlp", ".", "data", ".", "IWSLT2015", "(", "'test'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "elif", "dataset", "==", "'WMT2016BPE'", ":", "common_prefix", "=", "'WMT2016BPE_{}_{}_{}_{}'", ".", "format", "(", "src_lang", ",", "tgt_lang", ",", "args", ".", "src_max_len", ",", "args", ".", "tgt_max_len", ")", "data_train", "=", "nlp", ".", "data", ".", "WMT2016BPE", "(", "'train'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_val", "=", "nlp", ".", "data", ".", "WMT2016BPE", "(", "'newstest2013'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_test", "=", "nlp", ".", "data", ".", "WMT2016BPE", "(", "'newstest2014'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "elif", "dataset", "==", "'WMT2014BPE'", ":", "common_prefix", "=", "'WMT2014BPE_{}_{}_{}_{}'", ".", "format", "(", "src_lang", ",", "tgt_lang", ",", "args", ".", "src_max_len", ",", "args", ".", "tgt_max_len", ")", "data_train", "=", "nlp", ".", "data", ".", "WMT2014BPE", "(", "'train'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_val", "=", "nlp", ".", "data", ".", "WMT2014BPE", "(", "'newstest2013'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_test", "=", "nlp", ".", "data", ".", "WMT2014BPE", "(", "'newstest2014'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ",", "full", "=", "args", ".", "full", ")", "elif", "dataset", "==", "'TOY'", ":", "common_prefix", "=", "'TOY_{}_{}_{}_{}'", ".", "format", "(", "src_lang", ",", "tgt_lang", ",", "args", ".", "src_max_len", ",", "args", ".", "tgt_max_len", ")", "data_train", "=", "_dataset", ".", "TOY", "(", "'train'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_val", "=", "_dataset", ".", "TOY", "(", "'val'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "data_test", "=", "_dataset", ".", "TOY", "(", "'test'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "else", ":", "raise", "NotImplementedError", "src_vocab", ",", "tgt_vocab", "=", "data_train", ".", "src_vocab", ",", "data_train", ".", "tgt_vocab", "data_train_processed", "=", "_load_cached_dataset", "(", "common_prefix", "+", "'_train'", ")", "if", "not", "data_train_processed", ":", "data_train_processed", "=", "process_dataset", "(", "data_train", ",", "src_vocab", ",", "tgt_vocab", ",", "args", ".", "src_max_len", ",", "args", ".", "tgt_max_len", ")", "_cache_dataset", "(", "data_train_processed", ",", "common_prefix", "+", "'_train'", ")", "data_val_processed", "=", "_load_cached_dataset", "(", "common_prefix", "+", "'_val'", ")", "if", "not", "data_val_processed", ":", "data_val_processed", "=", "process_dataset", "(", "data_val", ",", "src_vocab", ",", "tgt_vocab", ")", "_cache_dataset", "(", "data_val_processed", ",", "common_prefix", "+", "'_val'", ")", "if", "dataset", "==", "'WMT2014BPE'", ":", "filename", "=", "common_prefix", "+", "'_'", "+", "str", "(", "args", ".", "full", ")", "+", "'_test'", "else", ":", "filename", "=", "common_prefix", "+", "'_test'", "data_test_processed", "=", "_load_cached_dataset", "(", "filename", ")", "if", "not", "data_test_processed", ":", "data_test_processed", "=", "process_dataset", "(", "data_test", ",", "src_vocab", ",", "tgt_vocab", ")", "_cache_dataset", "(", "data_test_processed", ",", "filename", ")", "if", "bleu", "==", "'tweaked'", ":", "fetch_tgt_sentence", "=", "lambda", "src", ",", "tgt", ":", "tgt", ".", "split", "(", ")", "val_tgt_sentences", "=", "list", "(", "data_val", ".", "transform", "(", "fetch_tgt_sentence", ")", ")", "test_tgt_sentences", "=", "list", "(", "data_test", ".", "transform", "(", "fetch_tgt_sentence", ")", ")", "elif", "bleu", "==", "'13a'", "or", "bleu", "==", "'intl'", ":", "fetch_tgt_sentence", "=", "lambda", "src", ",", "tgt", ":", "tgt", "if", "dataset", "==", "'WMT2016BPE'", ":", "val_text", "=", "nlp", ".", "data", ".", "WMT2016", "(", "'newstest2013'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "test_text", "=", "nlp", ".", "data", ".", "WMT2016", "(", "'newstest2014'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "elif", "dataset", "==", "'WMT2014BPE'", ":", "val_text", "=", "nlp", ".", "data", ".", "WMT2014", "(", "'newstest2013'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ")", "test_text", "=", "nlp", ".", "data", ".", "WMT2014", "(", "'newstest2014'", ",", "src_lang", "=", "src_lang", ",", "tgt_lang", "=", "tgt_lang", ",", "full", "=", "args", ".", "full", ")", "elif", "dataset", "==", "'IWSLT2015'", "or", "dataset", "==", "'TOY'", ":", "val_text", "=", "data_val", "test_text", "=", "data_test", "else", ":", "raise", "NotImplementedError", "val_tgt_sentences", "=", "list", "(", "val_text", ".", "transform", "(", "fetch_tgt_sentence", ")", ")", "test_tgt_sentences", "=", "list", "(", "test_text", ".", "transform", "(", "fetch_tgt_sentence", ")", ")", "else", ":", "raise", "NotImplementedError", "return", "data_train_processed", ",", "data_val_processed", ",", "data_test_processed", ",", "val_tgt_sentences", ",", "test_tgt_sentences", ",", "src_vocab", ",", "tgt_vocab" ]
Load translation dataset Parameters ---------- dataset : str args : argparse result Returns -------
[ "Load", "translation", "dataset" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/dataprocessor.py#L117-L198
train
dmlc/gluon-nlp
scripts/machine_translation/dataprocessor.py
make_dataloader
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 = get_data_lengths(data_test) train_batchify_fn = btf.Tuple(btf.Pad(), btf.Pad(), btf.Stack(dtype='float32'), btf.Stack(dtype='float32')) test_batchify_fn = btf.Tuple(btf.Pad(), btf.Pad(), btf.Stack(dtype='float32'), btf.Stack(dtype='float32'), btf.Stack()) target_val_lengths = list(map(lambda x: x[-1], data_val_lengths)) target_test_lengths = list(map(lambda x: x[-1], data_test_lengths)) if args.bucket_scheme == 'constant': bucket_scheme = nlp.data.ConstWidthBucket() elif args.bucket_scheme == 'linear': bucket_scheme = nlp.data.LinearWidthBucket() elif args.bucket_scheme == 'exp': bucket_scheme = nlp.data.ExpWidthBucket(bucket_len_step=1.2) else: raise NotImplementedError train_batch_sampler = nlp.data.FixedBucketSampler(lengths=data_train_lengths, batch_size=args.batch_size, num_buckets=args.num_buckets, ratio=args.bucket_ratio, shuffle=True, use_average_length=use_average_length, num_shards=num_shards, bucket_scheme=bucket_scheme) logging.info('Train Batch Sampler:\n%s', train_batch_sampler.stats()) train_data_loader = nlp.data.ShardedDataLoader(data_train, batch_sampler=train_batch_sampler, batchify_fn=train_batchify_fn, num_workers=num_workers) val_batch_sampler = nlp.data.FixedBucketSampler(lengths=target_val_lengths, batch_size=args.test_batch_size, num_buckets=args.num_buckets, ratio=args.bucket_ratio, shuffle=False, use_average_length=use_average_length, bucket_scheme=bucket_scheme) logging.info('Valid Batch Sampler:\n%s', val_batch_sampler.stats()) val_data_loader = gluon.data.DataLoader(data_val, batch_sampler=val_batch_sampler, batchify_fn=test_batchify_fn, num_workers=num_workers) test_batch_sampler = nlp.data.FixedBucketSampler(lengths=target_test_lengths, batch_size=args.test_batch_size, num_buckets=args.num_buckets, ratio=args.bucket_ratio, shuffle=False, use_average_length=use_average_length, bucket_scheme=bucket_scheme) logging.info('Test Batch Sampler:\n%s', test_batch_sampler.stats()) test_data_loader = gluon.data.DataLoader(data_test, batch_sampler=test_batch_sampler, batchify_fn=test_batchify_fn, num_workers=num_workers) return train_data_loader, val_data_loader, test_data_loader
python
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 = get_data_lengths(data_test) train_batchify_fn = btf.Tuple(btf.Pad(), btf.Pad(), btf.Stack(dtype='float32'), btf.Stack(dtype='float32')) test_batchify_fn = btf.Tuple(btf.Pad(), btf.Pad(), btf.Stack(dtype='float32'), btf.Stack(dtype='float32'), btf.Stack()) target_val_lengths = list(map(lambda x: x[-1], data_val_lengths)) target_test_lengths = list(map(lambda x: x[-1], data_test_lengths)) if args.bucket_scheme == 'constant': bucket_scheme = nlp.data.ConstWidthBucket() elif args.bucket_scheme == 'linear': bucket_scheme = nlp.data.LinearWidthBucket() elif args.bucket_scheme == 'exp': bucket_scheme = nlp.data.ExpWidthBucket(bucket_len_step=1.2) else: raise NotImplementedError train_batch_sampler = nlp.data.FixedBucketSampler(lengths=data_train_lengths, batch_size=args.batch_size, num_buckets=args.num_buckets, ratio=args.bucket_ratio, shuffle=True, use_average_length=use_average_length, num_shards=num_shards, bucket_scheme=bucket_scheme) logging.info('Train Batch Sampler:\n%s', train_batch_sampler.stats()) train_data_loader = nlp.data.ShardedDataLoader(data_train, batch_sampler=train_batch_sampler, batchify_fn=train_batchify_fn, num_workers=num_workers) val_batch_sampler = nlp.data.FixedBucketSampler(lengths=target_val_lengths, batch_size=args.test_batch_size, num_buckets=args.num_buckets, ratio=args.bucket_ratio, shuffle=False, use_average_length=use_average_length, bucket_scheme=bucket_scheme) logging.info('Valid Batch Sampler:\n%s', val_batch_sampler.stats()) val_data_loader = gluon.data.DataLoader(data_val, batch_sampler=val_batch_sampler, batchify_fn=test_batchify_fn, num_workers=num_workers) test_batch_sampler = nlp.data.FixedBucketSampler(lengths=target_test_lengths, batch_size=args.test_batch_size, num_buckets=args.num_buckets, ratio=args.bucket_ratio, shuffle=False, use_average_length=use_average_length, bucket_scheme=bucket_scheme) logging.info('Test Batch Sampler:\n%s', test_batch_sampler.stats()) test_data_loader = gluon.data.DataLoader(data_test, batch_sampler=test_batch_sampler, batchify_fn=test_batchify_fn, num_workers=num_workers) return train_data_loader, val_data_loader, test_data_loader
[ "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_data_lengths", "(", "data_test", ")", "train_batchify_fn", "=", "btf", ".", "Tuple", "(", "btf", ".", "Pad", "(", ")", ",", "btf", ".", "Pad", "(", ")", ",", "btf", ".", "Stack", "(", "dtype", "=", "'float32'", ")", ",", "btf", ".", "Stack", "(", "dtype", "=", "'float32'", ")", ")", "test_batchify_fn", "=", "btf", ".", "Tuple", "(", "btf", ".", "Pad", "(", ")", ",", "btf", ".", "Pad", "(", ")", ",", "btf", ".", "Stack", "(", "dtype", "=", "'float32'", ")", ",", "btf", ".", "Stack", "(", "dtype", "=", "'float32'", ")", ",", "btf", ".", "Stack", "(", ")", ")", "target_val_lengths", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", "[", "-", "1", "]", ",", "data_val_lengths", ")", ")", "target_test_lengths", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", "[", "-", "1", "]", ",", "data_test_lengths", ")", ")", "if", "args", ".", "bucket_scheme", "==", "'constant'", ":", "bucket_scheme", "=", "nlp", ".", "data", ".", "ConstWidthBucket", "(", ")", "elif", "args", ".", "bucket_scheme", "==", "'linear'", ":", "bucket_scheme", "=", "nlp", ".", "data", ".", "LinearWidthBucket", "(", ")", "elif", "args", ".", "bucket_scheme", "==", "'exp'", ":", "bucket_scheme", "=", "nlp", ".", "data", ".", "ExpWidthBucket", "(", "bucket_len_step", "=", "1.2", ")", "else", ":", "raise", "NotImplementedError", "train_batch_sampler", "=", "nlp", ".", "data", ".", "FixedBucketSampler", "(", "lengths", "=", "data_train_lengths", ",", "batch_size", "=", "args", ".", "batch_size", ",", "num_buckets", "=", "args", ".", "num_buckets", ",", "ratio", "=", "args", ".", "bucket_ratio", ",", "shuffle", "=", "True", ",", "use_average_length", "=", "use_average_length", ",", "num_shards", "=", "num_shards", ",", "bucket_scheme", "=", "bucket_scheme", ")", "logging", ".", "info", "(", "'Train Batch Sampler:\\n%s'", ",", "train_batch_sampler", ".", "stats", "(", ")", ")", "train_data_loader", "=", "nlp", ".", "data", ".", "ShardedDataLoader", "(", "data_train", ",", "batch_sampler", "=", "train_batch_sampler", ",", "batchify_fn", "=", "train_batchify_fn", ",", "num_workers", "=", "num_workers", ")", "val_batch_sampler", "=", "nlp", ".", "data", ".", "FixedBucketSampler", "(", "lengths", "=", "target_val_lengths", ",", "batch_size", "=", "args", ".", "test_batch_size", ",", "num_buckets", "=", "args", ".", "num_buckets", ",", "ratio", "=", "args", ".", "bucket_ratio", ",", "shuffle", "=", "False", ",", "use_average_length", "=", "use_average_length", ",", "bucket_scheme", "=", "bucket_scheme", ")", "logging", ".", "info", "(", "'Valid Batch Sampler:\\n%s'", ",", "val_batch_sampler", ".", "stats", "(", ")", ")", "val_data_loader", "=", "gluon", ".", "data", ".", "DataLoader", "(", "data_val", ",", "batch_sampler", "=", "val_batch_sampler", ",", "batchify_fn", "=", "test_batchify_fn", ",", "num_workers", "=", "num_workers", ")", "test_batch_sampler", "=", "nlp", ".", "data", ".", "FixedBucketSampler", "(", "lengths", "=", "target_test_lengths", ",", "batch_size", "=", "args", ".", "test_batch_size", ",", "num_buckets", "=", "args", ".", "num_buckets", ",", "ratio", "=", "args", ".", "bucket_ratio", ",", "shuffle", "=", "False", ",", "use_average_length", "=", "use_average_length", ",", "bucket_scheme", "=", "bucket_scheme", ")", "logging", ".", "info", "(", "'Test Batch Sampler:\\n%s'", ",", "test_batch_sampler", ".", "stats", "(", ")", ")", "test_data_loader", "=", "gluon", ".", "data", ".", "DataLoader", "(", "data_test", ",", "batch_sampler", "=", "test_batch_sampler", ",", "batchify_fn", "=", "test_batchify_fn", ",", "num_workers", "=", "num_workers", ")", "return", "train_data_loader", ",", "val_data_loader", ",", "test_data_loader" ]
Create data loaders for training/validation/test.
[ "Create", "data", "loaders", "for", "training", "/", "validation", "/", "test", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/dataprocessor.py#L206-L265
train
dmlc/gluon-nlp
src/gluonnlp/data/stream.py
_Prefetcher.run
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 support # https://github.com/apache/incubator-mxnet/issues/4659 mx.random.seed(self.mx_seed) # Startup - Master waits for this try: stream_iter = iter(self.stream) self._errorq.put(None) except Exception as e: # pylint: disable=broad-except tb = traceback.format_exc() self._errorq.put((e, tb)) # Async work while True: try: # Check control queue c = self._controlq.get(False) if c is None: break else: raise RuntimeError('Got unexpected control code {}'.format(repr(c))) except queue.Empty: pass except RuntimeError as e: tb = traceback.format_exc() self._errorq.put((e, tb)) self._dataq.put(None) try: data = next(stream_iter) error = None except Exception as e: # pylint: disable=broad-except tb = traceback.format_exc() error = (e, tb) data = None finally: self._errorq.put(error) self._dataq.put(data)
python
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 support # https://github.com/apache/incubator-mxnet/issues/4659 mx.random.seed(self.mx_seed) # Startup - Master waits for this try: stream_iter = iter(self.stream) self._errorq.put(None) except Exception as e: # pylint: disable=broad-except tb = traceback.format_exc() self._errorq.put((e, tb)) # Async work while True: try: # Check control queue c = self._controlq.get(False) if c is None: break else: raise RuntimeError('Got unexpected control code {}'.format(repr(c))) except queue.Empty: pass except RuntimeError as e: tb = traceback.format_exc() self._errorq.put((e, tb)) self._dataq.put(None) try: data = next(stream_iter) error = None except Exception as e: # pylint: disable=broad-except tb = traceback.format_exc() error = (e, tb) data = None finally: self._errorq.put(error) self._dataq.put(data)
[ "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", "# https://github.com/apache/incubator-mxnet/issues/4659", "mx", ".", "random", ".", "seed", "(", "self", ".", "mx_seed", ")", "# Startup - Master waits for this", "try", ":", "stream_iter", "=", "iter", "(", "self", ".", "stream", ")", "self", ".", "_errorq", ".", "put", "(", "None", ")", "except", "Exception", "as", "e", ":", "# pylint: disable=broad-except", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "_errorq", ".", "put", "(", "(", "e", ",", "tb", ")", ")", "# Async work", "while", "True", ":", "try", ":", "# Check control queue", "c", "=", "self", ".", "_controlq", ".", "get", "(", "False", ")", "if", "c", "is", "None", ":", "break", "else", ":", "raise", "RuntimeError", "(", "'Got unexpected control code {}'", ".", "format", "(", "repr", "(", "c", ")", ")", ")", "except", "queue", ".", "Empty", ":", "pass", "except", "RuntimeError", "as", "e", ":", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "_errorq", ".", "put", "(", "(", "e", ",", "tb", ")", ")", "self", ".", "_dataq", ".", "put", "(", "None", ")", "try", ":", "data", "=", "next", "(", "stream_iter", ")", "error", "=", "None", "except", "Exception", "as", "e", ":", "# pylint: disable=broad-except", "tb", "=", "traceback", ".", "format_exc", "(", ")", "error", "=", "(", "e", ",", "tb", ")", "data", "=", "None", "finally", ":", "self", ".", "_errorq", ".", "put", "(", "error", ")", "self", ".", "_dataq", ".", "put", "(", "data", ")" ]
Method representing the process’s activity.
[ "Method", "representing", "the", "process’s", "activity", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/stream.py#L228-L270
train
dmlc/gluon-nlp
src/gluonnlp/model/block.py
RNNCellLayer.forward
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: states = self.cell.begin_state(batch_size, ctx=inputs.context) if isinstance(states, ndarray.NDArray): states = [states] for state, info in zip(states, self.cell.state_info(batch_size)): if state.shape != info['shape']: raise ValueError( 'Invalid recurrent state shape. Expecting %s, got %s.'%( str(info['shape']), str(state.shape))) states = sum(zip(*((j for j in i) for i in states)), ()) outputs, states = self.cell.unroll( inputs.shape[self._axis], inputs, states, layout=self._layout, merge_outputs=True) if skip_states: return outputs return outputs, states
python
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: states = self.cell.begin_state(batch_size, ctx=inputs.context) if isinstance(states, ndarray.NDArray): states = [states] for state, info in zip(states, self.cell.state_info(batch_size)): if state.shape != info['shape']: raise ValueError( 'Invalid recurrent state shape. Expecting %s, got %s.'%( str(info['shape']), str(state.shape))) states = sum(zip(*((j for j in i) for i in states)), ()) outputs, states = self.cell.unroll( inputs.shape[self._axis], inputs, states, layout=self._layout, merge_outputs=True) if skip_states: return outputs return outputs, states
[ "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", ")", "if", "isinstance", "(", "states", ",", "ndarray", ".", "NDArray", ")", ":", "states", "=", "[", "states", "]", "for", "state", ",", "info", "in", "zip", "(", "states", ",", "self", ".", "cell", ".", "state_info", "(", "batch_size", ")", ")", ":", "if", "state", ".", "shape", "!=", "info", "[", "'shape'", "]", ":", "raise", "ValueError", "(", "'Invalid recurrent state shape. Expecting %s, got %s.'", "%", "(", "str", "(", "info", "[", "'shape'", "]", ")", ",", "str", "(", "state", ".", "shape", ")", ")", ")", "states", "=", "sum", "(", "zip", "(", "*", "(", "(", "j", "for", "j", "in", "i", ")", "for", "i", "in", "states", ")", ")", ",", "(", ")", ")", "outputs", ",", "states", "=", "self", ".", "cell", ".", "unroll", "(", "inputs", ".", "shape", "[", "self", ".", "_axis", "]", ",", "inputs", ",", "states", ",", "layout", "=", "self", ".", "_layout", ",", "merge_outputs", "=", "True", ")", "if", "skip_states", ":", "return", "outputs", "return", "outputs", ",", "states" ]
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`.
[ "Defines", "the", "forward", "computation", ".", "Arguments", "can", "be", "either", ":", "py", ":", "class", ":", "NDArray", "or", ":", "py", ":", "class", ":", "Symbol", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/block.py#L48-L69
train
dmlc/gluon-nlp
src/gluonnlp/model/train/embedding.py
CSREmbeddingModel.hybrid_forward
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 embeddings
python
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 embeddings
[ "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. Parameters ---------- words : mx.nd.NDArray Array of token indices.
[ "Compute", "embedding", "of", "words", "in", "batch", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/embedding.py#L120-L131
train
dmlc/gluon-nlp
src/gluonnlp/model/train/embedding.py
FasttextEmbeddingModel.load_fasttext_format
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 the .bin model file. ctx : mx.Context, default mx.cpu() Context to initialize the weights on. kwargs : dict Keyword arguments are passed to the class initializer. """ 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_vectors(f, new_format, bucket, len(idx_to_token)) token_to_idx = {token: idx for idx, token in enumerate(idx_to_token)} if len(token_to_idx) != len(idx_to_token): # If multiple tokens with invalid encoding were collapsed in a # single token due to replacement of invalid bytes with Unicode # replacement character warnings.warn( 'There are duplicate tokens in the embedding file. ' 'This is likely due to decoding errors for some tokens, ' 'where invalid bytes were replaced by ' 'the Unicode replacement character. ' 'This affects {} tokens.'.format( len(idx_to_token) - len(token_to_idx))) for _ in range(len(token_to_idx), len(idx_to_token)): # Add pseudo tokens to make sure length is the same token_to_idx[object()] = -1 assert len(token_to_idx) == len(idx_to_token) subword_function = create_subword_function( 'NGramHashes', num_subwords=matrix.shape[0] - len(idx_to_token), ngrams=list(range(minn, maxn + 1)), special_tokens={'</s>'}) self = cls(token_to_idx, subword_function, output_dim=dim, **kwargs) self.initialize(ctx=ctx) self.weight.set_data(nd.array(matrix)) return self
python
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 the .bin model file. ctx : mx.Context, default mx.cpu() Context to initialize the weights on. kwargs : dict Keyword arguments are passed to the class initializer. """ 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_vectors(f, new_format, bucket, len(idx_to_token)) token_to_idx = {token: idx for idx, token in enumerate(idx_to_token)} if len(token_to_idx) != len(idx_to_token): # If multiple tokens with invalid encoding were collapsed in a # single token due to replacement of invalid bytes with Unicode # replacement character warnings.warn( 'There are duplicate tokens in the embedding file. ' 'This is likely due to decoding errors for some tokens, ' 'where invalid bytes were replaced by ' 'the Unicode replacement character. ' 'This affects {} tokens.'.format( len(idx_to_token) - len(token_to_idx))) for _ in range(len(token_to_idx), len(idx_to_token)): # Add pseudo tokens to make sure length is the same token_to_idx[object()] = -1 assert len(token_to_idx) == len(idx_to_token) subword_function = create_subword_function( 'NGramHashes', num_subwords=matrix.shape[0] - len(idx_to_token), ngrams=list(range(minn, maxn + 1)), special_tokens={'</s>'}) self = cls(token_to_idx, subword_function, output_dim=dim, **kwargs) self.initialize(ctx=ctx) self.weight.set_data(nd.array(matrix)) return self
[ "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_vectors", "(", "f", ",", "new_format", ",", "bucket", ",", "len", "(", "idx_to_token", ")", ")", "token_to_idx", "=", "{", "token", ":", "idx", "for", "idx", ",", "token", "in", "enumerate", "(", "idx_to_token", ")", "}", "if", "len", "(", "token_to_idx", ")", "!=", "len", "(", "idx_to_token", ")", ":", "# If multiple tokens with invalid encoding were collapsed in a", "# single token due to replacement of invalid bytes with Unicode", "# replacement character", "warnings", ".", "warn", "(", "'There are duplicate tokens in the embedding file. '", "'This is likely due to decoding errors for some tokens, '", "'where invalid bytes were replaced by '", "'the Unicode replacement character. '", "'This affects {} tokens.'", ".", "format", "(", "len", "(", "idx_to_token", ")", "-", "len", "(", "token_to_idx", ")", ")", ")", "for", "_", "in", "range", "(", "len", "(", "token_to_idx", ")", ",", "len", "(", "idx_to_token", ")", ")", ":", "# Add pseudo tokens to make sure length is the same", "token_to_idx", "[", "object", "(", ")", "]", "=", "-", "1", "assert", "len", "(", "token_to_idx", ")", "==", "len", "(", "idx_to_token", ")", "subword_function", "=", "create_subword_function", "(", "'NGramHashes'", ",", "num_subwords", "=", "matrix", ".", "shape", "[", "0", "]", "-", "len", "(", "idx_to_token", ")", ",", "ngrams", "=", "list", "(", "range", "(", "minn", ",", "maxn", "+", "1", ")", ")", ",", "special_tokens", "=", "{", "'</s>'", "}", ")", "self", "=", "cls", "(", "token_to_idx", ",", "subword_function", ",", "output_dim", "=", "dim", ",", "*", "*", "kwargs", ")", "self", ".", "initialize", "(", "ctx", "=", "ctx", ")", "self", ".", "weight", ".", "set_data", "(", "nd", ".", "array", "(", "matrix", ")", ")", "return", "self" ]
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() Context to initialize the weights on. kwargs : dict Keyword arguments are passed to the class initializer.
[ "Create", "an", "instance", "of", "the", "class", "and", "load", "weights", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/embedding.py#L232-L280
train
dmlc/gluon-nlp
scripts/natural_language_inference/utils.py
logging_config
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: logger.removeHandler(handler) logger.handlers = [] logger.propagate = False logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(filename)s:%(funcName)s: %(message)s') if logpath is not None: print('All Logs will be saved to {}'.format(logpath)) logfile = logging.FileHandler(logpath, mode='w') logfile.setLevel(level) logfile.setFormatter(formatter) logger.addHandler(logfile) if not no_console: # Initialze the console logging logconsole = logging.StreamHandler() logconsole.setLevel(console_level) logconsole.setFormatter(formatter) logger.addHandler(logconsole)
python
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: logger.removeHandler(handler) logger.handlers = [] logger.propagate = False logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(filename)s:%(funcName)s: %(message)s') if logpath is not None: print('All Logs will be saved to {}'.format(logpath)) logfile = logging.FileHandler(logpath, mode='w') logfile.setLevel(level) logfile.setFormatter(formatter) logger.addHandler(logfile) if not no_console: # Initialze the console logging logconsole = logging.StreamHandler() logconsole.setLevel(console_level) logconsole.setFormatter(formatter) logger.addHandler(logconsole)
[ "def", "logging_config", "(", "logpath", "=", "None", ",", "level", "=", "logging", ".", "DEBUG", ",", "console_level", "=", "logging", ".", "INFO", ",", "no_console", "=", "False", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'nli'", ")", "# Remove all the current handlers", "for", "handler", "in", "logger", ".", "handlers", ":", "logger", ".", "removeHandler", "(", "handler", ")", "logger", ".", "handlers", "=", "[", "]", "logger", ".", "propagate", "=", "False", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(filename)s:%(funcName)s: %(message)s'", ")", "if", "logpath", "is", "not", "None", ":", "print", "(", "'All Logs will be saved to {}'", ".", "format", "(", "logpath", ")", ")", "logfile", "=", "logging", ".", "FileHandler", "(", "logpath", ",", "mode", "=", "'w'", ")", "logfile", ".", "setLevel", "(", "level", ")", "logfile", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "logfile", ")", "if", "not", "no_console", ":", "# Initialze the console logging", "logconsole", "=", "logging", ".", "StreamHandler", "(", ")", "logconsole", ".", "setLevel", "(", "console_level", ")", "logconsole", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "logconsole", ")" ]
Config the logging.
[ "Config", "the", "logging", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/utils.py#L27-L56
train
dmlc/gluon-nlp
scripts/word_embeddings/train_glove.py
parse_args
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( 'cooccurrences', type=str, help='Path to cooccurrences.npz containing a sparse (COO) ' 'representation of the co-occurrence matrix in numpy archive format. ' 'Output of ./cooccur') group.add_argument('vocab', type=str, help='Vocabulary indices. Output of vocab_count tool.') # Computation options group = parser.add_argument_group('Computation arguments') group.add_argument('--batch-size', type=int, default=512, help='Batch size for training.') group.add_argument('--epochs', type=int, default=50, help='Epoch limit') group.add_argument( '--gpu', type=int, nargs='+', help='Number (index) of GPU to run on, e.g. 0. ' 'If not specified, uses CPU.') group.add_argument('--no-hybridize', action='store_true', help='Disable hybridization of gluon HybridBlocks.') group.add_argument( '--no-static-alloc', action='store_true', help='Disable static memory allocation for HybridBlocks.') # Model group = parser.add_argument_group('Model arguments') group.add_argument('--emsize', type=int, default=300, help='Size of embedding vectors.') group.add_argument('--x-max', type=int, default=100) group.add_argument('--alpha', type=float, default=0.75) # Optimization options group = parser.add_argument_group('Optimization arguments') group.add_argument('--adagrad-eps', type=float, default=1, help='Initial AdaGrad state value.') group.add_argument('--lr', type=float, default=0.1, help='Learning rate') group.add_argument('--seed', type=int, default=1, help='Random seed') group.add_argument('--dropout', type=float, default=0.15) # Logging group = parser.add_argument_group('Logging arguments') group.add_argument('--logdir', type=str, default='logs', help='Directory to store logs.') group.add_argument('--log-interval', type=int, default=100) group.add_argument( '--eval-interval', type=int, help='Evaluate every --eval-interval iterations ' 'in addition to at the end of every epoch.') group.add_argument('--no-eval-analogy', action='store_true', help='Don\'t evaluate on the analogy task.') # Evaluation options evaluation.add_parameters(parser) args = parser.parse_args() evaluation.validate_args(args) random.seed(args.seed) mx.random.seed(args.seed) np.random.seed(args.seed) return args
python
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( 'cooccurrences', type=str, help='Path to cooccurrences.npz containing a sparse (COO) ' 'representation of the co-occurrence matrix in numpy archive format. ' 'Output of ./cooccur') group.add_argument('vocab', type=str, help='Vocabulary indices. Output of vocab_count tool.') # Computation options group = parser.add_argument_group('Computation arguments') group.add_argument('--batch-size', type=int, default=512, help='Batch size for training.') group.add_argument('--epochs', type=int, default=50, help='Epoch limit') group.add_argument( '--gpu', type=int, nargs='+', help='Number (index) of GPU to run on, e.g. 0. ' 'If not specified, uses CPU.') group.add_argument('--no-hybridize', action='store_true', help='Disable hybridization of gluon HybridBlocks.') group.add_argument( '--no-static-alloc', action='store_true', help='Disable static memory allocation for HybridBlocks.') # Model group = parser.add_argument_group('Model arguments') group.add_argument('--emsize', type=int, default=300, help='Size of embedding vectors.') group.add_argument('--x-max', type=int, default=100) group.add_argument('--alpha', type=float, default=0.75) # Optimization options group = parser.add_argument_group('Optimization arguments') group.add_argument('--adagrad-eps', type=float, default=1, help='Initial AdaGrad state value.') group.add_argument('--lr', type=float, default=0.1, help='Learning rate') group.add_argument('--seed', type=int, default=1, help='Random seed') group.add_argument('--dropout', type=float, default=0.15) # Logging group = parser.add_argument_group('Logging arguments') group.add_argument('--logdir', type=str, default='logs', help='Directory to store logs.') group.add_argument('--log-interval', type=int, default=100) group.add_argument( '--eval-interval', type=int, help='Evaluate every --eval-interval iterations ' 'in addition to at the end of every epoch.') group.add_argument('--no-eval-analogy', action='store_true', help='Don\'t evaluate on the analogy task.') # Evaluation options evaluation.add_parameters(parser) args = parser.parse_args() evaluation.validate_args(args) random.seed(args.seed) mx.random.seed(args.seed) np.random.seed(args.seed) return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'GloVe with GluonNLP'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "# Data options", "group", "=", "parser", ".", "add_argument_group", "(", "'Data arguments'", ")", "group", ".", "add_argument", "(", "'cooccurrences'", ",", "type", "=", "str", ",", "help", "=", "'Path to cooccurrences.npz containing a sparse (COO) '", "'representation of the co-occurrence matrix in numpy archive format. '", "'Output of ./cooccur'", ")", "group", ".", "add_argument", "(", "'vocab'", ",", "type", "=", "str", ",", "help", "=", "'Vocabulary indices. Output of vocab_count tool.'", ")", "# Computation options", "group", "=", "parser", ".", "add_argument_group", "(", "'Computation arguments'", ")", "group", ".", "add_argument", "(", "'--batch-size'", ",", "type", "=", "int", ",", "default", "=", "512", ",", "help", "=", "'Batch size for training.'", ")", "group", ".", "add_argument", "(", "'--epochs'", ",", "type", "=", "int", ",", "default", "=", "50", ",", "help", "=", "'Epoch limit'", ")", "group", ".", "add_argument", "(", "'--gpu'", ",", "type", "=", "int", ",", "nargs", "=", "'+'", ",", "help", "=", "'Number (index) of GPU to run on, e.g. 0. '", "'If not specified, uses CPU.'", ")", "group", ".", "add_argument", "(", "'--no-hybridize'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Disable hybridization of gluon HybridBlocks.'", ")", "group", ".", "add_argument", "(", "'--no-static-alloc'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Disable static memory allocation for HybridBlocks.'", ")", "# Model", "group", "=", "parser", ".", "add_argument_group", "(", "'Model arguments'", ")", "group", ".", "add_argument", "(", "'--emsize'", ",", "type", "=", "int", ",", "default", "=", "300", ",", "help", "=", "'Size of embedding vectors.'", ")", "group", ".", "add_argument", "(", "'--x-max'", ",", "type", "=", "int", ",", "default", "=", "100", ")", "group", ".", "add_argument", "(", "'--alpha'", ",", "type", "=", "float", ",", "default", "=", "0.75", ")", "# Optimization options", "group", "=", "parser", ".", "add_argument_group", "(", "'Optimization arguments'", ")", "group", ".", "add_argument", "(", "'--adagrad-eps'", ",", "type", "=", "float", ",", "default", "=", "1", ",", "help", "=", "'Initial AdaGrad state value.'", ")", "group", ".", "add_argument", "(", "'--lr'", ",", "type", "=", "float", ",", "default", "=", "0.1", ",", "help", "=", "'Learning rate'", ")", "group", ".", "add_argument", "(", "'--seed'", ",", "type", "=", "int", ",", "default", "=", "1", ",", "help", "=", "'Random seed'", ")", "group", ".", "add_argument", "(", "'--dropout'", ",", "type", "=", "float", ",", "default", "=", "0.15", ")", "# Logging", "group", "=", "parser", ".", "add_argument_group", "(", "'Logging arguments'", ")", "group", ".", "add_argument", "(", "'--logdir'", ",", "type", "=", "str", ",", "default", "=", "'logs'", ",", "help", "=", "'Directory to store logs.'", ")", "group", ".", "add_argument", "(", "'--log-interval'", ",", "type", "=", "int", ",", "default", "=", "100", ")", "group", ".", "add_argument", "(", "'--eval-interval'", ",", "type", "=", "int", ",", "help", "=", "'Evaluate every --eval-interval iterations '", "'in addition to at the end of every epoch.'", ")", "group", ".", "add_argument", "(", "'--no-eval-analogy'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Don\\'t evaluate on the analogy task.'", ")", "# Evaluation options", "evaluation", ".", "add_parameters", "(", "parser", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "evaluation", ".", "validate_args", "(", "args", ")", "random", ".", "seed", "(", "args", ".", "seed", ")", "mx", ".", "random", ".", "seed", "(", "args", ".", "seed", ")", "np", ".", "random", ".", "seed", "(", "args", ".", "seed", ")", "return", "args" ]
Parse command line arguments.
[ "Parse", "command", "line", "arguments", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L59-L127
train
dmlc/gluon-nlp
scripts/word_embeddings/train_glove.py
get_train_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_token=None, bos_token=None, eos_token=None, min_freq=1) npz = np.load(args.cooccurrences) row, col, counts = npz['row'], npz['col'], npz['data'] rank_dtype = 'int32' if row.max() >= np.iinfo(np.int32).max: rank_dtype = 'int64' # MXNet has no support for uint32, so we must fall back to int64 logging.info('More words than could be counted using int32. ' 'Using int64 to represent word indices.') row = mx.nd.array(row, dtype=rank_dtype) col = mx.nd.array(col, dtype=rank_dtype) # row is always used as 'source' and col as 'context' word. Therefore # duplicate the entries. assert row.shape == col.shape row = mx.nd.concatenate([row, col]) col = mx.nd.concatenate([col, row[:len(row) // 2]]) counts = mx.nd.array(counts, dtype='float32') counts = mx.nd.concatenate([counts, counts]) return vocab, row, col, counts
python
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_token=None, bos_token=None, eos_token=None, min_freq=1) npz = np.load(args.cooccurrences) row, col, counts = npz['row'], npz['col'], npz['data'] rank_dtype = 'int32' if row.max() >= np.iinfo(np.int32).max: rank_dtype = 'int64' # MXNet has no support for uint32, so we must fall back to int64 logging.info('More words than could be counted using int32. ' 'Using int64 to represent word indices.') row = mx.nd.array(row, dtype=rank_dtype) col = mx.nd.array(col, dtype=rank_dtype) # row is always used as 'source' and col as 'context' word. Therefore # duplicate the entries. assert row.shape == col.shape row = mx.nd.concatenate([row, col]) col = mx.nd.concatenate([col, row[:len(row) // 2]]) counts = mx.nd.array(counts, dtype='float32') counts = mx.nd.concatenate([counts, counts]) return vocab, row, col, counts
[ "def", "get_train_data", "(", "args", ")", ":", "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_token", "=", "None", ",", "bos_token", "=", "None", ",", "eos_token", "=", "None", ",", "min_freq", "=", "1", ")", "npz", "=", "np", ".", "load", "(", "args", ".", "cooccurrences", ")", "row", ",", "col", ",", "counts", "=", "npz", "[", "'row'", "]", ",", "npz", "[", "'col'", "]", ",", "npz", "[", "'data'", "]", "rank_dtype", "=", "'int32'", "if", "row", ".", "max", "(", ")", ">=", "np", ".", "iinfo", "(", "np", ".", "int32", ")", ".", "max", ":", "rank_dtype", "=", "'int64'", "# MXNet has no support for uint32, so we must fall back to int64", "logging", ".", "info", "(", "'More words than could be counted using int32. '", "'Using int64 to represent word indices.'", ")", "row", "=", "mx", ".", "nd", ".", "array", "(", "row", ",", "dtype", "=", "rank_dtype", ")", "col", "=", "mx", ".", "nd", ".", "array", "(", "col", ",", "dtype", "=", "rank_dtype", ")", "# row is always used as 'source' and col as 'context' word. Therefore", "# duplicate the entries.", "assert", "row", ".", "shape", "==", "col", ".", "shape", "row", "=", "mx", ".", "nd", ".", "concatenate", "(", "[", "row", ",", "col", "]", ")", "col", "=", "mx", ".", "nd", ".", "concatenate", "(", "[", "col", ",", "row", "[", ":", "len", "(", "row", ")", "//", "2", "]", "]", ")", "counts", "=", "mx", ".", "nd", ".", "array", "(", "counts", ",", "dtype", "=", "'float32'", ")", "counts", "=", "mx", ".", "nd", ".", "concatenate", "(", "[", "counts", ",", "counts", "]", ")", "return", "vocab", ",", "row", ",", "col", ",", "counts" ]
Helper function to get training data.
[ "Helper", "function", "to", "get", "training", "data", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L130-L161
train
dmlc/gluon-nlp
scripts/word_embeddings/train_glove.py
train
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)) context = get_context(args) model.initialize(ctx=context) if not args.no_hybridize: model.hybridize(static_alloc=not args.no_static_alloc) optimizer_kwargs = dict(learning_rate=args.lr, eps=args.adagrad_eps) params = list(model.collect_params().values()) try: trainer = mx.gluon.Trainer(params, 'groupadagrad', optimizer_kwargs) except ValueError: logging.warning('MXNet <= v1.3 does not contain ' 'GroupAdaGrad support. Falling back to AdaGrad') trainer = mx.gluon.Trainer(params, 'adagrad', optimizer_kwargs) index_dtype = 'int32' if counts.shape[0] >= np.iinfo(np.int32).max: index_dtype = 'int64' logging.info('Co-occurrence matrix is large. ' 'Using int64 to represent sample indices.') indices = mx.nd.arange(counts.shape[0], dtype=index_dtype) for epoch in range(args.epochs): # Logging variables log_wc = 0 log_start_time = time.time() log_avg_loss = 0 mx.nd.shuffle(indices, indices) # inplace shuffle bs = args.batch_size num_batches = indices.shape[0] // bs for i in range(num_batches): batch_indices = indices[bs * i:bs * (i + 1)] ctx = context[i % len(context)] batch_row = row[batch_indices].as_in_context(ctx) batch_col = col[batch_indices].as_in_context(ctx) batch_counts = counts[batch_indices].as_in_context(ctx) with mx.autograd.record(): loss = model(batch_row, batch_col, batch_counts) loss.backward() if len(context) == 1 or (i + 1) % len(context) == 0: trainer.step(batch_size=1) # Logging log_wc += loss.shape[0] log_avg_loss += loss.mean().as_in_context(context[0]) if (i + 1) % args.log_interval == 0: # Forces waiting for computation by computing loss value log_avg_loss = log_avg_loss.asscalar() / args.log_interval wps = log_wc / (time.time() - log_start_time) logging.info('[Epoch {} Batch {}/{}] loss={:.4f}, ' 'throughput={:.2f}K wps, wc={:.2f}K'.format( epoch, i + 1, num_batches, log_avg_loss, wps / 1000, log_wc / 1000)) log_dict = dict( global_step=epoch * len(indices) + i * args.batch_size, epoch=epoch, batch=i + 1, loss=log_avg_loss, wps=wps / 1000) log(args, log_dict) log_start_time = time.time() log_avg_loss = 0 log_wc = 0 if args.eval_interval and (i + 1) % args.eval_interval == 0: with print_time('mx.nd.waitall()'): mx.nd.waitall() with print_time('evaluate'): evaluate(args, model, vocab, i + num_batches * epoch) # Evaluate with print_time('mx.nd.waitall()'): mx.nd.waitall() with print_time('evaluate'): evaluate(args, model, vocab, num_batches * args.epochs, eval_analogy=not args.no_eval_analogy) # Save params with print_time('save parameters'): model.save_parameters(os.path.join(args.logdir, 'glove.params'))
python
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)) context = get_context(args) model.initialize(ctx=context) if not args.no_hybridize: model.hybridize(static_alloc=not args.no_static_alloc) optimizer_kwargs = dict(learning_rate=args.lr, eps=args.adagrad_eps) params = list(model.collect_params().values()) try: trainer = mx.gluon.Trainer(params, 'groupadagrad', optimizer_kwargs) except ValueError: logging.warning('MXNet <= v1.3 does not contain ' 'GroupAdaGrad support. Falling back to AdaGrad') trainer = mx.gluon.Trainer(params, 'adagrad', optimizer_kwargs) index_dtype = 'int32' if counts.shape[0] >= np.iinfo(np.int32).max: index_dtype = 'int64' logging.info('Co-occurrence matrix is large. ' 'Using int64 to represent sample indices.') indices = mx.nd.arange(counts.shape[0], dtype=index_dtype) for epoch in range(args.epochs): # Logging variables log_wc = 0 log_start_time = time.time() log_avg_loss = 0 mx.nd.shuffle(indices, indices) # inplace shuffle bs = args.batch_size num_batches = indices.shape[0] // bs for i in range(num_batches): batch_indices = indices[bs * i:bs * (i + 1)] ctx = context[i % len(context)] batch_row = row[batch_indices].as_in_context(ctx) batch_col = col[batch_indices].as_in_context(ctx) batch_counts = counts[batch_indices].as_in_context(ctx) with mx.autograd.record(): loss = model(batch_row, batch_col, batch_counts) loss.backward() if len(context) == 1 or (i + 1) % len(context) == 0: trainer.step(batch_size=1) # Logging log_wc += loss.shape[0] log_avg_loss += loss.mean().as_in_context(context[0]) if (i + 1) % args.log_interval == 0: # Forces waiting for computation by computing loss value log_avg_loss = log_avg_loss.asscalar() / args.log_interval wps = log_wc / (time.time() - log_start_time) logging.info('[Epoch {} Batch {}/{}] loss={:.4f}, ' 'throughput={:.2f}K wps, wc={:.2f}K'.format( epoch, i + 1, num_batches, log_avg_loss, wps / 1000, log_wc / 1000)) log_dict = dict( global_step=epoch * len(indices) + i * args.batch_size, epoch=epoch, batch=i + 1, loss=log_avg_loss, wps=wps / 1000) log(args, log_dict) log_start_time = time.time() log_avg_loss = 0 log_wc = 0 if args.eval_interval and (i + 1) % args.eval_interval == 0: with print_time('mx.nd.waitall()'): mx.nd.waitall() with print_time('evaluate'): evaluate(args, model, vocab, i + num_batches * epoch) # Evaluate with print_time('mx.nd.waitall()'): mx.nd.waitall() with print_time('evaluate'): evaluate(args, model, vocab, num_batches * args.epochs, eval_analogy=not args.no_eval_analogy) # Save params with print_time('save parameters'): model.save_parameters(os.path.join(args.logdir, 'glove.params'))
[ "def", "train", "(", "args", ")", ":", "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", ")", ")", "context", "=", "get_context", "(", "args", ")", "model", ".", "initialize", "(", "ctx", "=", "context", ")", "if", "not", "args", ".", "no_hybridize", ":", "model", ".", "hybridize", "(", "static_alloc", "=", "not", "args", ".", "no_static_alloc", ")", "optimizer_kwargs", "=", "dict", "(", "learning_rate", "=", "args", ".", "lr", ",", "eps", "=", "args", ".", "adagrad_eps", ")", "params", "=", "list", "(", "model", ".", "collect_params", "(", ")", ".", "values", "(", ")", ")", "try", ":", "trainer", "=", "mx", ".", "gluon", ".", "Trainer", "(", "params", ",", "'groupadagrad'", ",", "optimizer_kwargs", ")", "except", "ValueError", ":", "logging", ".", "warning", "(", "'MXNet <= v1.3 does not contain '", "'GroupAdaGrad support. Falling back to AdaGrad'", ")", "trainer", "=", "mx", ".", "gluon", ".", "Trainer", "(", "params", ",", "'adagrad'", ",", "optimizer_kwargs", ")", "index_dtype", "=", "'int32'", "if", "counts", ".", "shape", "[", "0", "]", ">=", "np", ".", "iinfo", "(", "np", ".", "int32", ")", ".", "max", ":", "index_dtype", "=", "'int64'", "logging", ".", "info", "(", "'Co-occurrence matrix is large. '", "'Using int64 to represent sample indices.'", ")", "indices", "=", "mx", ".", "nd", ".", "arange", "(", "counts", ".", "shape", "[", "0", "]", ",", "dtype", "=", "index_dtype", ")", "for", "epoch", "in", "range", "(", "args", ".", "epochs", ")", ":", "# Logging variables", "log_wc", "=", "0", "log_start_time", "=", "time", ".", "time", "(", ")", "log_avg_loss", "=", "0", "mx", ".", "nd", ".", "shuffle", "(", "indices", ",", "indices", ")", "# inplace shuffle", "bs", "=", "args", ".", "batch_size", "num_batches", "=", "indices", ".", "shape", "[", "0", "]", "//", "bs", "for", "i", "in", "range", "(", "num_batches", ")", ":", "batch_indices", "=", "indices", "[", "bs", "*", "i", ":", "bs", "*", "(", "i", "+", "1", ")", "]", "ctx", "=", "context", "[", "i", "%", "len", "(", "context", ")", "]", "batch_row", "=", "row", "[", "batch_indices", "]", ".", "as_in_context", "(", "ctx", ")", "batch_col", "=", "col", "[", "batch_indices", "]", ".", "as_in_context", "(", "ctx", ")", "batch_counts", "=", "counts", "[", "batch_indices", "]", ".", "as_in_context", "(", "ctx", ")", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "loss", "=", "model", "(", "batch_row", ",", "batch_col", ",", "batch_counts", ")", "loss", ".", "backward", "(", ")", "if", "len", "(", "context", ")", "==", "1", "or", "(", "i", "+", "1", ")", "%", "len", "(", "context", ")", "==", "0", ":", "trainer", ".", "step", "(", "batch_size", "=", "1", ")", "# Logging", "log_wc", "+=", "loss", ".", "shape", "[", "0", "]", "log_avg_loss", "+=", "loss", ".", "mean", "(", ")", ".", "as_in_context", "(", "context", "[", "0", "]", ")", "if", "(", "i", "+", "1", ")", "%", "args", ".", "log_interval", "==", "0", ":", "# Forces waiting for computation by computing loss value", "log_avg_loss", "=", "log_avg_loss", ".", "asscalar", "(", ")", "/", "args", ".", "log_interval", "wps", "=", "log_wc", "/", "(", "time", ".", "time", "(", ")", "-", "log_start_time", ")", "logging", ".", "info", "(", "'[Epoch {} Batch {}/{}] loss={:.4f}, '", "'throughput={:.2f}K wps, wc={:.2f}K'", ".", "format", "(", "epoch", ",", "i", "+", "1", ",", "num_batches", ",", "log_avg_loss", ",", "wps", "/", "1000", ",", "log_wc", "/", "1000", ")", ")", "log_dict", "=", "dict", "(", "global_step", "=", "epoch", "*", "len", "(", "indices", ")", "+", "i", "*", "args", ".", "batch_size", ",", "epoch", "=", "epoch", ",", "batch", "=", "i", "+", "1", ",", "loss", "=", "log_avg_loss", ",", "wps", "=", "wps", "/", "1000", ")", "log", "(", "args", ",", "log_dict", ")", "log_start_time", "=", "time", ".", "time", "(", ")", "log_avg_loss", "=", "0", "log_wc", "=", "0", "if", "args", ".", "eval_interval", "and", "(", "i", "+", "1", ")", "%", "args", ".", "eval_interval", "==", "0", ":", "with", "print_time", "(", "'mx.nd.waitall()'", ")", ":", "mx", ".", "nd", ".", "waitall", "(", ")", "with", "print_time", "(", "'evaluate'", ")", ":", "evaluate", "(", "args", ",", "model", ",", "vocab", ",", "i", "+", "num_batches", "*", "epoch", ")", "# Evaluate", "with", "print_time", "(", "'mx.nd.waitall()'", ")", ":", "mx", ".", "nd", ".", "waitall", "(", ")", "with", "print_time", "(", "'evaluate'", ")", ":", "evaluate", "(", "args", ",", "model", ",", "vocab", ",", "num_batches", "*", "args", ".", "epochs", ",", "eval_analogy", "=", "not", "args", ".", "no_eval_analogy", ")", "# Save params", "with", "print_time", "(", "'save parameters'", ")", ":", "model", ".", "save_parameters", "(", "os", ".", "path", ".", "join", "(", "args", ".", "logdir", ",", "'glove.params'", ")", ")" ]
Training helper.
[ "Training", "helper", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L273-L357
train
dmlc/gluon-nlp
scripts/word_embeddings/train_glove.py
log
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 = sorted(kwargs.keys()) header = '\t'.join((str(k) for k in log_created)) + '\n' with open(logfile, 'w') as f: f.write(header) # Log variables shouldn't change during training assert log_created == sorted(kwargs.keys()) with open(logfile, 'a') as f: f.write('\t'.join((str(kwargs[k]) for k in log_created)) + '\n')
python
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 = sorted(kwargs.keys()) header = '\t'.join((str(k) for k in log_created)) + '\n' with open(logfile, 'w') as f: f.write(header) # Log variables shouldn't change during training assert log_created == sorted(kwargs.keys()) with open(logfile, 'a') as f: f.write('\t'.join((str(kwargs[k]) for k in log_created)) + '\n')
[ "def", "log", "(", "args", ",", "kwargs", ")", ":", "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", "=", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", "header", "=", "'\\t'", ".", "join", "(", "(", "str", "(", "k", ")", "for", "k", "in", "log_created", ")", ")", "+", "'\\n'", "with", "open", "(", "logfile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "header", ")", "# Log variables shouldn't change during training", "assert", "log_created", "==", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", "with", "open", "(", "logfile", ",", "'a'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\t'", ".", "join", "(", "(", "str", "(", "kwargs", "[", "k", "]", ")", "for", "k", "in", "log_created", ")", ")", "+", "'\\n'", ")" ]
Log to a file.
[ "Log", "to", "a", "file", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L396-L416
train
dmlc/gluon-nlp
scripts/word_embeddings/train_glove.py
GloVe.hybrid_forward
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 Array of token indices for context words. Shape (batch_size, ). counts : mxnet.nd.NDArray or mxnet.sym.Symbol Their co-occurrence counts. Shape (batch_size, ). Returns ------- mxnet.nd.NDArray or mxnet.sym.Symbol Loss. Shape (batch_size, ). """ emb_in = self.source_embedding(row) emb_out = self.context_embedding(col) if self._dropout: emb_in = F.Dropout(emb_in, p=self._dropout) emb_out = F.Dropout(emb_out, p=self._dropout) bias_in = self.source_bias(row).squeeze() bias_out = self.context_bias(col).squeeze() dot = F.batch_dot(emb_in.expand_dims(1), emb_out.expand_dims(2)).squeeze() tmp = dot + bias_in + bias_out - F.log(counts).squeeze() weight = F.clip(((counts / self._x_max)**self._alpha), a_min=0, a_max=1).squeeze() loss = weight * F.square(tmp) return loss
python
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 Array of token indices for context words. Shape (batch_size, ). counts : mxnet.nd.NDArray or mxnet.sym.Symbol Their co-occurrence counts. Shape (batch_size, ). Returns ------- mxnet.nd.NDArray or mxnet.sym.Symbol Loss. Shape (batch_size, ). """ emb_in = self.source_embedding(row) emb_out = self.context_embedding(col) if self._dropout: emb_in = F.Dropout(emb_in, p=self._dropout) emb_out = F.Dropout(emb_out, p=self._dropout) bias_in = self.source_bias(row).squeeze() bias_out = self.context_bias(col).squeeze() dot = F.batch_dot(emb_in.expand_dims(1), emb_out.expand_dims(2)).squeeze() tmp = dot + bias_in + bias_out - F.log(counts).squeeze() weight = F.clip(((counts / self._x_max)**self._alpha), a_min=0, a_max=1).squeeze() loss = weight * F.square(tmp) return loss
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "row", ",", "col", ",", "counts", ")", ":", "emb_in", "=", "self", ".", "source_embedding", "(", "row", ")", "emb_out", "=", "self", ".", "context_embedding", "(", "col", ")", "if", "self", ".", "_dropout", ":", "emb_in", "=", "F", ".", "Dropout", "(", "emb_in", ",", "p", "=", "self", ".", "_dropout", ")", "emb_out", "=", "F", ".", "Dropout", "(", "emb_out", ",", "p", "=", "self", ".", "_dropout", ")", "bias_in", "=", "self", ".", "source_bias", "(", "row", ")", ".", "squeeze", "(", ")", "bias_out", "=", "self", ".", "context_bias", "(", "col", ")", ".", "squeeze", "(", ")", "dot", "=", "F", ".", "batch_dot", "(", "emb_in", ".", "expand_dims", "(", "1", ")", ",", "emb_out", ".", "expand_dims", "(", "2", ")", ")", ".", "squeeze", "(", ")", "tmp", "=", "dot", "+", "bias_in", "+", "bias_out", "-", "F", ".", "log", "(", "counts", ")", ".", "squeeze", "(", ")", "weight", "=", "F", ".", "clip", "(", "(", "(", "counts", "/", "self", ".", "_x_max", ")", "**", "self", ".", "_alpha", ")", ",", "a_min", "=", "0", ",", "a_max", "=", "1", ")", ".", "squeeze", "(", ")", "loss", "=", "weight", "*", "F", ".", "square", "(", "tmp", ")", "return", "loss" ]
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_size, ). counts : mxnet.nd.NDArray or mxnet.sym.Symbol Their co-occurrence counts. Shape (batch_size, ). Returns ------- mxnet.nd.NDArray or mxnet.sym.Symbol Loss. Shape (batch_size, ).
[ "Compute", "embedding", "of", "words", "in", "batch", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L201-L235
train
dmlc/gluon-nlp
src/gluonnlp/metric/masked_accuracy.py
MaskedAccuracy.update
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 `NDArray` Prediction values for samples. Each prediction value can either be the class index, or a vector of likelihoods for all classes. masks : list of `NDArray` or None, optional Masks for samples, with the same shape as `labels`. value of its element must be either 1 or 0. If None, all samples are considered valid. """ labels, preds = check_label_shapes(labels, preds, True) masks = [None] * len(labels) if masks is None else masks for label, pred_label, mask in zip(labels, preds, masks): if pred_label.shape != label.shape: # TODO(haibin) topk does not support fp16. Issue tracked at: # https://github.com/apache/incubator-mxnet/issues/14125 # topk is used because argmax is slow: # https://github.com/apache/incubator-mxnet/issues/11061 pred_label = ndarray.topk(pred_label.astype('float32', copy=False), k=1, ret_typ='indices', axis=self.axis) # flatten before checking shapes to avoid shape miss match pred_label = pred_label.astype('int32', copy=False).reshape((-1,)) label = label.astype('int32', copy=False).reshape((-1,)) check_label_shapes(label, pred_label) if mask is not None: mask = mask.astype('int32', copy=False).reshape((-1,)) check_label_shapes(label, mask) num_correct = ((pred_label == label) * mask).sum().asscalar() num_inst = mask.sum().asscalar() else: num_correct = (pred_label == label).sum().asscalar() num_inst = len(label) self.sum_metric += num_correct self.global_sum_metric += num_correct self.num_inst += num_inst self.global_num_inst += num_inst
python
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 `NDArray` Prediction values for samples. Each prediction value can either be the class index, or a vector of likelihoods for all classes. masks : list of `NDArray` or None, optional Masks for samples, with the same shape as `labels`. value of its element must be either 1 or 0. If None, all samples are considered valid. """ labels, preds = check_label_shapes(labels, preds, True) masks = [None] * len(labels) if masks is None else masks for label, pred_label, mask in zip(labels, preds, masks): if pred_label.shape != label.shape: # TODO(haibin) topk does not support fp16. Issue tracked at: # https://github.com/apache/incubator-mxnet/issues/14125 # topk is used because argmax is slow: # https://github.com/apache/incubator-mxnet/issues/11061 pred_label = ndarray.topk(pred_label.astype('float32', copy=False), k=1, ret_typ='indices', axis=self.axis) # flatten before checking shapes to avoid shape miss match pred_label = pred_label.astype('int32', copy=False).reshape((-1,)) label = label.astype('int32', copy=False).reshape((-1,)) check_label_shapes(label, pred_label) if mask is not None: mask = mask.astype('int32', copy=False).reshape((-1,)) check_label_shapes(label, mask) num_correct = ((pred_label == label) * mask).sum().asscalar() num_inst = mask.sum().asscalar() else: num_correct = (pred_label == label).sum().asscalar() num_inst = len(label) self.sum_metric += num_correct self.global_sum_metric += num_correct self.num_inst += num_inst self.global_num_inst += num_inst
[ "def", "update", "(", "self", ",", "labels", ",", "preds", ",", "masks", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "labels", ",", "preds", "=", "check_label_shapes", "(", "labels", ",", "preds", ",", "True", ")", "masks", "=", "[", "None", "]", "*", "len", "(", "labels", ")", "if", "masks", "is", "None", "else", "masks", "for", "label", ",", "pred_label", ",", "mask", "in", "zip", "(", "labels", ",", "preds", ",", "masks", ")", ":", "if", "pred_label", ".", "shape", "!=", "label", ".", "shape", ":", "# TODO(haibin) topk does not support fp16. Issue tracked at:", "# https://github.com/apache/incubator-mxnet/issues/14125", "# topk is used because argmax is slow:", "# https://github.com/apache/incubator-mxnet/issues/11061", "pred_label", "=", "ndarray", ".", "topk", "(", "pred_label", ".", "astype", "(", "'float32'", ",", "copy", "=", "False", ")", ",", "k", "=", "1", ",", "ret_typ", "=", "'indices'", ",", "axis", "=", "self", ".", "axis", ")", "# flatten before checking shapes to avoid shape miss match", "pred_label", "=", "pred_label", ".", "astype", "(", "'int32'", ",", "copy", "=", "False", ")", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "label", "=", "label", ".", "astype", "(", "'int32'", ",", "copy", "=", "False", ")", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "check_label_shapes", "(", "label", ",", "pred_label", ")", "if", "mask", "is", "not", "None", ":", "mask", "=", "mask", ".", "astype", "(", "'int32'", ",", "copy", "=", "False", ")", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "check_label_shapes", "(", "label", ",", "mask", ")", "num_correct", "=", "(", "(", "pred_label", "==", "label", ")", "*", "mask", ")", ".", "sum", "(", ")", ".", "asscalar", "(", ")", "num_inst", "=", "mask", ".", "sum", "(", ")", ".", "asscalar", "(", ")", "else", ":", "num_correct", "=", "(", "pred_label", "==", "label", ")", ".", "sum", "(", ")", ".", "asscalar", "(", ")", "num_inst", "=", "len", "(", "label", ")", "self", ".", "sum_metric", "+=", "num_correct", "self", ".", "global_sum_metric", "+=", "num_correct", "self", ".", "num_inst", "+=", "num_inst", "self", ".", "global_num_inst", "+=", "num_inst" ]
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 index, or a vector of likelihoods for all classes. masks : list of `NDArray` or None, optional Masks for samples, with the same shape as `labels`. value of its element must be either 1 or 0. If None, all samples are considered valid.
[ "Updates", "the", "internal", "evaluation", "result", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/metric/masked_accuracy.py#L232-L275
train
dmlc/gluon-nlp
scripts/natural_language_inference/decomposable_attention.py
NLIModel.hybrid_forward
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 ------- pred : NDArray Shape (batch_size, num_classes). num_classes == 3. """ feature1 = self.lin_proj(self.word_emb(sentence1)) feature2 = self.lin_proj(self.word_emb(sentence2)) if self.use_intra_attention: feature1 = F.concat(feature1, self.intra_attention(feature1), dim=-1) feature2 = F.concat(feature2, self.intra_attention(feature2), dim=-1) pred = self.model(feature1, feature2) return pred
python
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 ------- pred : NDArray Shape (batch_size, num_classes). num_classes == 3. """ feature1 = self.lin_proj(self.word_emb(sentence1)) feature2 = self.lin_proj(self.word_emb(sentence2)) if self.use_intra_attention: feature1 = F.concat(feature1, self.intra_attention(feature1), dim=-1) feature2 = F.concat(feature2, self.intra_attention(feature2), dim=-1) pred = self.model(feature1, feature2) return pred
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "sentence1", ",", "sentence2", ")", ":", "feature1", "=", "self", ".", "lin_proj", "(", "self", ".", "word_emb", "(", "sentence1", ")", ")", "feature2", "=", "self", ".", "lin_proj", "(", "self", ".", "word_emb", "(", "sentence2", ")", ")", "if", "self", ".", "use_intra_attention", ":", "feature1", "=", "F", ".", "concat", "(", "feature1", ",", "self", ".", "intra_attention", "(", "feature1", ")", ",", "dim", "=", "-", "1", ")", "feature2", "=", "F", ".", "concat", "(", "feature2", ",", "self", ".", "intra_attention", "(", "feature2", ")", ",", "dim", "=", "-", "1", ")", "pred", "=", "self", ".", "model", "(", "feature1", ",", "feature2", ")", "return", "pred" ]
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_classes == 3.
[ "Predict", "the", "relation", "of", "two", "sentences", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/decomposable_attention.py#L55-L78
train
dmlc/gluon-nlp
scripts/natural_language_inference/decomposable_attention.py
IntraSentenceAttention.hybrid_forward
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, length, hidden_size) """ tilde_a = self.intra_attn_emb(feature_a) e_matrix = F.batch_dot(tilde_a, tilde_a, transpose_b=True) alpha = F.batch_dot(e_matrix.softmax(), tilde_a) return alpha
python
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, length, hidden_size) """ tilde_a = self.intra_attn_emb(feature_a) e_matrix = F.batch_dot(tilde_a, tilde_a, transpose_b=True) alpha = F.batch_dot(e_matrix.softmax(), tilde_a) return alpha
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "feature_a", ")", ":", "tilde_a", "=", "self", ".", "intra_attn_emb", "(", "feature_a", ")", "e_matrix", "=", "F", ".", "batch_dot", "(", "tilde_a", ",", "tilde_a", ",", "transpose_b", "=", "True", ")", "alpha", "=", "F", ".", "batch_dot", "(", "e_matrix", ".", "softmax", "(", ")", ",", "tilde_a", ")", "return", "alpha" ]
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)
[ "Compute", "intra", "-", "sentence", "attention", "given", "embedded", "words", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/decomposable_attention.py#L98-L115
train
dmlc/gluon-nlp
scripts/natural_language_inference/decomposable_attention.py
DecomposableAttention.hybrid_forward
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 # e.shape = [B, L1, L2] e = F.batch_dot(tilde_a, tilde_b, transpose_b=True) # beta: b align to a, [B, L1, H] beta = F.batch_dot(e.softmax(), tilde_b) # alpha: a align to b, [B, L2, H] alpha = F.batch_dot(e.transpose([0, 2, 1]).softmax(), tilde_a) # compare feature1 = self.g(F.concat(tilde_a, beta, dim=2)) feature2 = self.g(F.concat(tilde_b, alpha, dim=2)) feature1 = feature1.sum(axis=1) feature2 = feature2.sum(axis=1) yhat = self.h(F.concat(feature1, feature2, dim=1)) return yhat
python
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 # e.shape = [B, L1, L2] e = F.batch_dot(tilde_a, tilde_b, transpose_b=True) # beta: b align to a, [B, L1, H] beta = F.batch_dot(e.softmax(), tilde_b) # alpha: a align to b, [B, L2, H] alpha = F.batch_dot(e.transpose([0, 2, 1]).softmax(), tilde_a) # compare feature1 = self.g(F.concat(tilde_a, beta, dim=2)) feature2 = self.g(F.concat(tilde_b, alpha, dim=2)) feature1 = feature1.sum(axis=1) feature2 = feature2.sum(axis=1) yhat = self.h(F.concat(feature1, feature2, dim=1)) return yhat
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "a", ",", "b", ")", ":", "# 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", "# e.shape = [B, L1, L2]", "e", "=", "F", ".", "batch_dot", "(", "tilde_a", ",", "tilde_b", ",", "transpose_b", "=", "True", ")", "# beta: b align to a, [B, L1, H]", "beta", "=", "F", ".", "batch_dot", "(", "e", ".", "softmax", "(", ")", ",", "tilde_b", ")", "# alpha: a align to b, [B, L2, H]", "alpha", "=", "F", ".", "batch_dot", "(", "e", ".", "transpose", "(", "[", "0", ",", "2", ",", "1", "]", ")", ".", "softmax", "(", ")", ",", "tilde_a", ")", "# compare", "feature1", "=", "self", ".", "g", "(", "F", ".", "concat", "(", "tilde_a", ",", "beta", ",", "dim", "=", "2", ")", ")", "feature2", "=", "self", ".", "g", "(", "F", ".", "concat", "(", "tilde_b", ",", "alpha", ",", "dim", "=", "2", ")", ")", "feature1", "=", "feature1", ".", "sum", "(", "axis", "=", "1", ")", "feature2", "=", "feature2", ".", "sum", "(", "axis", "=", "1", ")", "yhat", "=", "self", ".", "h", "(", "F", ".", "concat", "(", "feature1", ",", "feature2", ",", "dim", "=", "1", ")", ")", "return", "yhat" ]
Forward of Decomposable Attention layer
[ "Forward", "of", "Decomposable", "Attention", "layer" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/decomposable_attention.py#L144-L166
train
dmlc/gluon-nlp
src/gluonnlp/data/utils.py
count_tokens
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 ---------- tokens : list of str A source list of tokens. to_lower : bool, default False Whether to convert the source source_str to the lower case. counter : Counter or None, default None The Counter instance to be updated with the counts of `tokens`. If None, return a new Counter instance counting tokens from `tokens`. Returns ------- The `counter` Counter instance after being updated with the token counts of `source_str`. If `counter` is None, return a new Counter instance counting tokens from `source_str`. Examples -------- >>> import re >>> source_str = ' Life is great ! \n life is good . \n' >>> source_str_tokens = filter(None, re.split(' |\n', source_str)) >>> gluonnlp.data.count_tokens(source_str_tokens) Counter({'is': 2, 'Life': 1, 'great': 1, '!': 1, 'life': 1, 'good': 1, '.': 1}) """ if to_lower: tokens = [t.lower() for t in tokens] if counter is None: return Counter(tokens) else: counter.update(tokens) return counter
python
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 ---------- tokens : list of str A source list of tokens. to_lower : bool, default False Whether to convert the source source_str to the lower case. counter : Counter or None, default None The Counter instance to be updated with the counts of `tokens`. If None, return a new Counter instance counting tokens from `tokens`. Returns ------- The `counter` Counter instance after being updated with the token counts of `source_str`. If `counter` is None, return a new Counter instance counting tokens from `source_str`. Examples -------- >>> import re >>> source_str = ' Life is great ! \n life is good . \n' >>> source_str_tokens = filter(None, re.split(' |\n', source_str)) >>> gluonnlp.data.count_tokens(source_str_tokens) Counter({'is': 2, 'Life': 1, 'great': 1, '!': 1, 'life': 1, 'good': 1, '.': 1}) """ if to_lower: tokens = [t.lower() for t in tokens] if counter is None: return Counter(tokens) else: counter.update(tokens) return counter
[ "def", "count_tokens", "(", "tokens", ",", "to_lower", "=", "False", ",", "counter", "=", "None", ")", ":", "if", "to_lower", ":", "tokens", "=", "[", "t", ".", "lower", "(", ")", "for", "t", "in", "tokens", "]", "if", "counter", "is", "None", ":", "return", "Counter", "(", "tokens", ")", "else", ":", "counter", ".", "update", "(", "tokens", ")", "return", "counter" ]
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 tokens. to_lower : bool, default False Whether to convert the source source_str to the lower case. counter : Counter or None, default None The Counter instance to be updated with the counts of `tokens`. If None, return a new Counter instance counting tokens from `tokens`. Returns ------- The `counter` Counter instance after being updated with the token counts of `source_str`. If `counter` is None, return a new Counter instance counting tokens from `source_str`. Examples -------- >>> import re >>> source_str = ' Life is great ! \n life is good . \n' >>> source_str_tokens = filter(None, re.split(' |\n', source_str)) >>> gluonnlp.data.count_tokens(source_str_tokens) Counter({'is': 2, 'Life': 1, 'great': 1, '!': 1, 'life': 1, 'good': 1, '.': 1})
[ "r", "Counts", "tokens", "in", "the", "specified", "string", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L92-L133
train
dmlc/gluon-nlp
src/gluonnlp/data/utils.py
slice_sequence
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 : list of object A flat list of tokens. length : int The length of each of the samples. pad_last : bool, default False Whether to pad the last sequence when its length doesn't align. If the last sequence's length doesn't align and ``pad_last`` is False, it will be dropped. pad_val : object, default The padding value to use when the padding of the last sequence is enabled. In general, the type of ``pad_val`` should be the same as the tokens. overlap : int, default 0 The extra number of items in current sample that should overlap with the next sample. Returns ------- List of list of tokens, with the length of each inner list equal to `length`. """ if length <= overlap: raise ValueError('length needs to be larger than overlap') if pad_last: pad_len = _slice_pad_length(len(sequence), length, overlap) sequence = sequence + [pad_val] * pad_len num_samples = (len(sequence) - length) // (length - overlap) + 1 return [sequence[i * (length - overlap): ((i + 1) * length - i * overlap)] for i in range(num_samples)]
python
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 : list of object A flat list of tokens. length : int The length of each of the samples. pad_last : bool, default False Whether to pad the last sequence when its length doesn't align. If the last sequence's length doesn't align and ``pad_last`` is False, it will be dropped. pad_val : object, default The padding value to use when the padding of the last sequence is enabled. In general, the type of ``pad_val`` should be the same as the tokens. overlap : int, default 0 The extra number of items in current sample that should overlap with the next sample. Returns ------- List of list of tokens, with the length of each inner list equal to `length`. """ if length <= overlap: raise ValueError('length needs to be larger than overlap') if pad_last: pad_len = _slice_pad_length(len(sequence), length, overlap) sequence = sequence + [pad_val] * pad_len num_samples = (len(sequence) - length) // (length - overlap) + 1 return [sequence[i * (length - overlap): ((i + 1) * length - i * overlap)] for i in range(num_samples)]
[ "def", "slice_sequence", "(", "sequence", ",", "length", ",", "pad_last", "=", "False", ",", "pad_val", "=", "C", ".", "PAD_TOKEN", ",", "overlap", "=", "0", ")", ":", "if", "length", "<=", "overlap", ":", "raise", "ValueError", "(", "'length needs to be larger than overlap'", ")", "if", "pad_last", ":", "pad_len", "=", "_slice_pad_length", "(", "len", "(", "sequence", ")", ",", "length", ",", "overlap", ")", "sequence", "=", "sequence", "+", "[", "pad_val", "]", "*", "pad_len", "num_samples", "=", "(", "len", "(", "sequence", ")", "-", "length", ")", "//", "(", "length", "-", "overlap", ")", "+", "1", "return", "[", "sequence", "[", "i", "*", "(", "length", "-", "overlap", ")", ":", "(", "(", "i", "+", "1", ")", "*", "length", "-", "i", "*", "overlap", ")", "]", "for", "i", "in", "range", "(", "num_samples", ")", "]" ]
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 the samples. pad_last : bool, default False Whether to pad the last sequence when its length doesn't align. If the last sequence's length doesn't align and ``pad_last`` is False, it will be dropped. pad_val : object, default The padding value to use when the padding of the last sequence is enabled. In general, the type of ``pad_val`` should be the same as the tokens. overlap : int, default 0 The extra number of items in current sample that should overlap with the next sample. Returns ------- List of list of tokens, with the length of each inner list equal to `length`.
[ "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", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L152-L187
train
dmlc/gluon-nlp
src/gluonnlp/data/utils.py
_slice_pad_length
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 : int, default 0 The extra number of items in current sample that should overlap with the next sample. Returns ------- Length of paddings. """ if length <= overlap: raise ValueError('length needs to be larger than overlap') step = length - overlap span = num_items - length residual = span % step if residual: return step - residual else: return 0
python
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 : int, default 0 The extra number of items in current sample that should overlap with the next sample. Returns ------- Length of paddings. """ if length <= overlap: raise ValueError('length needs to be larger than overlap') step = length - overlap span = num_items - length residual = span % step if residual: return step - residual else: return 0
[ "def", "_slice_pad_length", "(", "num_items", ",", "length", ",", "overlap", "=", "0", ")", ":", "if", "length", "<=", "overlap", ":", "raise", "ValueError", "(", "'length needs to be larger than overlap'", ")", "step", "=", "length", "-", "overlap", "span", "=", "num_items", "-", "length", "residual", "=", "span", "%", "step", "if", "residual", ":", "return", "step", "-", "residual", "else", ":", "return", "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 : int, default 0 The extra number of items in current sample that should overlap with the next sample. Returns ------- Length of paddings.
[ "Calculate", "the", "padding", "length", "needed", "for", "sliced", "samples", "in", "order", "not", "to", "discard", "data", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L190-L217
train
dmlc/gluon-nlp
src/gluonnlp/data/utils.py
train_valid_split
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] Returns ------- train : SimpleDataset valid : SimpleDataset """ if not 0.0 <= valid_ratio <= 1.0: raise ValueError('valid_ratio should be in [0, 1]') num_train = len(dataset) num_valid = np.ceil(num_train * valid_ratio).astype('int') indices = np.arange(num_train) np.random.shuffle(indices) valid = SimpleDataset([dataset[indices[i]] for i in range(num_valid)]) train = SimpleDataset([dataset[indices[i + num_valid]] for i in range(num_train - num_valid)]) return train, valid
python
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] Returns ------- train : SimpleDataset valid : SimpleDataset """ if not 0.0 <= valid_ratio <= 1.0: raise ValueError('valid_ratio should be in [0, 1]') num_train = len(dataset) num_valid = np.ceil(num_train * valid_ratio).astype('int') indices = np.arange(num_train) np.random.shuffle(indices) valid = SimpleDataset([dataset[indices[i]] for i in range(num_valid)]) train = SimpleDataset([dataset[indices[i + num_valid]] for i in range(num_train - num_valid)]) return train, valid
[ "def", "train_valid_split", "(", "dataset", ",", "valid_ratio", "=", "0.05", ")", ":", "if", "not", "0.0", "<=", "valid_ratio", "<=", "1.0", ":", "raise", "ValueError", "(", "'valid_ratio should be in [0, 1]'", ")", "num_train", "=", "len", "(", "dataset", ")", "num_valid", "=", "np", ".", "ceil", "(", "num_train", "*", "valid_ratio", ")", ".", "astype", "(", "'int'", ")", "indices", "=", "np", ".", "arange", "(", "num_train", ")", "np", ".", "random", ".", "shuffle", "(", "indices", ")", "valid", "=", "SimpleDataset", "(", "[", "dataset", "[", "indices", "[", "i", "]", "]", "for", "i", "in", "range", "(", "num_valid", ")", "]", ")", "train", "=", "SimpleDataset", "(", "[", "dataset", "[", "indices", "[", "i", "+", "num_valid", "]", "]", "for", "i", "in", "range", "(", "num_train", "-", "num_valid", ")", "]", ")", "return", "train", ",", "valid" ]
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 valid : SimpleDataset
[ "Split", "the", "dataset", "into", "training", "and", "validation", "sets", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L236-L262
train
dmlc/gluon-nlp
src/gluonnlp/data/utils.py
_load_pretrained_vocab
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' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. cls : nlp.Vocab or nlp.vocab.BERTVocab, default nlp.Vocab Returns ------- Vocab or nlp.vocab.BERTVocab Loaded vocabulary object for the pre-trained model. """ file_name = '{name}-{short_hash}'.format(name=name, short_hash=short_hash(name)) root = os.path.expanduser(root) file_path = os.path.join(root, file_name + '.vocab') sha1_hash = _vocab_sha1[name] if os.path.exists(file_path): if check_sha1(file_path, sha1_hash): return _load_vocab_file(file_path, cls) else: print('Detected mismatch in the content of model vocab file. Downloading again.') else: print('Vocab file is not found. Downloading.') if not os.path.exists(root): os.makedirs(root) zip_file_path = os.path.join(root, file_name + '.zip') repo_url = _get_repo_url() if repo_url[-1] != '/': repo_url = repo_url + '/' download(_url_format.format(repo_url=repo_url, file_name=file_name), path=zip_file_path, overwrite=True) with zipfile.ZipFile(zip_file_path) as zf: zf.extractall(root) os.remove(zip_file_path) if check_sha1(file_path, sha1_hash): return _load_vocab_file(file_path, cls) else: raise ValueError('Downloaded file has different hash. Please try again.')
python
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' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. cls : nlp.Vocab or nlp.vocab.BERTVocab, default nlp.Vocab Returns ------- Vocab or nlp.vocab.BERTVocab Loaded vocabulary object for the pre-trained model. """ file_name = '{name}-{short_hash}'.format(name=name, short_hash=short_hash(name)) root = os.path.expanduser(root) file_path = os.path.join(root, file_name + '.vocab') sha1_hash = _vocab_sha1[name] if os.path.exists(file_path): if check_sha1(file_path, sha1_hash): return _load_vocab_file(file_path, cls) else: print('Detected mismatch in the content of model vocab file. Downloading again.') else: print('Vocab file is not found. Downloading.') if not os.path.exists(root): os.makedirs(root) zip_file_path = os.path.join(root, file_name + '.zip') repo_url = _get_repo_url() if repo_url[-1] != '/': repo_url = repo_url + '/' download(_url_format.format(repo_url=repo_url, file_name=file_name), path=zip_file_path, overwrite=True) with zipfile.ZipFile(zip_file_path) as zf: zf.extractall(root) os.remove(zip_file_path) if check_sha1(file_path, sha1_hash): return _load_vocab_file(file_path, cls) else: raise ValueError('Downloaded file has different hash. Please try again.')
[ "def", "_load_pretrained_vocab", "(", "name", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ")", ",", "cls", "=", "None", ")", ":", "file_name", "=", "'{name}-{short_hash}'", ".", "format", "(", "name", "=", "name", ",", "short_hash", "=", "short_hash", "(", "name", ")", ")", "root", "=", "os", ".", "path", ".", "expanduser", "(", "root", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file_name", "+", "'.vocab'", ")", "sha1_hash", "=", "_vocab_sha1", "[", "name", "]", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "if", "check_sha1", "(", "file_path", ",", "sha1_hash", ")", ":", "return", "_load_vocab_file", "(", "file_path", ",", "cls", ")", "else", ":", "print", "(", "'Detected mismatch in the content of model vocab file. Downloading again.'", ")", "else", ":", "print", "(", "'Vocab file is not found. Downloading.'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "root", ")", ":", "os", ".", "makedirs", "(", "root", ")", "zip_file_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file_name", "+", "'.zip'", ")", "repo_url", "=", "_get_repo_url", "(", ")", "if", "repo_url", "[", "-", "1", "]", "!=", "'/'", ":", "repo_url", "=", "repo_url", "+", "'/'", "download", "(", "_url_format", ".", "format", "(", "repo_url", "=", "repo_url", ",", "file_name", "=", "file_name", ")", ",", "path", "=", "zip_file_path", ",", "overwrite", "=", "True", ")", "with", "zipfile", ".", "ZipFile", "(", "zip_file_path", ")", "as", "zf", ":", "zf", ".", "extractall", "(", "root", ")", "os", ".", "remove", "(", "zip_file_path", ")", "if", "check_sha1", "(", "file_path", ",", "sha1_hash", ")", ":", "return", "_load_vocab_file", "(", "file_path", ",", "cls", ")", "else", ":", "raise", "ValueError", "(", "'Downloaded file has different hash. Please try again.'", ")" ]
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 : nlp.Vocab or nlp.vocab.BERTVocab, default nlp.Vocab Returns ------- Vocab or nlp.vocab.BERTVocab Loaded vocabulary object for the pre-trained model.
[ "Load", "the", "accompanying", "vocabulary", "object", "for", "pre", "-", "trained", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L271-L318
train
dmlc/gluon-nlp
src/gluonnlp/data/utils.py
_extract_archive
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('.tgz'): archive = tarfile.open(file, 'r') elif file.endswith('.zip'): archive = zipfile.ZipFile(file, 'r') else: raise Exception('Unrecognized file type: ' + file) archive.extractall(path=target_dir) archive.close()
python
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('.tgz'): archive = tarfile.open(file, 'r') elif file.endswith('.zip'): archive = zipfile.ZipFile(file, 'r') else: raise Exception('Unrecognized file type: ' + file) archive.extractall(path=target_dir) archive.close()
[ "def", "_extract_archive", "(", "file", ",", "target_dir", ")", ":", "if", "file", ".", "endswith", "(", "'.gz'", ")", "or", "file", ".", "endswith", "(", "'.tar'", ")", "or", "file", ".", "endswith", "(", "'.tgz'", ")", ":", "archive", "=", "tarfile", ".", "open", "(", "file", ",", "'r'", ")", "elif", "file", ".", "endswith", "(", "'.zip'", ")", ":", "archive", "=", "zipfile", ".", "ZipFile", "(", "file", ",", "'r'", ")", "else", ":", "raise", "Exception", "(", "'Unrecognized file type: '", "+", "file", ")", "archive", ".", "extractall", "(", "path", "=", "target_dir", ")", "archive", ".", "close", "(", ")" ]
Extract archive file Parameters ---------- file : str Absolute path of the archive file. target_dir : str Target directory of the archive to be uncompressed
[ "Extract", "archive", "file" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L330-L348
train
dmlc/gluon-nlp
src/gluonnlp/data/utils.py
Counter.discard
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 Counter returned. unknown_token: str The representation for any unknown token. Returns ------- The Counter instance. Examples -------- >>> a = gluonnlp.data.Counter({'a': 10, 'b': 1, 'c': 1}) >>> a.discard(3, '<unk>') Counter({'a': 10, '<unk>': 2}) """ freq = 0 ret = Counter({}) for token, count in self.items(): if count < min_freq: freq += count else: ret[token] = count ret[unknown_token] = ret.get(unknown_token, 0) + freq return ret
python
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 Counter returned. unknown_token: str The representation for any unknown token. Returns ------- The Counter instance. Examples -------- >>> a = gluonnlp.data.Counter({'a': 10, 'b': 1, 'c': 1}) >>> a.discard(3, '<unk>') Counter({'a': 10, '<unk>': 2}) """ freq = 0 ret = Counter({}) for token, count in self.items(): if count < min_freq: freq += count else: ret[token] = count ret[unknown_token] = ret.get(unknown_token, 0) + freq return ret
[ "def", "discard", "(", "self", ",", "min_freq", ",", "unknown_token", ")", ":", "freq", "=", "0", "ret", "=", "Counter", "(", "{", "}", ")", "for", "token", ",", "count", "in", "self", ".", "items", "(", ")", ":", "if", "count", "<", "min_freq", ":", "freq", "+=", "count", "else", ":", "ret", "[", "token", "]", "=", "count", "ret", "[", "unknown_token", "]", "=", "ret", ".", "get", "(", "unknown_token", ",", "0", ")", "+", "freq", "return", "ret" ]
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 The representation for any unknown token. Returns ------- The Counter instance. Examples -------- >>> a = gluonnlp.data.Counter({'a': 10, 'b': 1, 'c': 1}) >>> a.discard(3, '<unk>') Counter({'a': 10, '<unk>': 2})
[ "Discards", "tokens", "with", "frequency", "below", "min_frequency", "and", "represents", "them", "as", "unknown_token", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L45-L75
train
dmlc/gluon-nlp
scripts/machine_translation/train_transformer.py
train
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, data_test, args, use_average_length=True, num_shards=len(ctx)) if args.bleu == 'tweaked': bpe = bool(args.dataset != 'IWSLT2015' and args.dataset != 'TOY') split_compound_word = bpe tokenized = True elif args.bleu == '13a' or args.bleu == 'intl': bpe = False split_compound_word = False tokenized = False else: raise NotImplementedError best_valid_bleu = 0.0 step_num = 0 warmup_steps = args.warmup_steps grad_interval = args.num_accumulated model.collect_params().setattr('grad_req', 'add') average_start = (len(train_data_loader) // grad_interval) * (args.epochs - args.average_start) average_param_dict = None model.collect_params().zero_grad() parallel = Parallel(num_ctxs, parallel_model) for epoch_id in range(args.epochs): log_avg_loss = 0 log_wc = 0 loss_denom = 0 step_loss = 0 log_start_time = time.time() for batch_id, seqs \ in enumerate(train_data_loader): if batch_id % grad_interval == 0: step_num += 1 new_lr = args.lr / math.sqrt(args.num_units) \ * min(1. / math.sqrt(step_num), step_num * warmup_steps ** (-1.5)) trainer.set_learning_rate(new_lr) src_wc, tgt_wc, bs = np.sum([(shard[2].sum(), shard[3].sum(), shard[0].shape[0]) for shard in seqs], axis=0) seqs = [[seq.as_in_context(context) for seq in shard] for context, shard in zip(ctx, seqs)] Ls = [] for seq in seqs: parallel.put((seq, args.batch_size)) Ls = [parallel.get() for _ in range(len(ctx))] src_wc = src_wc.asscalar() tgt_wc = tgt_wc.asscalar() loss_denom += tgt_wc - bs if batch_id % grad_interval == grad_interval - 1 or\ batch_id == len(train_data_loader) - 1: if average_param_dict is None: average_param_dict = {k: v.data(ctx[0]).copy() for k, v in model.collect_params().items()} trainer.step(float(loss_denom) / args.batch_size / 100.0) param_dict = model.collect_params() param_dict.zero_grad() if step_num > average_start: alpha = 1. / max(1, step_num - average_start) for name, average_param in average_param_dict.items(): average_param[:] += alpha * (param_dict[name].data(ctx[0]) - average_param) step_loss += sum([L.asscalar() for L in Ls]) if batch_id % grad_interval == grad_interval - 1 or\ batch_id == len(train_data_loader) - 1: log_avg_loss += step_loss / loss_denom * args.batch_size * 100.0 loss_denom = 0 step_loss = 0 log_wc += src_wc + tgt_wc if (batch_id + 1) % (args.log_interval * grad_interval) == 0: wps = log_wc / (time.time() - log_start_time) logging.info('[Epoch {} Batch {}/{}] loss={:.4f}, ppl={:.4f}, ' 'throughput={:.2f}K wps, wc={:.2f}K' .format(epoch_id, batch_id + 1, len(train_data_loader), log_avg_loss / args.log_interval, np.exp(log_avg_loss / args.log_interval), wps / 1000, log_wc / 1000)) log_start_time = time.time() log_avg_loss = 0 log_wc = 0 mx.nd.waitall() valid_loss, valid_translation_out = evaluate(val_data_loader, ctx[0]) valid_bleu_score, _, _, _, _ = compute_bleu([val_tgt_sentences], valid_translation_out, tokenized=tokenized, tokenizer=args.bleu, split_compound_word=split_compound_word, bpe=bpe) logging.info('[Epoch {}] valid Loss={:.4f}, valid ppl={:.4f}, valid bleu={:.2f}' .format(epoch_id, valid_loss, np.exp(valid_loss), valid_bleu_score * 100)) test_loss, test_translation_out = evaluate(test_data_loader, ctx[0]) test_bleu_score, _, _, _, _ = compute_bleu([test_tgt_sentences], test_translation_out, tokenized=tokenized, tokenizer=args.bleu, split_compound_word=split_compound_word, bpe=bpe) logging.info('[Epoch {}] test Loss={:.4f}, test ppl={:.4f}, test bleu={:.2f}' .format(epoch_id, test_loss, np.exp(test_loss), test_bleu_score * 100)) dataprocessor.write_sentences(valid_translation_out, os.path.join(args.save_dir, 'epoch{:d}_valid_out.txt').format(epoch_id)) dataprocessor.write_sentences(test_translation_out, os.path.join(args.save_dir, 'epoch{:d}_test_out.txt').format(epoch_id)) if valid_bleu_score > best_valid_bleu: best_valid_bleu = valid_bleu_score save_path = os.path.join(args.save_dir, 'valid_best.params') logging.info('Save best parameters to {}'.format(save_path)) model.save_parameters(save_path) save_path = os.path.join(args.save_dir, 'epoch{:d}.params'.format(epoch_id)) model.save_parameters(save_path) save_path = os.path.join(args.save_dir, 'average.params') mx.nd.save(save_path, average_param_dict) if args.average_checkpoint: for j in range(args.num_averages): params = mx.nd.load(os.path.join(args.save_dir, 'epoch{:d}.params'.format(args.epochs - j - 1))) alpha = 1. / (j + 1) for k, v in model._collect_params_with_prefix().items(): for c in ctx: v.data(c)[:] += alpha * (params[k].as_in_context(c) - v.data(c)) save_path = os.path.join(args.save_dir, 'average_checkpoint_{}.params'.format(args.num_averages)) model.save_parameters(save_path) elif args.average_start > 0: for k, v in model.collect_params().items(): v.set_data(average_param_dict[k]) save_path = os.path.join(args.save_dir, 'average.params') model.save_parameters(save_path) else: model.load_parameters(os.path.join(args.save_dir, 'valid_best.params'), ctx) valid_loss, valid_translation_out = evaluate(val_data_loader, ctx[0]) valid_bleu_score, _, _, _, _ = compute_bleu([val_tgt_sentences], valid_translation_out, tokenized=tokenized, tokenizer=args.bleu, bpe=bpe, split_compound_word=split_compound_word) logging.info('Best model valid Loss={:.4f}, valid ppl={:.4f}, valid bleu={:.2f}' .format(valid_loss, np.exp(valid_loss), valid_bleu_score * 100)) test_loss, test_translation_out = evaluate(test_data_loader, ctx[0]) test_bleu_score, _, _, _, _ = compute_bleu([test_tgt_sentences], test_translation_out, tokenized=tokenized, tokenizer=args.bleu, bpe=bpe, split_compound_word=split_compound_word) logging.info('Best model test Loss={:.4f}, test ppl={:.4f}, test bleu={:.2f}' .format(test_loss, np.exp(test_loss), test_bleu_score * 100)) dataprocessor.write_sentences(valid_translation_out, os.path.join(args.save_dir, 'best_valid_out.txt')) dataprocessor.write_sentences(test_translation_out, os.path.join(args.save_dir, 'best_test_out.txt'))
python
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, data_test, args, use_average_length=True, num_shards=len(ctx)) if args.bleu == 'tweaked': bpe = bool(args.dataset != 'IWSLT2015' and args.dataset != 'TOY') split_compound_word = bpe tokenized = True elif args.bleu == '13a' or args.bleu == 'intl': bpe = False split_compound_word = False tokenized = False else: raise NotImplementedError best_valid_bleu = 0.0 step_num = 0 warmup_steps = args.warmup_steps grad_interval = args.num_accumulated model.collect_params().setattr('grad_req', 'add') average_start = (len(train_data_loader) // grad_interval) * (args.epochs - args.average_start) average_param_dict = None model.collect_params().zero_grad() parallel = Parallel(num_ctxs, parallel_model) for epoch_id in range(args.epochs): log_avg_loss = 0 log_wc = 0 loss_denom = 0 step_loss = 0 log_start_time = time.time() for batch_id, seqs \ in enumerate(train_data_loader): if batch_id % grad_interval == 0: step_num += 1 new_lr = args.lr / math.sqrt(args.num_units) \ * min(1. / math.sqrt(step_num), step_num * warmup_steps ** (-1.5)) trainer.set_learning_rate(new_lr) src_wc, tgt_wc, bs = np.sum([(shard[2].sum(), shard[3].sum(), shard[0].shape[0]) for shard in seqs], axis=0) seqs = [[seq.as_in_context(context) for seq in shard] for context, shard in zip(ctx, seqs)] Ls = [] for seq in seqs: parallel.put((seq, args.batch_size)) Ls = [parallel.get() for _ in range(len(ctx))] src_wc = src_wc.asscalar() tgt_wc = tgt_wc.asscalar() loss_denom += tgt_wc - bs if batch_id % grad_interval == grad_interval - 1 or\ batch_id == len(train_data_loader) - 1: if average_param_dict is None: average_param_dict = {k: v.data(ctx[0]).copy() for k, v in model.collect_params().items()} trainer.step(float(loss_denom) / args.batch_size / 100.0) param_dict = model.collect_params() param_dict.zero_grad() if step_num > average_start: alpha = 1. / max(1, step_num - average_start) for name, average_param in average_param_dict.items(): average_param[:] += alpha * (param_dict[name].data(ctx[0]) - average_param) step_loss += sum([L.asscalar() for L in Ls]) if batch_id % grad_interval == grad_interval - 1 or\ batch_id == len(train_data_loader) - 1: log_avg_loss += step_loss / loss_denom * args.batch_size * 100.0 loss_denom = 0 step_loss = 0 log_wc += src_wc + tgt_wc if (batch_id + 1) % (args.log_interval * grad_interval) == 0: wps = log_wc / (time.time() - log_start_time) logging.info('[Epoch {} Batch {}/{}] loss={:.4f}, ppl={:.4f}, ' 'throughput={:.2f}K wps, wc={:.2f}K' .format(epoch_id, batch_id + 1, len(train_data_loader), log_avg_loss / args.log_interval, np.exp(log_avg_loss / args.log_interval), wps / 1000, log_wc / 1000)) log_start_time = time.time() log_avg_loss = 0 log_wc = 0 mx.nd.waitall() valid_loss, valid_translation_out = evaluate(val_data_loader, ctx[0]) valid_bleu_score, _, _, _, _ = compute_bleu([val_tgt_sentences], valid_translation_out, tokenized=tokenized, tokenizer=args.bleu, split_compound_word=split_compound_word, bpe=bpe) logging.info('[Epoch {}] valid Loss={:.4f}, valid ppl={:.4f}, valid bleu={:.2f}' .format(epoch_id, valid_loss, np.exp(valid_loss), valid_bleu_score * 100)) test_loss, test_translation_out = evaluate(test_data_loader, ctx[0]) test_bleu_score, _, _, _, _ = compute_bleu([test_tgt_sentences], test_translation_out, tokenized=tokenized, tokenizer=args.bleu, split_compound_word=split_compound_word, bpe=bpe) logging.info('[Epoch {}] test Loss={:.4f}, test ppl={:.4f}, test bleu={:.2f}' .format(epoch_id, test_loss, np.exp(test_loss), test_bleu_score * 100)) dataprocessor.write_sentences(valid_translation_out, os.path.join(args.save_dir, 'epoch{:d}_valid_out.txt').format(epoch_id)) dataprocessor.write_sentences(test_translation_out, os.path.join(args.save_dir, 'epoch{:d}_test_out.txt').format(epoch_id)) if valid_bleu_score > best_valid_bleu: best_valid_bleu = valid_bleu_score save_path = os.path.join(args.save_dir, 'valid_best.params') logging.info('Save best parameters to {}'.format(save_path)) model.save_parameters(save_path) save_path = os.path.join(args.save_dir, 'epoch{:d}.params'.format(epoch_id)) model.save_parameters(save_path) save_path = os.path.join(args.save_dir, 'average.params') mx.nd.save(save_path, average_param_dict) if args.average_checkpoint: for j in range(args.num_averages): params = mx.nd.load(os.path.join(args.save_dir, 'epoch{:d}.params'.format(args.epochs - j - 1))) alpha = 1. / (j + 1) for k, v in model._collect_params_with_prefix().items(): for c in ctx: v.data(c)[:] += alpha * (params[k].as_in_context(c) - v.data(c)) save_path = os.path.join(args.save_dir, 'average_checkpoint_{}.params'.format(args.num_averages)) model.save_parameters(save_path) elif args.average_start > 0: for k, v in model.collect_params().items(): v.set_data(average_param_dict[k]) save_path = os.path.join(args.save_dir, 'average.params') model.save_parameters(save_path) else: model.load_parameters(os.path.join(args.save_dir, 'valid_best.params'), ctx) valid_loss, valid_translation_out = evaluate(val_data_loader, ctx[0]) valid_bleu_score, _, _, _, _ = compute_bleu([val_tgt_sentences], valid_translation_out, tokenized=tokenized, tokenizer=args.bleu, bpe=bpe, split_compound_word=split_compound_word) logging.info('Best model valid Loss={:.4f}, valid ppl={:.4f}, valid bleu={:.2f}' .format(valid_loss, np.exp(valid_loss), valid_bleu_score * 100)) test_loss, test_translation_out = evaluate(test_data_loader, ctx[0]) test_bleu_score, _, _, _, _ = compute_bleu([test_tgt_sentences], test_translation_out, tokenized=tokenized, tokenizer=args.bleu, bpe=bpe, split_compound_word=split_compound_word) logging.info('Best model test Loss={:.4f}, test ppl={:.4f}, test bleu={:.2f}' .format(test_loss, np.exp(test_loss), test_bleu_score * 100)) dataprocessor.write_sentences(valid_translation_out, os.path.join(args.save_dir, 'best_valid_out.txt')) dataprocessor.write_sentences(test_translation_out, os.path.join(args.save_dir, 'best_test_out.txt'))
[ "def", "train", "(", ")", ":", "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", ",", "data_test", ",", "args", ",", "use_average_length", "=", "True", ",", "num_shards", "=", "len", "(", "ctx", ")", ")", "if", "args", ".", "bleu", "==", "'tweaked'", ":", "bpe", "=", "bool", "(", "args", ".", "dataset", "!=", "'IWSLT2015'", "and", "args", ".", "dataset", "!=", "'TOY'", ")", "split_compound_word", "=", "bpe", "tokenized", "=", "True", "elif", "args", ".", "bleu", "==", "'13a'", "or", "args", ".", "bleu", "==", "'intl'", ":", "bpe", "=", "False", "split_compound_word", "=", "False", "tokenized", "=", "False", "else", ":", "raise", "NotImplementedError", "best_valid_bleu", "=", "0.0", "step_num", "=", "0", "warmup_steps", "=", "args", ".", "warmup_steps", "grad_interval", "=", "args", ".", "num_accumulated", "model", ".", "collect_params", "(", ")", ".", "setattr", "(", "'grad_req'", ",", "'add'", ")", "average_start", "=", "(", "len", "(", "train_data_loader", ")", "//", "grad_interval", ")", "*", "(", "args", ".", "epochs", "-", "args", ".", "average_start", ")", "average_param_dict", "=", "None", "model", ".", "collect_params", "(", ")", ".", "zero_grad", "(", ")", "parallel", "=", "Parallel", "(", "num_ctxs", ",", "parallel_model", ")", "for", "epoch_id", "in", "range", "(", "args", ".", "epochs", ")", ":", "log_avg_loss", "=", "0", "log_wc", "=", "0", "loss_denom", "=", "0", "step_loss", "=", "0", "log_start_time", "=", "time", ".", "time", "(", ")", "for", "batch_id", ",", "seqs", "in", "enumerate", "(", "train_data_loader", ")", ":", "if", "batch_id", "%", "grad_interval", "==", "0", ":", "step_num", "+=", "1", "new_lr", "=", "args", ".", "lr", "/", "math", ".", "sqrt", "(", "args", ".", "num_units", ")", "*", "min", "(", "1.", "/", "math", ".", "sqrt", "(", "step_num", ")", ",", "step_num", "*", "warmup_steps", "**", "(", "-", "1.5", ")", ")", "trainer", ".", "set_learning_rate", "(", "new_lr", ")", "src_wc", ",", "tgt_wc", ",", "bs", "=", "np", ".", "sum", "(", "[", "(", "shard", "[", "2", "]", ".", "sum", "(", ")", ",", "shard", "[", "3", "]", ".", "sum", "(", ")", ",", "shard", "[", "0", "]", ".", "shape", "[", "0", "]", ")", "for", "shard", "in", "seqs", "]", ",", "axis", "=", "0", ")", "seqs", "=", "[", "[", "seq", ".", "as_in_context", "(", "context", ")", "for", "seq", "in", "shard", "]", "for", "context", ",", "shard", "in", "zip", "(", "ctx", ",", "seqs", ")", "]", "Ls", "=", "[", "]", "for", "seq", "in", "seqs", ":", "parallel", ".", "put", "(", "(", "seq", ",", "args", ".", "batch_size", ")", ")", "Ls", "=", "[", "parallel", ".", "get", "(", ")", "for", "_", "in", "range", "(", "len", "(", "ctx", ")", ")", "]", "src_wc", "=", "src_wc", ".", "asscalar", "(", ")", "tgt_wc", "=", "tgt_wc", ".", "asscalar", "(", ")", "loss_denom", "+=", "tgt_wc", "-", "bs", "if", "batch_id", "%", "grad_interval", "==", "grad_interval", "-", "1", "or", "batch_id", "==", "len", "(", "train_data_loader", ")", "-", "1", ":", "if", "average_param_dict", "is", "None", ":", "average_param_dict", "=", "{", "k", ":", "v", ".", "data", "(", "ctx", "[", "0", "]", ")", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "model", ".", "collect_params", "(", ")", ".", "items", "(", ")", "}", "trainer", ".", "step", "(", "float", "(", "loss_denom", ")", "/", "args", ".", "batch_size", "/", "100.0", ")", "param_dict", "=", "model", ".", "collect_params", "(", ")", "param_dict", ".", "zero_grad", "(", ")", "if", "step_num", ">", "average_start", ":", "alpha", "=", "1.", "/", "max", "(", "1", ",", "step_num", "-", "average_start", ")", "for", "name", ",", "average_param", "in", "average_param_dict", ".", "items", "(", ")", ":", "average_param", "[", ":", "]", "+=", "alpha", "*", "(", "param_dict", "[", "name", "]", ".", "data", "(", "ctx", "[", "0", "]", ")", "-", "average_param", ")", "step_loss", "+=", "sum", "(", "[", "L", ".", "asscalar", "(", ")", "for", "L", "in", "Ls", "]", ")", "if", "batch_id", "%", "grad_interval", "==", "grad_interval", "-", "1", "or", "batch_id", "==", "len", "(", "train_data_loader", ")", "-", "1", ":", "log_avg_loss", "+=", "step_loss", "/", "loss_denom", "*", "args", ".", "batch_size", "*", "100.0", "loss_denom", "=", "0", "step_loss", "=", "0", "log_wc", "+=", "src_wc", "+", "tgt_wc", "if", "(", "batch_id", "+", "1", ")", "%", "(", "args", ".", "log_interval", "*", "grad_interval", ")", "==", "0", ":", "wps", "=", "log_wc", "/", "(", "time", ".", "time", "(", ")", "-", "log_start_time", ")", "logging", ".", "info", "(", "'[Epoch {} Batch {}/{}] loss={:.4f}, ppl={:.4f}, '", "'throughput={:.2f}K wps, wc={:.2f}K'", ".", "format", "(", "epoch_id", ",", "batch_id", "+", "1", ",", "len", "(", "train_data_loader", ")", ",", "log_avg_loss", "/", "args", ".", "log_interval", ",", "np", ".", "exp", "(", "log_avg_loss", "/", "args", ".", "log_interval", ")", ",", "wps", "/", "1000", ",", "log_wc", "/", "1000", ")", ")", "log_start_time", "=", "time", ".", "time", "(", ")", "log_avg_loss", "=", "0", "log_wc", "=", "0", "mx", ".", "nd", ".", "waitall", "(", ")", "valid_loss", ",", "valid_translation_out", "=", "evaluate", "(", "val_data_loader", ",", "ctx", "[", "0", "]", ")", "valid_bleu_score", ",", "_", ",", "_", ",", "_", ",", "_", "=", "compute_bleu", "(", "[", "val_tgt_sentences", "]", ",", "valid_translation_out", ",", "tokenized", "=", "tokenized", ",", "tokenizer", "=", "args", ".", "bleu", ",", "split_compound_word", "=", "split_compound_word", ",", "bpe", "=", "bpe", ")", "logging", ".", "info", "(", "'[Epoch {}] valid Loss={:.4f}, valid ppl={:.4f}, valid bleu={:.2f}'", ".", "format", "(", "epoch_id", ",", "valid_loss", ",", "np", ".", "exp", "(", "valid_loss", ")", ",", "valid_bleu_score", "*", "100", ")", ")", "test_loss", ",", "test_translation_out", "=", "evaluate", "(", "test_data_loader", ",", "ctx", "[", "0", "]", ")", "test_bleu_score", ",", "_", ",", "_", ",", "_", ",", "_", "=", "compute_bleu", "(", "[", "test_tgt_sentences", "]", ",", "test_translation_out", ",", "tokenized", "=", "tokenized", ",", "tokenizer", "=", "args", ".", "bleu", ",", "split_compound_word", "=", "split_compound_word", ",", "bpe", "=", "bpe", ")", "logging", ".", "info", "(", "'[Epoch {}] test Loss={:.4f}, test ppl={:.4f}, test bleu={:.2f}'", ".", "format", "(", "epoch_id", ",", "test_loss", ",", "np", ".", "exp", "(", "test_loss", ")", ",", "test_bleu_score", "*", "100", ")", ")", "dataprocessor", ".", "write_sentences", "(", "valid_translation_out", ",", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'epoch{:d}_valid_out.txt'", ")", ".", "format", "(", "epoch_id", ")", ")", "dataprocessor", ".", "write_sentences", "(", "test_translation_out", ",", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'epoch{:d}_test_out.txt'", ")", ".", "format", "(", "epoch_id", ")", ")", "if", "valid_bleu_score", ">", "best_valid_bleu", ":", "best_valid_bleu", "=", "valid_bleu_score", "save_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'valid_best.params'", ")", "logging", ".", "info", "(", "'Save best parameters to {}'", ".", "format", "(", "save_path", ")", ")", "model", ".", "save_parameters", "(", "save_path", ")", "save_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'epoch{:d}.params'", ".", "format", "(", "epoch_id", ")", ")", "model", ".", "save_parameters", "(", "save_path", ")", "save_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'average.params'", ")", "mx", ".", "nd", ".", "save", "(", "save_path", ",", "average_param_dict", ")", "if", "args", ".", "average_checkpoint", ":", "for", "j", "in", "range", "(", "args", ".", "num_averages", ")", ":", "params", "=", "mx", ".", "nd", ".", "load", "(", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'epoch{:d}.params'", ".", "format", "(", "args", ".", "epochs", "-", "j", "-", "1", ")", ")", ")", "alpha", "=", "1.", "/", "(", "j", "+", "1", ")", "for", "k", ",", "v", "in", "model", ".", "_collect_params_with_prefix", "(", ")", ".", "items", "(", ")", ":", "for", "c", "in", "ctx", ":", "v", ".", "data", "(", "c", ")", "[", ":", "]", "+=", "alpha", "*", "(", "params", "[", "k", "]", ".", "as_in_context", "(", "c", ")", "-", "v", ".", "data", "(", "c", ")", ")", "save_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'average_checkpoint_{}.params'", ".", "format", "(", "args", ".", "num_averages", ")", ")", "model", ".", "save_parameters", "(", "save_path", ")", "elif", "args", ".", "average_start", ">", "0", ":", "for", "k", ",", "v", "in", "model", ".", "collect_params", "(", ")", ".", "items", "(", ")", ":", "v", ".", "set_data", "(", "average_param_dict", "[", "k", "]", ")", "save_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'average.params'", ")", "model", ".", "save_parameters", "(", "save_path", ")", "else", ":", "model", ".", "load_parameters", "(", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'valid_best.params'", ")", ",", "ctx", ")", "valid_loss", ",", "valid_translation_out", "=", "evaluate", "(", "val_data_loader", ",", "ctx", "[", "0", "]", ")", "valid_bleu_score", ",", "_", ",", "_", ",", "_", ",", "_", "=", "compute_bleu", "(", "[", "val_tgt_sentences", "]", ",", "valid_translation_out", ",", "tokenized", "=", "tokenized", ",", "tokenizer", "=", "args", ".", "bleu", ",", "bpe", "=", "bpe", ",", "split_compound_word", "=", "split_compound_word", ")", "logging", ".", "info", "(", "'Best model valid Loss={:.4f}, valid ppl={:.4f}, valid bleu={:.2f}'", ".", "format", "(", "valid_loss", ",", "np", ".", "exp", "(", "valid_loss", ")", ",", "valid_bleu_score", "*", "100", ")", ")", "test_loss", ",", "test_translation_out", "=", "evaluate", "(", "test_data_loader", ",", "ctx", "[", "0", "]", ")", "test_bleu_score", ",", "_", ",", "_", ",", "_", ",", "_", "=", "compute_bleu", "(", "[", "test_tgt_sentences", "]", ",", "test_translation_out", ",", "tokenized", "=", "tokenized", ",", "tokenizer", "=", "args", ".", "bleu", ",", "bpe", "=", "bpe", ",", "split_compound_word", "=", "split_compound_word", ")", "logging", ".", "info", "(", "'Best model test Loss={:.4f}, test ppl={:.4f}, test bleu={:.2f}'", ".", "format", "(", "test_loss", ",", "np", ".", "exp", "(", "test_loss", ")", ",", "test_bleu_score", "*", "100", ")", ")", "dataprocessor", ".", "write_sentences", "(", "valid_translation_out", ",", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'best_valid_out.txt'", ")", ")", "dataprocessor", ".", "write_sentences", "(", "test_translation_out", ",", "os", ".", "path", ".", "join", "(", "args", ".", "save_dir", ",", "'best_test_out.txt'", ")", ")" ]
Training function.
[ "Training", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/train_transformer.py#L262-L408
train
dmlc/gluon-nlp
src/gluonnlp/model/highway.py
Highway.hybrid_forward
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 ---------- outputs: NDArray The output tensor is of the same shape with input tensor `(..., input_size)`. """ current_input = inputs for layer in self.hnet: projected_input = layer(current_input) linear_transform = current_input nonlinear_transform, transform_gate = projected_input.split(num_outputs=2, axis=-1) nonlinear_transform = self._activation(nonlinear_transform) transform_gate = transform_gate.sigmoid() current_input = (1 - transform_gate) * linear_transform + \ transform_gate * nonlinear_transform return current_input
python
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 ---------- outputs: NDArray The output tensor is of the same shape with input tensor `(..., input_size)`. """ current_input = inputs for layer in self.hnet: projected_input = layer(current_input) linear_transform = current_input nonlinear_transform, transform_gate = projected_input.split(num_outputs=2, axis=-1) nonlinear_transform = self._activation(nonlinear_transform) transform_gate = transform_gate.sigmoid() current_input = (1 - transform_gate) * linear_transform + \ transform_gate * nonlinear_transform return current_input
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "current_input", "=", "inputs", "for", "layer", "in", "self", ".", "hnet", ":", "projected_input", "=", "layer", "(", "current_input", ")", "linear_transform", "=", "current_input", "nonlinear_transform", ",", "transform_gate", "=", "projected_input", ".", "split", "(", "num_outputs", "=", "2", ",", "axis", "=", "-", "1", ")", "nonlinear_transform", "=", "self", ".", "_activation", "(", "nonlinear_transform", ")", "transform_gate", "=", "transform_gate", ".", "sigmoid", "(", ")", "current_input", "=", "(", "1", "-", "transform_gate", ")", "*", "linear_transform", "+", "transform_gate", "*", "nonlinear_transform", "return", "current_input" ]
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_size)`.
[ "r", "Forward", "computation", "for", "highway", "layer" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/highway.py#L102-L126
train
dmlc/gluon-nlp
scripts/bert/bert_qa_model.py
BertForQA.forward
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. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to indicate whether the word belongs to the first sentence or the second one. valid_length : NDArray or None, shape (batch_size,) Valid length of the sequence. This is used to mask the padded tokens. Returns ------- outputs : NDArray Shape (batch_size, seq_length, 2) """ bert_output = self.bert(inputs, token_types, valid_length) output = self.span_classifier(bert_output) return output
python
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. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to indicate whether the word belongs to the first sentence or the second one. valid_length : NDArray or None, shape (batch_size,) Valid length of the sequence. This is used to mask the padded tokens. Returns ------- outputs : NDArray Shape (batch_size, seq_length, 2) """ bert_output = self.bert(inputs, token_types, valid_length) output = self.span_classifier(bert_output) return output
[ "def", "forward", "(", "self", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "bert_output", "=", "self", ".", "bert", "(", "inputs", ",", "token_types", ",", "valid_length", ")", "output", "=", "self", ".", "span_classifier", "(", "bert_output", ")", "return", "output" ]
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 indicate whether the word belongs to the first sentence or the second one. valid_length : NDArray or None, shape (batch_size,) Valid length of the sequence. This is used to mask the padded tokens. Returns ------- outputs : NDArray Shape (batch_size, seq_length, 2)
[ "Generate", "the", "unnormalized", "score", "for", "the", "given", "the", "input", "sequences", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_model.py#L49-L69
train
dmlc/gluon-nlp
src/gluonnlp/model/bilm_encoder.py
BiLMEncoder.hybrid_forward
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 ---------- inputs : NDArray The input data layout='TNC'. states : Tuple[List[List[NDArray]]] The states. including: states[0] indicates the states used in forward layer, Each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). states[1] indicates the states used in backward layer, Each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). Returns -------- out: NDArray The output data with shape (num_layers, seq_len, batch_size, 2*input_size). [states_forward, states_backward] : List Including: states_forward: The out states from forward layer, which has the same structure with *states[0]*. states_backward: The out states from backward layer, which has the same structure with *states[1]*. """ states_forward, states_backward = states if mask is not None: sequence_length = mask.sum(axis=1) outputs_forward = [] outputs_backward = [] for layer_index in range(self._num_layers): if layer_index == 0: layer_inputs = inputs else: layer_inputs = outputs_forward[layer_index-1] output, states_forward[layer_index] = F.contrib.foreach( self.forward_layers[layer_index], layer_inputs, states_forward[layer_index]) outputs_forward.append(output) if layer_index == 0: layer_inputs = inputs else: layer_inputs = outputs_backward[layer_index-1] if mask is not None: layer_inputs = F.SequenceReverse(layer_inputs, sequence_length=sequence_length, use_sequence_length=True, axis=0) else: layer_inputs = F.SequenceReverse(layer_inputs, axis=0) output, states_backward[layer_index] = F.contrib.foreach( self.backward_layers[layer_index], layer_inputs, states_backward[layer_index]) if mask is not None: backward_out = F.SequenceReverse(output, sequence_length=sequence_length, use_sequence_length=True, axis=0) else: backward_out = F.SequenceReverse(output, axis=0) outputs_backward.append(backward_out) out = F.concat(*[F.stack(*outputs_forward, axis=0), F.stack(*outputs_backward, axis=0)], dim=-1) return out, [states_forward, states_backward]
python
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 ---------- inputs : NDArray The input data layout='TNC'. states : Tuple[List[List[NDArray]]] The states. including: states[0] indicates the states used in forward layer, Each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). states[1] indicates the states used in backward layer, Each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). Returns -------- out: NDArray The output data with shape (num_layers, seq_len, batch_size, 2*input_size). [states_forward, states_backward] : List Including: states_forward: The out states from forward layer, which has the same structure with *states[0]*. states_backward: The out states from backward layer, which has the same structure with *states[1]*. """ states_forward, states_backward = states if mask is not None: sequence_length = mask.sum(axis=1) outputs_forward = [] outputs_backward = [] for layer_index in range(self._num_layers): if layer_index == 0: layer_inputs = inputs else: layer_inputs = outputs_forward[layer_index-1] output, states_forward[layer_index] = F.contrib.foreach( self.forward_layers[layer_index], layer_inputs, states_forward[layer_index]) outputs_forward.append(output) if layer_index == 0: layer_inputs = inputs else: layer_inputs = outputs_backward[layer_index-1] if mask is not None: layer_inputs = F.SequenceReverse(layer_inputs, sequence_length=sequence_length, use_sequence_length=True, axis=0) else: layer_inputs = F.SequenceReverse(layer_inputs, axis=0) output, states_backward[layer_index] = F.contrib.foreach( self.backward_layers[layer_index], layer_inputs, states_backward[layer_index]) if mask is not None: backward_out = F.SequenceReverse(output, sequence_length=sequence_length, use_sequence_length=True, axis=0) else: backward_out = F.SequenceReverse(output, axis=0) outputs_backward.append(backward_out) out = F.concat(*[F.stack(*outputs_forward, axis=0), F.stack(*outputs_backward, axis=0)], dim=-1) return out, [states_forward, states_backward]
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", "=", "None", ",", "mask", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "states_forward", ",", "states_backward", "=", "states", "if", "mask", "is", "not", "None", ":", "sequence_length", "=", "mask", ".", "sum", "(", "axis", "=", "1", ")", "outputs_forward", "=", "[", "]", "outputs_backward", "=", "[", "]", "for", "layer_index", "in", "range", "(", "self", ".", "_num_layers", ")", ":", "if", "layer_index", "==", "0", ":", "layer_inputs", "=", "inputs", "else", ":", "layer_inputs", "=", "outputs_forward", "[", "layer_index", "-", "1", "]", "output", ",", "states_forward", "[", "layer_index", "]", "=", "F", ".", "contrib", ".", "foreach", "(", "self", ".", "forward_layers", "[", "layer_index", "]", ",", "layer_inputs", ",", "states_forward", "[", "layer_index", "]", ")", "outputs_forward", ".", "append", "(", "output", ")", "if", "layer_index", "==", "0", ":", "layer_inputs", "=", "inputs", "else", ":", "layer_inputs", "=", "outputs_backward", "[", "layer_index", "-", "1", "]", "if", "mask", "is", "not", "None", ":", "layer_inputs", "=", "F", ".", "SequenceReverse", "(", "layer_inputs", ",", "sequence_length", "=", "sequence_length", ",", "use_sequence_length", "=", "True", ",", "axis", "=", "0", ")", "else", ":", "layer_inputs", "=", "F", ".", "SequenceReverse", "(", "layer_inputs", ",", "axis", "=", "0", ")", "output", ",", "states_backward", "[", "layer_index", "]", "=", "F", ".", "contrib", ".", "foreach", "(", "self", ".", "backward_layers", "[", "layer_index", "]", ",", "layer_inputs", ",", "states_backward", "[", "layer_index", "]", ")", "if", "mask", "is", "not", "None", ":", "backward_out", "=", "F", ".", "SequenceReverse", "(", "output", ",", "sequence_length", "=", "sequence_length", ",", "use_sequence_length", "=", "True", ",", "axis", "=", "0", ")", "else", ":", "backward_out", "=", "F", ".", "SequenceReverse", "(", "output", ",", "axis", "=", "0", ")", "outputs_backward", ".", "append", "(", "backward_out", ")", "out", "=", "F", ".", "concat", "(", "*", "[", "F", ".", "stack", "(", "*", "outputs_forward", ",", "axis", "=", "0", ")", ",", "F", ".", "stack", "(", "*", "outputs_backward", ",", "axis", "=", "0", ")", "]", ",", "dim", "=", "-", "1", ")", "return", "out", ",", "[", "states_forward", ",", "states_backward", "]" ]
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: states[0] indicates the states used in forward layer, Each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). states[1] indicates the states used in backward layer, Each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). Returns -------- out: NDArray The output data with shape (num_layers, seq_len, batch_size, 2*input_size). [states_forward, states_backward] : List Including: states_forward: The out states from forward layer, which has the same structure with *states[0]*. states_backward: The out states from backward layer, which has the same structure with *states[1]*.
[ "Defines", "the", "forward", "computation", "for", "cache", "cell", ".", "Arguments", "can", "be", "either", ":", "py", ":", "class", ":", "NDArray", "or", ":", "py", ":", "class", ":", "Symbol", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bilm_encoder.py#L132-L205
train
dmlc/gluon-nlp
scripts/natural_language_inference/preprocess.py
main
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']) s2 = read_tokens(cols['sentence2_parse']) label = cols['gold_label'] if label in ('neutral', 'contradiction', 'entailment'): examples.append((s1, s2, label)) with open(args.output, 'w') as fout: for s1, s2, l in examples: fout.write('{}\t{}\t{}\n'.format(' '.join(s1), ' '.join(s2), l))
python
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']) s2 = read_tokens(cols['sentence2_parse']) label = cols['gold_label'] if label in ('neutral', 'contradiction', 'entailment'): examples.append((s1, s2, label)) with open(args.output, 'w') as fout: for s1, s2, l in examples: fout.write('{}\t{}\t{}\n'.format(' '.join(s1), ' '.join(s2), l))
[ "def", "main", "(", "args", ")", ":", "examples", "=", "[", "]", "with", "open", "(", "args", ".", "input", ",", "'r'", ")", "as", "fin", ":", "reader", "=", "csv", ".", "DictReader", "(", "fin", ",", "delimiter", "=", "'\\t'", ")", "for", "cols", "in", "reader", ":", "s1", "=", "read_tokens", "(", "cols", "[", "'sentence1_parse'", "]", ")", "s2", "=", "read_tokens", "(", "cols", "[", "'sentence2_parse'", "]", ")", "label", "=", "cols", "[", "'gold_label'", "]", "if", "label", "in", "(", "'neutral'", ",", "'contradiction'", ",", "'entailment'", ")", ":", "examples", ".", "append", "(", "(", "s1", ",", "s2", ",", "label", ")", ")", "with", "open", "(", "args", ".", "output", ",", "'w'", ")", "as", "fout", ":", "for", "s1", ",", "s2", ",", "l", "in", "examples", ":", "fout", ".", "write", "(", "'{}\\t{}\\t{}\\n'", ".", "format", "(", "' '", ".", "join", "(", "s1", ")", ",", "' '", ".", "join", "(", "s2", ")", ",", "l", ")", ")" ]
Read tokens from the provided parse tree in the SNLI dataset. Illegal examples are removed.
[ "Read", "tokens", "from", "the", "provided", "parse", "tree", "in", "the", "SNLI", "dataset", ".", "Illegal", "examples", "are", "removed", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/preprocess.py#L42-L58
train
dmlc/gluon-nlp
scripts/parsing/common/k_means.py
KMeans._recenter
def _recenter(self): """ one iteration of k-means """ for split_idx in range(len(self._splits)): split = self._splits[split_idx] len_idx = self._split2len_idx[split] if split == self._splits[-1]: continue right_split = self._splits[split_idx + 1] # Try shifting the centroid to the left if len_idx > 0 and self._lengths[len_idx - 1] not in self._split_cntr: new_split = self._lengths[len_idx - 1] left_delta = self._len_cntr[split] * (right_split - new_split) - self._split_cntr[split] * ( split - new_split) if left_delta < 0: self._splits[split_idx] = new_split self._split2len_idx[new_split] = len_idx - 1 del self._split2len_idx[split] self._split_cntr[split] -= self._len_cntr[split] self._split_cntr[right_split] += self._len_cntr[split] self._split_cntr[new_split] = self._split_cntr[split] del self._split_cntr[split] # Try shifting the centroid to the right elif len_idx < len(self._lengths) - 2 and self._lengths[len_idx + 1] not in self._split_cntr: new_split = self._lengths[len_idx + 1] right_delta = self._split_cntr[split] * (new_split - split) - self._len_cntr[split] * ( new_split - split) if right_delta <= 0: self._splits[split_idx] = new_split self._split2len_idx[new_split] = len_idx + 1 del self._split2len_idx[split] self._split_cntr[split] += self._len_cntr[split] self._split_cntr[right_split] -= self._len_cntr[split] self._split_cntr[new_split] = self._split_cntr[split] del self._split_cntr[split]
python
def _recenter(self): """ one iteration of k-means """ for split_idx in range(len(self._splits)): split = self._splits[split_idx] len_idx = self._split2len_idx[split] if split == self._splits[-1]: continue right_split = self._splits[split_idx + 1] # Try shifting the centroid to the left if len_idx > 0 and self._lengths[len_idx - 1] not in self._split_cntr: new_split = self._lengths[len_idx - 1] left_delta = self._len_cntr[split] * (right_split - new_split) - self._split_cntr[split] * ( split - new_split) if left_delta < 0: self._splits[split_idx] = new_split self._split2len_idx[new_split] = len_idx - 1 del self._split2len_idx[split] self._split_cntr[split] -= self._len_cntr[split] self._split_cntr[right_split] += self._len_cntr[split] self._split_cntr[new_split] = self._split_cntr[split] del self._split_cntr[split] # Try shifting the centroid to the right elif len_idx < len(self._lengths) - 2 and self._lengths[len_idx + 1] not in self._split_cntr: new_split = self._lengths[len_idx + 1] right_delta = self._split_cntr[split] * (new_split - split) - self._len_cntr[split] * ( new_split - split) if right_delta <= 0: self._splits[split_idx] = new_split self._split2len_idx[new_split] = len_idx + 1 del self._split2len_idx[split] self._split_cntr[split] += self._len_cntr[split] self._split_cntr[right_split] -= self._len_cntr[split] self._split_cntr[new_split] = self._split_cntr[split] del self._split_cntr[split]
[ "def", "_recenter", "(", "self", ")", ":", "for", "split_idx", "in", "range", "(", "len", "(", "self", ".", "_splits", ")", ")", ":", "split", "=", "self", ".", "_splits", "[", "split_idx", "]", "len_idx", "=", "self", ".", "_split2len_idx", "[", "split", "]", "if", "split", "==", "self", ".", "_splits", "[", "-", "1", "]", ":", "continue", "right_split", "=", "self", ".", "_splits", "[", "split_idx", "+", "1", "]", "# Try shifting the centroid to the left", "if", "len_idx", ">", "0", "and", "self", ".", "_lengths", "[", "len_idx", "-", "1", "]", "not", "in", "self", ".", "_split_cntr", ":", "new_split", "=", "self", ".", "_lengths", "[", "len_idx", "-", "1", "]", "left_delta", "=", "self", ".", "_len_cntr", "[", "split", "]", "*", "(", "right_split", "-", "new_split", ")", "-", "self", ".", "_split_cntr", "[", "split", "]", "*", "(", "split", "-", "new_split", ")", "if", "left_delta", "<", "0", ":", "self", ".", "_splits", "[", "split_idx", "]", "=", "new_split", "self", ".", "_split2len_idx", "[", "new_split", "]", "=", "len_idx", "-", "1", "del", "self", ".", "_split2len_idx", "[", "split", "]", "self", ".", "_split_cntr", "[", "split", "]", "-=", "self", ".", "_len_cntr", "[", "split", "]", "self", ".", "_split_cntr", "[", "right_split", "]", "+=", "self", ".", "_len_cntr", "[", "split", "]", "self", ".", "_split_cntr", "[", "new_split", "]", "=", "self", ".", "_split_cntr", "[", "split", "]", "del", "self", ".", "_split_cntr", "[", "split", "]", "# Try shifting the centroid to the right", "elif", "len_idx", "<", "len", "(", "self", ".", "_lengths", ")", "-", "2", "and", "self", ".", "_lengths", "[", "len_idx", "+", "1", "]", "not", "in", "self", ".", "_split_cntr", ":", "new_split", "=", "self", ".", "_lengths", "[", "len_idx", "+", "1", "]", "right_delta", "=", "self", ".", "_split_cntr", "[", "split", "]", "*", "(", "new_split", "-", "split", ")", "-", "self", ".", "_len_cntr", "[", "split", "]", "*", "(", "new_split", "-", "split", ")", "if", "right_delta", "<=", "0", ":", "self", ".", "_splits", "[", "split_idx", "]", "=", "new_split", "self", ".", "_split2len_idx", "[", "new_split", "]", "=", "len_idx", "+", "1", "del", "self", ".", "_split2len_idx", "[", "split", "]", "self", ".", "_split_cntr", "[", "split", "]", "+=", "self", ".", "_len_cntr", "[", "split", "]", "self", ".", "_split_cntr", "[", "right_split", "]", "-=", "self", ".", "_len_cntr", "[", "split", "]", "self", ".", "_split_cntr", "[", "new_split", "]", "=", "self", ".", "_split_cntr", "[", "split", "]", "del", "self", ".", "_split_cntr", "[", "split", "]" ]
one iteration of k-means
[ "one", "iteration", "of", "k", "-", "means" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/k_means.py#L108-L145
train
dmlc/gluon-nlp
scripts/parsing/common/k_means.py
KMeans._reindex
def _reindex(self): """ Index every sentence into a cluster """ self._len2split_idx = {} last_split = -1 for split_idx, split in enumerate(self._splits): self._len2split_idx.update( dict(list(zip(list(range(last_split + 1, split)), [split_idx] * (split - (last_split + 1))))))
python
def _reindex(self): """ Index every sentence into a cluster """ self._len2split_idx = {} last_split = -1 for split_idx, split in enumerate(self._splits): self._len2split_idx.update( dict(list(zip(list(range(last_split + 1, split)), [split_idx] * (split - (last_split + 1))))))
[ "def", "_reindex", "(", "self", ")", ":", "self", ".", "_len2split_idx", "=", "{", "}", "last_split", "=", "-", "1", "for", "split_idx", ",", "split", "in", "enumerate", "(", "self", ".", "_splits", ")", ":", "self", ".", "_len2split_idx", ".", "update", "(", "dict", "(", "list", "(", "zip", "(", "list", "(", "range", "(", "last_split", "+", "1", ",", "split", ")", ")", ",", "[", "split_idx", "]", "*", "(", "split", "-", "(", "last_split", "+", "1", ")", ")", ")", ")", ")", ")" ]
Index every sentence into a cluster
[ "Index", "every", "sentence", "into", "a", "cluster" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/k_means.py#L147-L155
train
dmlc/gluon-nlp
scripts/machine_translation/gnmt.py
get_gnmt_encoder_decoder
def get_gnmt_encoder_decoder(cell_type='lstm', attention_cell='scaled_luong', num_layers=2, num_bi_layers=1, hidden_size=128, dropout=0.0, use_residual=False, i2h_weight_initializer=None, h2h_weight_initializer=None, i2h_bias_initializer=mx.init.LSTMBias(forget_bias=1.0), h2h_bias_initializer='zeros', prefix='gnmt_', params=None): """Build a pair of GNMT encoder/decoder Parameters ---------- cell_type : str or type attention_cell : str or AttentionCell num_layers : int num_bi_layers : int hidden_size : int dropout : float use_residual : bool i2h_weight_initializer : mx.init.Initializer or None h2h_weight_initializer : mx.init.Initializer or None i2h_bias_initializer : mx.init.Initializer or None h2h_bias_initializer : mx.init.Initializer or None prefix : str, default 'gnmt_' Prefix for name of `Block`s. params : Parameter or None Container for weight sharing between cells. Created if `None`. Returns ------- encoder : GNMTEncoder decoder : GNMTDecoder """ encoder = GNMTEncoder(cell_type=cell_type, num_layers=num_layers, num_bi_layers=num_bi_layers, hidden_size=hidden_size, dropout=dropout, use_residual=use_residual, i2h_weight_initializer=i2h_weight_initializer, h2h_weight_initializer=h2h_weight_initializer, i2h_bias_initializer=i2h_bias_initializer, h2h_bias_initializer=h2h_bias_initializer, prefix=prefix + 'enc_', params=params) decoder = GNMTDecoder(cell_type=cell_type, attention_cell=attention_cell, num_layers=num_layers, hidden_size=hidden_size, dropout=dropout, use_residual=use_residual, i2h_weight_initializer=i2h_weight_initializer, h2h_weight_initializer=h2h_weight_initializer, i2h_bias_initializer=i2h_bias_initializer, h2h_bias_initializer=h2h_bias_initializer, prefix=prefix + 'dec_', params=params) return encoder, decoder
python
def get_gnmt_encoder_decoder(cell_type='lstm', attention_cell='scaled_luong', num_layers=2, num_bi_layers=1, hidden_size=128, dropout=0.0, use_residual=False, i2h_weight_initializer=None, h2h_weight_initializer=None, i2h_bias_initializer=mx.init.LSTMBias(forget_bias=1.0), h2h_bias_initializer='zeros', prefix='gnmt_', params=None): """Build a pair of GNMT encoder/decoder Parameters ---------- cell_type : str or type attention_cell : str or AttentionCell num_layers : int num_bi_layers : int hidden_size : int dropout : float use_residual : bool i2h_weight_initializer : mx.init.Initializer or None h2h_weight_initializer : mx.init.Initializer or None i2h_bias_initializer : mx.init.Initializer or None h2h_bias_initializer : mx.init.Initializer or None prefix : str, default 'gnmt_' Prefix for name of `Block`s. params : Parameter or None Container for weight sharing between cells. Created if `None`. Returns ------- encoder : GNMTEncoder decoder : GNMTDecoder """ encoder = GNMTEncoder(cell_type=cell_type, num_layers=num_layers, num_bi_layers=num_bi_layers, hidden_size=hidden_size, dropout=dropout, use_residual=use_residual, i2h_weight_initializer=i2h_weight_initializer, h2h_weight_initializer=h2h_weight_initializer, i2h_bias_initializer=i2h_bias_initializer, h2h_bias_initializer=h2h_bias_initializer, prefix=prefix + 'enc_', params=params) decoder = GNMTDecoder(cell_type=cell_type, attention_cell=attention_cell, num_layers=num_layers, hidden_size=hidden_size, dropout=dropout, use_residual=use_residual, i2h_weight_initializer=i2h_weight_initializer, h2h_weight_initializer=h2h_weight_initializer, i2h_bias_initializer=i2h_bias_initializer, h2h_bias_initializer=h2h_bias_initializer, prefix=prefix + 'dec_', params=params) return encoder, decoder
[ "def", "get_gnmt_encoder_decoder", "(", "cell_type", "=", "'lstm'", ",", "attention_cell", "=", "'scaled_luong'", ",", "num_layers", "=", "2", ",", "num_bi_layers", "=", "1", ",", "hidden_size", "=", "128", ",", "dropout", "=", "0.0", ",", "use_residual", "=", "False", ",", "i2h_weight_initializer", "=", "None", ",", "h2h_weight_initializer", "=", "None", ",", "i2h_bias_initializer", "=", "mx", ".", "init", ".", "LSTMBias", "(", "forget_bias", "=", "1.0", ")", ",", "h2h_bias_initializer", "=", "'zeros'", ",", "prefix", "=", "'gnmt_'", ",", "params", "=", "None", ")", ":", "encoder", "=", "GNMTEncoder", "(", "cell_type", "=", "cell_type", ",", "num_layers", "=", "num_layers", ",", "num_bi_layers", "=", "num_bi_layers", ",", "hidden_size", "=", "hidden_size", ",", "dropout", "=", "dropout", ",", "use_residual", "=", "use_residual", ",", "i2h_weight_initializer", "=", "i2h_weight_initializer", ",", "h2h_weight_initializer", "=", "h2h_weight_initializer", ",", "i2h_bias_initializer", "=", "i2h_bias_initializer", ",", "h2h_bias_initializer", "=", "h2h_bias_initializer", ",", "prefix", "=", "prefix", "+", "'enc_'", ",", "params", "=", "params", ")", "decoder", "=", "GNMTDecoder", "(", "cell_type", "=", "cell_type", ",", "attention_cell", "=", "attention_cell", ",", "num_layers", "=", "num_layers", ",", "hidden_size", "=", "hidden_size", ",", "dropout", "=", "dropout", ",", "use_residual", "=", "use_residual", ",", "i2h_weight_initializer", "=", "i2h_weight_initializer", ",", "h2h_weight_initializer", "=", "h2h_weight_initializer", ",", "i2h_bias_initializer", "=", "i2h_bias_initializer", ",", "h2h_bias_initializer", "=", "h2h_bias_initializer", ",", "prefix", "=", "prefix", "+", "'dec_'", ",", "params", "=", "params", ")", "return", "encoder", ",", "decoder" ]
Build a pair of GNMT encoder/decoder Parameters ---------- cell_type : str or type attention_cell : str or AttentionCell num_layers : int num_bi_layers : int hidden_size : int dropout : float use_residual : bool i2h_weight_initializer : mx.init.Initializer or None h2h_weight_initializer : mx.init.Initializer or None i2h_bias_initializer : mx.init.Initializer or None h2h_bias_initializer : mx.init.Initializer or None prefix : str, default 'gnmt_' Prefix for name of `Block`s. params : Parameter or None Container for weight sharing between cells. Created if `None`. Returns ------- encoder : GNMTEncoder decoder : GNMTDecoder
[ "Build", "a", "pair", "of", "GNMT", "encoder", "/", "decoder" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/gnmt.py#L407-L455
train
dmlc/gluon-nlp
scripts/machine_translation/gnmt.py
GNMTDecoder.init_state_from_encoder
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None): """Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder states, includes: - rnn_states : NDArray - attention_vec : NDArray - mem_value : NDArray - mem_masks : NDArray, optional """ mem_value, rnn_states = encoder_outputs batch_size, _, mem_size = mem_value.shape attention_vec = mx.nd.zeros(shape=(batch_size, mem_size), ctx=mem_value.context) decoder_states = [rnn_states, attention_vec, mem_value] mem_length = mem_value.shape[1] if encoder_valid_length is not None: mem_masks = mx.nd.broadcast_lesser( mx.nd.arange(mem_length, ctx=encoder_valid_length.context).reshape((1, -1)), encoder_valid_length.reshape((-1, 1))) decoder_states.append(mem_masks) return decoder_states
python
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None): """Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder states, includes: - rnn_states : NDArray - attention_vec : NDArray - mem_value : NDArray - mem_masks : NDArray, optional """ mem_value, rnn_states = encoder_outputs batch_size, _, mem_size = mem_value.shape attention_vec = mx.nd.zeros(shape=(batch_size, mem_size), ctx=mem_value.context) decoder_states = [rnn_states, attention_vec, mem_value] mem_length = mem_value.shape[1] if encoder_valid_length is not None: mem_masks = mx.nd.broadcast_lesser( mx.nd.arange(mem_length, ctx=encoder_valid_length.context).reshape((1, -1)), encoder_valid_length.reshape((-1, 1))) decoder_states.append(mem_masks) return decoder_states
[ "def", "init_state_from_encoder", "(", "self", ",", "encoder_outputs", ",", "encoder_valid_length", "=", "None", ")", ":", "mem_value", ",", "rnn_states", "=", "encoder_outputs", "batch_size", ",", "_", ",", "mem_size", "=", "mem_value", ".", "shape", "attention_vec", "=", "mx", ".", "nd", ".", "zeros", "(", "shape", "=", "(", "batch_size", ",", "mem_size", ")", ",", "ctx", "=", "mem_value", ".", "context", ")", "decoder_states", "=", "[", "rnn_states", ",", "attention_vec", ",", "mem_value", "]", "mem_length", "=", "mem_value", ".", "shape", "[", "1", "]", "if", "encoder_valid_length", "is", "not", "None", ":", "mem_masks", "=", "mx", ".", "nd", ".", "broadcast_lesser", "(", "mx", ".", "nd", ".", "arange", "(", "mem_length", ",", "ctx", "=", "encoder_valid_length", ".", "context", ")", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", ",", "encoder_valid_length", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ")", "decoder_states", ".", "append", "(", "mem_masks", ")", "return", "decoder_states" ]
Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder states, includes: - rnn_states : NDArray - attention_vec : NDArray - mem_value : NDArray - mem_masks : NDArray, optional
[ "Initialize", "the", "state", "from", "the", "encoder", "outputs", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/gnmt.py#L224-L252
train
dmlc/gluon-nlp
scripts/machine_translation/gnmt.py
GNMTDecoder.decode_seq
def decode_seq(self, inputs, states, valid_length=None): """Decode the decoder inputs. This function is only used for training. Parameters ---------- inputs : NDArray, Shape (batch_size, length, C_in) states : list of NDArrays or None Initial states. The list of initial decoder states valid_length : NDArray or None Valid lengths of each sequence. This is usually used when part of sequence has been padded. Shape (batch_size,) Returns ------- output : NDArray, Shape (batch_size, length, C_out) states : list The decoder states, includes: - rnn_states : NDArray - attention_vec : NDArray - mem_value : NDArray - mem_masks : NDArray, optional additional_outputs : list Either be an empty list or contains the attention weights in this step. The attention weights will have shape (batch_size, length, mem_length) or (batch_size, num_heads, length, mem_length) """ length = inputs.shape[1] output = [] additional_outputs = [] inputs = _as_list(mx.nd.split(inputs, num_outputs=length, axis=1, squeeze_axis=True)) rnn_states_l = [] attention_output_l = [] fixed_states = states[2:] for i in range(length): ele_output, states, ele_additional_outputs = self.forward(inputs[i], states) rnn_states_l.append(states[0]) attention_output_l.append(states[1]) output.append(ele_output) additional_outputs.extend(ele_additional_outputs) output = mx.nd.stack(*output, axis=1) if valid_length is not None: states = [_nested_sequence_last(rnn_states_l, valid_length), _nested_sequence_last(attention_output_l, valid_length)] + fixed_states output = mx.nd.SequenceMask(output, sequence_length=valid_length, use_sequence_length=True, axis=1) if self._output_attention: additional_outputs = [mx.nd.concat(*additional_outputs, dim=-2)] return output, states, additional_outputs
python
def decode_seq(self, inputs, states, valid_length=None): """Decode the decoder inputs. This function is only used for training. Parameters ---------- inputs : NDArray, Shape (batch_size, length, C_in) states : list of NDArrays or None Initial states. The list of initial decoder states valid_length : NDArray or None Valid lengths of each sequence. This is usually used when part of sequence has been padded. Shape (batch_size,) Returns ------- output : NDArray, Shape (batch_size, length, C_out) states : list The decoder states, includes: - rnn_states : NDArray - attention_vec : NDArray - mem_value : NDArray - mem_masks : NDArray, optional additional_outputs : list Either be an empty list or contains the attention weights in this step. The attention weights will have shape (batch_size, length, mem_length) or (batch_size, num_heads, length, mem_length) """ length = inputs.shape[1] output = [] additional_outputs = [] inputs = _as_list(mx.nd.split(inputs, num_outputs=length, axis=1, squeeze_axis=True)) rnn_states_l = [] attention_output_l = [] fixed_states = states[2:] for i in range(length): ele_output, states, ele_additional_outputs = self.forward(inputs[i], states) rnn_states_l.append(states[0]) attention_output_l.append(states[1]) output.append(ele_output) additional_outputs.extend(ele_additional_outputs) output = mx.nd.stack(*output, axis=1) if valid_length is not None: states = [_nested_sequence_last(rnn_states_l, valid_length), _nested_sequence_last(attention_output_l, valid_length)] + fixed_states output = mx.nd.SequenceMask(output, sequence_length=valid_length, use_sequence_length=True, axis=1) if self._output_attention: additional_outputs = [mx.nd.concat(*additional_outputs, dim=-2)] return output, states, additional_outputs
[ "def", "decode_seq", "(", "self", ",", "inputs", ",", "states", ",", "valid_length", "=", "None", ")", ":", "length", "=", "inputs", ".", "shape", "[", "1", "]", "output", "=", "[", "]", "additional_outputs", "=", "[", "]", "inputs", "=", "_as_list", "(", "mx", ".", "nd", ".", "split", "(", "inputs", ",", "num_outputs", "=", "length", ",", "axis", "=", "1", ",", "squeeze_axis", "=", "True", ")", ")", "rnn_states_l", "=", "[", "]", "attention_output_l", "=", "[", "]", "fixed_states", "=", "states", "[", "2", ":", "]", "for", "i", "in", "range", "(", "length", ")", ":", "ele_output", ",", "states", ",", "ele_additional_outputs", "=", "self", ".", "forward", "(", "inputs", "[", "i", "]", ",", "states", ")", "rnn_states_l", ".", "append", "(", "states", "[", "0", "]", ")", "attention_output_l", ".", "append", "(", "states", "[", "1", "]", ")", "output", ".", "append", "(", "ele_output", ")", "additional_outputs", ".", "extend", "(", "ele_additional_outputs", ")", "output", "=", "mx", ".", "nd", ".", "stack", "(", "*", "output", ",", "axis", "=", "1", ")", "if", "valid_length", "is", "not", "None", ":", "states", "=", "[", "_nested_sequence_last", "(", "rnn_states_l", ",", "valid_length", ")", ",", "_nested_sequence_last", "(", "attention_output_l", ",", "valid_length", ")", "]", "+", "fixed_states", "output", "=", "mx", ".", "nd", ".", "SequenceMask", "(", "output", ",", "sequence_length", "=", "valid_length", ",", "use_sequence_length", "=", "True", ",", "axis", "=", "1", ")", "if", "self", ".", "_output_attention", ":", "additional_outputs", "=", "[", "mx", ".", "nd", ".", "concat", "(", "*", "additional_outputs", ",", "dim", "=", "-", "2", ")", "]", "return", "output", ",", "states", ",", "additional_outputs" ]
Decode the decoder inputs. This function is only used for training. Parameters ---------- inputs : NDArray, Shape (batch_size, length, C_in) states : list of NDArrays or None Initial states. The list of initial decoder states valid_length : NDArray or None Valid lengths of each sequence. This is usually used when part of sequence has been padded. Shape (batch_size,) Returns ------- output : NDArray, Shape (batch_size, length, C_out) states : list The decoder states, includes: - rnn_states : NDArray - attention_vec : NDArray - mem_value : NDArray - mem_masks : NDArray, optional additional_outputs : list Either be an empty list or contains the attention weights in this step. The attention weights will have shape (batch_size, length, mem_length) or (batch_size, num_heads, length, mem_length)
[ "Decode", "the", "decoder", "inputs", ".", "This", "function", "is", "only", "used", "for", "training", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/gnmt.py#L254-L304
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
transform
def transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, do_pad=True): """Transform instance to inputs for MLM and NSP.""" pad = tokenizer.convert_tokens_to_ids(['[PAD]'])[0] input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) input_mask = [1] * len(input_ids) segment_ids = list(instance.segment_ids) assert len(input_ids) <= max_seq_length valid_lengths = len(input_ids) masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = tokenizer.convert_tokens_to_ids( instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) masked_lm_valid_lengths = len(masked_lm_ids) if do_pad: while len(input_ids) < max_seq_length: input_ids.append(pad) # Padding index MUST be defined to 0 on input_mask, segment_ids input_mask.append(0) segment_ids.append(0) while len(masked_lm_positions) < max_predictions_per_seq: masked_lm_positions.append(0) masked_lm_ids.append(pad) masked_lm_weights.append(0.0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length next_sentence_label = 1 if instance.is_random_next else 0 features = {} features['input_ids'] = input_ids features['input_mask'] = input_mask features['segment_ids'] = segment_ids features['masked_lm_positions'] = masked_lm_positions features['masked_lm_ids'] = masked_lm_ids features['segment_a_lengths'] = [instance.segment_a_lengths] features['segment_b_lengths'] = [instance.segment_b_lengths] features['masked_lm_ids'] = masked_lm_ids features['masked_lm_weights'] = masked_lm_weights features['next_sentence_labels'] = [next_sentence_label] features['valid_lengths'] = [valid_lengths] features['masked_lm_valid_lengths'] = [masked_lm_valid_lengths] return features
python
def transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, do_pad=True): """Transform instance to inputs for MLM and NSP.""" pad = tokenizer.convert_tokens_to_ids(['[PAD]'])[0] input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) input_mask = [1] * len(input_ids) segment_ids = list(instance.segment_ids) assert len(input_ids) <= max_seq_length valid_lengths = len(input_ids) masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = tokenizer.convert_tokens_to_ids( instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) masked_lm_valid_lengths = len(masked_lm_ids) if do_pad: while len(input_ids) < max_seq_length: input_ids.append(pad) # Padding index MUST be defined to 0 on input_mask, segment_ids input_mask.append(0) segment_ids.append(0) while len(masked_lm_positions) < max_predictions_per_seq: masked_lm_positions.append(0) masked_lm_ids.append(pad) masked_lm_weights.append(0.0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length next_sentence_label = 1 if instance.is_random_next else 0 features = {} features['input_ids'] = input_ids features['input_mask'] = input_mask features['segment_ids'] = segment_ids features['masked_lm_positions'] = masked_lm_positions features['masked_lm_ids'] = masked_lm_ids features['segment_a_lengths'] = [instance.segment_a_lengths] features['segment_b_lengths'] = [instance.segment_b_lengths] features['masked_lm_ids'] = masked_lm_ids features['masked_lm_weights'] = masked_lm_weights features['next_sentence_labels'] = [next_sentence_label] features['valid_lengths'] = [valid_lengths] features['masked_lm_valid_lengths'] = [masked_lm_valid_lengths] return features
[ "def", "transform", "(", "instance", ",", "tokenizer", ",", "max_seq_length", ",", "max_predictions_per_seq", ",", "do_pad", "=", "True", ")", ":", "pad", "=", "tokenizer", ".", "convert_tokens_to_ids", "(", "[", "'[PAD]'", "]", ")", "[", "0", "]", "input_ids", "=", "tokenizer", ".", "convert_tokens_to_ids", "(", "instance", ".", "tokens", ")", "input_mask", "=", "[", "1", "]", "*", "len", "(", "input_ids", ")", "segment_ids", "=", "list", "(", "instance", ".", "segment_ids", ")", "assert", "len", "(", "input_ids", ")", "<=", "max_seq_length", "valid_lengths", "=", "len", "(", "input_ids", ")", "masked_lm_positions", "=", "list", "(", "instance", ".", "masked_lm_positions", ")", "masked_lm_ids", "=", "tokenizer", ".", "convert_tokens_to_ids", "(", "instance", ".", "masked_lm_labels", ")", "masked_lm_weights", "=", "[", "1.0", "]", "*", "len", "(", "masked_lm_ids", ")", "masked_lm_valid_lengths", "=", "len", "(", "masked_lm_ids", ")", "if", "do_pad", ":", "while", "len", "(", "input_ids", ")", "<", "max_seq_length", ":", "input_ids", ".", "append", "(", "pad", ")", "# Padding index MUST be defined to 0 on input_mask, segment_ids", "input_mask", ".", "append", "(", "0", ")", "segment_ids", ".", "append", "(", "0", ")", "while", "len", "(", "masked_lm_positions", ")", "<", "max_predictions_per_seq", ":", "masked_lm_positions", ".", "append", "(", "0", ")", "masked_lm_ids", ".", "append", "(", "pad", ")", "masked_lm_weights", ".", "append", "(", "0.0", ")", "assert", "len", "(", "input_ids", ")", "==", "max_seq_length", "assert", "len", "(", "input_mask", ")", "==", "max_seq_length", "assert", "len", "(", "segment_ids", ")", "==", "max_seq_length", "next_sentence_label", "=", "1", "if", "instance", ".", "is_random_next", "else", "0", "features", "=", "{", "}", "features", "[", "'input_ids'", "]", "=", "input_ids", "features", "[", "'input_mask'", "]", "=", "input_mask", "features", "[", "'segment_ids'", "]", "=", "segment_ids", "features", "[", "'masked_lm_positions'", "]", "=", "masked_lm_positions", "features", "[", "'masked_lm_ids'", "]", "=", "masked_lm_ids", "features", "[", "'segment_a_lengths'", "]", "=", "[", "instance", ".", "segment_a_lengths", "]", "features", "[", "'segment_b_lengths'", "]", "=", "[", "instance", ".", "segment_b_lengths", "]", "features", "[", "'masked_lm_ids'", "]", "=", "masked_lm_ids", "features", "[", "'masked_lm_weights'", "]", "=", "masked_lm_weights", "features", "[", "'next_sentence_labels'", "]", "=", "[", "next_sentence_label", "]", "features", "[", "'valid_lengths'", "]", "=", "[", "valid_lengths", "]", "features", "[", "'masked_lm_valid_lengths'", "]", "=", "[", "masked_lm_valid_lengths", "]", "return", "features" ]
Transform instance to inputs for MLM and NSP.
[ "Transform", "instance", "to", "inputs", "for", "MLM", "and", "NSP", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L163-L208
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
write_to_files_np
def write_to_files_np(features, tokenizer, max_seq_length, max_predictions_per_seq, output_files): # pylint: disable=unused-argument """Write to numpy files from `TrainingInstance`s.""" next_sentence_labels = [] valid_lengths = [] assert len(output_files) == 1, 'numpy format only support single output file' output_file = output_files[0] (input_ids, segment_ids, masked_lm_positions, masked_lm_ids, masked_lm_weights, next_sentence_labels, valid_lengths) = features total_written = len(next_sentence_labels) # store variable length numpy array object directly. outputs = collections.OrderedDict() outputs['input_ids'] = np.array(input_ids, dtype=object) outputs['segment_ids'] = np.array(segment_ids, dtype=object) outputs['masked_lm_positions'] = np.array(masked_lm_positions, dtype=object) outputs['masked_lm_ids'] = np.array(masked_lm_ids, dtype=object) outputs['masked_lm_weights'] = np.array(masked_lm_weights, dtype=object) outputs['next_sentence_labels'] = np.array(next_sentence_labels, dtype='int32') outputs['valid_lengths'] = np.array(valid_lengths, dtype='int32') np.savez_compressed(output_file, **outputs) logging.info('Wrote %d total instances', total_written)
python
def write_to_files_np(features, tokenizer, max_seq_length, max_predictions_per_seq, output_files): # pylint: disable=unused-argument """Write to numpy files from `TrainingInstance`s.""" next_sentence_labels = [] valid_lengths = [] assert len(output_files) == 1, 'numpy format only support single output file' output_file = output_files[0] (input_ids, segment_ids, masked_lm_positions, masked_lm_ids, masked_lm_weights, next_sentence_labels, valid_lengths) = features total_written = len(next_sentence_labels) # store variable length numpy array object directly. outputs = collections.OrderedDict() outputs['input_ids'] = np.array(input_ids, dtype=object) outputs['segment_ids'] = np.array(segment_ids, dtype=object) outputs['masked_lm_positions'] = np.array(masked_lm_positions, dtype=object) outputs['masked_lm_ids'] = np.array(masked_lm_ids, dtype=object) outputs['masked_lm_weights'] = np.array(masked_lm_weights, dtype=object) outputs['next_sentence_labels'] = np.array(next_sentence_labels, dtype='int32') outputs['valid_lengths'] = np.array(valid_lengths, dtype='int32') np.savez_compressed(output_file, **outputs) logging.info('Wrote %d total instances', total_written)
[ "def", "write_to_files_np", "(", "features", ",", "tokenizer", ",", "max_seq_length", ",", "max_predictions_per_seq", ",", "output_files", ")", ":", "# pylint: disable=unused-argument", "next_sentence_labels", "=", "[", "]", "valid_lengths", "=", "[", "]", "assert", "len", "(", "output_files", ")", "==", "1", ",", "'numpy format only support single output file'", "output_file", "=", "output_files", "[", "0", "]", "(", "input_ids", ",", "segment_ids", ",", "masked_lm_positions", ",", "masked_lm_ids", ",", "masked_lm_weights", ",", "next_sentence_labels", ",", "valid_lengths", ")", "=", "features", "total_written", "=", "len", "(", "next_sentence_labels", ")", "# store variable length numpy array object directly.", "outputs", "=", "collections", ".", "OrderedDict", "(", ")", "outputs", "[", "'input_ids'", "]", "=", "np", ".", "array", "(", "input_ids", ",", "dtype", "=", "object", ")", "outputs", "[", "'segment_ids'", "]", "=", "np", ".", "array", "(", "segment_ids", ",", "dtype", "=", "object", ")", "outputs", "[", "'masked_lm_positions'", "]", "=", "np", ".", "array", "(", "masked_lm_positions", ",", "dtype", "=", "object", ")", "outputs", "[", "'masked_lm_ids'", "]", "=", "np", ".", "array", "(", "masked_lm_ids", ",", "dtype", "=", "object", ")", "outputs", "[", "'masked_lm_weights'", "]", "=", "np", ".", "array", "(", "masked_lm_weights", ",", "dtype", "=", "object", ")", "outputs", "[", "'next_sentence_labels'", "]", "=", "np", ".", "array", "(", "next_sentence_labels", ",", "dtype", "=", "'int32'", ")", "outputs", "[", "'valid_lengths'", "]", "=", "np", ".", "array", "(", "valid_lengths", ",", "dtype", "=", "'int32'", ")", "np", ".", "savez_compressed", "(", "output_file", ",", "*", "*", "outputs", ")", "logging", ".", "info", "(", "'Wrote %d total instances'", ",", "total_written", ")" ]
Write to numpy files from `TrainingInstance`s.
[ "Write", "to", "numpy", "files", "from", "TrainingInstance", "s", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L218-L242
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
write_to_files_rec
def write_to_files_rec(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create IndexedRecordIO files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append( mx.recordio.MXIndexedRecordIO( os.path.splitext(output_file)[0] + '.idx', output_file, 'w')) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): features = transform(instance, tokenizer, max_seq_length, max_predictions_per_seq) example = features writers[writer_index].write_idx(inst_index, json.dumps(example).encode('UTF-8')) writer_index = (writer_index + 1) % len(writers) total_written += 1 for writer in writers: writer.close() logging.info('Wrote %d total instances', total_written)
python
def write_to_files_rec(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create IndexedRecordIO files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append( mx.recordio.MXIndexedRecordIO( os.path.splitext(output_file)[0] + '.idx', output_file, 'w')) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): features = transform(instance, tokenizer, max_seq_length, max_predictions_per_seq) example = features writers[writer_index].write_idx(inst_index, json.dumps(example).encode('UTF-8')) writer_index = (writer_index + 1) % len(writers) total_written += 1 for writer in writers: writer.close() logging.info('Wrote %d total instances', total_written)
[ "def", "write_to_files_rec", "(", "instances", ",", "tokenizer", ",", "max_seq_length", ",", "max_predictions_per_seq", ",", "output_files", ")", ":", "writers", "=", "[", "]", "for", "output_file", "in", "output_files", ":", "writers", ".", "append", "(", "mx", ".", "recordio", ".", "MXIndexedRecordIO", "(", "os", ".", "path", ".", "splitext", "(", "output_file", ")", "[", "0", "]", "+", "'.idx'", ",", "output_file", ",", "'w'", ")", ")", "writer_index", "=", "0", "total_written", "=", "0", "for", "(", "inst_index", ",", "instance", ")", "in", "enumerate", "(", "instances", ")", ":", "features", "=", "transform", "(", "instance", ",", "tokenizer", ",", "max_seq_length", ",", "max_predictions_per_seq", ")", "example", "=", "features", "writers", "[", "writer_index", "]", ".", "write_idx", "(", "inst_index", ",", "json", ".", "dumps", "(", "example", ")", ".", "encode", "(", "'UTF-8'", ")", ")", "writer_index", "=", "(", "writer_index", "+", "1", ")", "%", "len", "(", "writers", ")", "total_written", "+=", "1", "for", "writer", "in", "writers", ":", "writer", ".", "close", "(", ")", "logging", ".", "info", "(", "'Wrote %d total instances'", ",", "total_written", ")" ]
Create IndexedRecordIO files from `TrainingInstance`s.
[ "Create", "IndexedRecordIO", "files", "from", "TrainingInstance", "s", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L244-L266
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
create_training_instances
def create_training_instances(x): """Create `TrainingInstance`s from raw text.""" (input_files, out, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng) = x time_start = time.time() logging.info('Processing %s', input_files) all_documents = [[]] # Input file format: # (1) One sentence per line. These should ideally be actual sentences, not # entire paragraphs or arbitrary spans of text. (Because we use the # sentence boundaries for the "next sentence prediction" task). # (2) Blank lines between documents. Document boundaries are needed so # that the "next sentence prediction" task doesn't span between documents. for input_file in input_files: with io.open(input_file, 'r', encoding='UTF-8') as reader: while True: line = reader.readline() if not line: break line = line.strip() # Empty lines are used as document delimiters if not line: all_documents.append([]) tokens = tokenizer(line) if not args.tokenized else line.split(' ') if tokens: all_documents[-1].append(tokens) # Remove empty documents all_documents = [x for x in all_documents if x] rng.shuffle(all_documents) vocab_words = tokenizer.vocab.idx_to_token instances = [] for _ in range(dupe_factor): for document_index in range(len(all_documents)): instances.extend( create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)) rng.shuffle(instances) input_ids = [] segment_ids = [] masked_lm_positions = [] masked_lm_ids = [] masked_lm_weights = [] next_sentence_labels = [] valid_lengths = [] for inst_index, instance in enumerate(instances): feature = transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, False) input_ids.append( np.ascontiguousarray(feature['input_ids'], dtype='int32')) segment_ids.append( np.ascontiguousarray(feature['segment_ids'], dtype='int32')) masked_lm_positions.append( np.ascontiguousarray(feature['masked_lm_positions'], dtype='int32')) masked_lm_ids.append(np.ascontiguousarray(feature['masked_lm_ids'], dtype='int32')) masked_lm_weights.append( np.ascontiguousarray(feature['masked_lm_weights'], dtype='float32')) next_sentence_labels.append(feature['next_sentence_labels'][0]) valid_lengths.append(feature['valid_lengths'][0]) if inst_index < 20: print_example(instance, feature) features = (input_ids, segment_ids, masked_lm_positions, masked_lm_ids, \ masked_lm_weights, next_sentence_labels, valid_lengths) logging.info('*** Writing to output file %s ***', out) if args.format == 'numpy': write_to_files_np(features, tokenizer, args.max_seq_length, args.max_predictions_per_seq, [out]) elif args.format == 'recordio': write_to_files_rec(instances, tokenizer, args.max_seq_length, args.max_predictions_per_seq, [out]) else: raise ValueError('unsupported format: %s'%args.format) time_end = time.time() logging.info('Process %d files took %.1f s', len(input_files), time_end - time_start)
python
def create_training_instances(x): """Create `TrainingInstance`s from raw text.""" (input_files, out, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng) = x time_start = time.time() logging.info('Processing %s', input_files) all_documents = [[]] # Input file format: # (1) One sentence per line. These should ideally be actual sentences, not # entire paragraphs or arbitrary spans of text. (Because we use the # sentence boundaries for the "next sentence prediction" task). # (2) Blank lines between documents. Document boundaries are needed so # that the "next sentence prediction" task doesn't span between documents. for input_file in input_files: with io.open(input_file, 'r', encoding='UTF-8') as reader: while True: line = reader.readline() if not line: break line = line.strip() # Empty lines are used as document delimiters if not line: all_documents.append([]) tokens = tokenizer(line) if not args.tokenized else line.split(' ') if tokens: all_documents[-1].append(tokens) # Remove empty documents all_documents = [x for x in all_documents if x] rng.shuffle(all_documents) vocab_words = tokenizer.vocab.idx_to_token instances = [] for _ in range(dupe_factor): for document_index in range(len(all_documents)): instances.extend( create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)) rng.shuffle(instances) input_ids = [] segment_ids = [] masked_lm_positions = [] masked_lm_ids = [] masked_lm_weights = [] next_sentence_labels = [] valid_lengths = [] for inst_index, instance in enumerate(instances): feature = transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, False) input_ids.append( np.ascontiguousarray(feature['input_ids'], dtype='int32')) segment_ids.append( np.ascontiguousarray(feature['segment_ids'], dtype='int32')) masked_lm_positions.append( np.ascontiguousarray(feature['masked_lm_positions'], dtype='int32')) masked_lm_ids.append(np.ascontiguousarray(feature['masked_lm_ids'], dtype='int32')) masked_lm_weights.append( np.ascontiguousarray(feature['masked_lm_weights'], dtype='float32')) next_sentence_labels.append(feature['next_sentence_labels'][0]) valid_lengths.append(feature['valid_lengths'][0]) if inst_index < 20: print_example(instance, feature) features = (input_ids, segment_ids, masked_lm_positions, masked_lm_ids, \ masked_lm_weights, next_sentence_labels, valid_lengths) logging.info('*** Writing to output file %s ***', out) if args.format == 'numpy': write_to_files_np(features, tokenizer, args.max_seq_length, args.max_predictions_per_seq, [out]) elif args.format == 'recordio': write_to_files_rec(instances, tokenizer, args.max_seq_length, args.max_predictions_per_seq, [out]) else: raise ValueError('unsupported format: %s'%args.format) time_end = time.time() logging.info('Process %d files took %.1f s', len(input_files), time_end - time_start)
[ "def", "create_training_instances", "(", "x", ")", ":", "(", "input_files", ",", "out", ",", "tokenizer", ",", "max_seq_length", ",", "dupe_factor", ",", "short_seq_prob", ",", "masked_lm_prob", ",", "max_predictions_per_seq", ",", "rng", ")", "=", "x", "time_start", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'Processing %s'", ",", "input_files", ")", "all_documents", "=", "[", "[", "]", "]", "# Input file format:", "# (1) One sentence per line. These should ideally be actual sentences, not", "# entire paragraphs or arbitrary spans of text. (Because we use the", "# sentence boundaries for the \"next sentence prediction\" task).", "# (2) Blank lines between documents. Document boundaries are needed so", "# that the \"next sentence prediction\" task doesn't span between documents.", "for", "input_file", "in", "input_files", ":", "with", "io", ".", "open", "(", "input_file", ",", "'r'", ",", "encoding", "=", "'UTF-8'", ")", "as", "reader", ":", "while", "True", ":", "line", "=", "reader", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "line", "=", "line", ".", "strip", "(", ")", "# Empty lines are used as document delimiters", "if", "not", "line", ":", "all_documents", ".", "append", "(", "[", "]", ")", "tokens", "=", "tokenizer", "(", "line", ")", "if", "not", "args", ".", "tokenized", "else", "line", ".", "split", "(", "' '", ")", "if", "tokens", ":", "all_documents", "[", "-", "1", "]", ".", "append", "(", "tokens", ")", "# Remove empty documents", "all_documents", "=", "[", "x", "for", "x", "in", "all_documents", "if", "x", "]", "rng", ".", "shuffle", "(", "all_documents", ")", "vocab_words", "=", "tokenizer", ".", "vocab", ".", "idx_to_token", "instances", "=", "[", "]", "for", "_", "in", "range", "(", "dupe_factor", ")", ":", "for", "document_index", "in", "range", "(", "len", "(", "all_documents", ")", ")", ":", "instances", ".", "extend", "(", "create_instances_from_document", "(", "all_documents", ",", "document_index", ",", "max_seq_length", ",", "short_seq_prob", ",", "masked_lm_prob", ",", "max_predictions_per_seq", ",", "vocab_words", ",", "rng", ")", ")", "rng", ".", "shuffle", "(", "instances", ")", "input_ids", "=", "[", "]", "segment_ids", "=", "[", "]", "masked_lm_positions", "=", "[", "]", "masked_lm_ids", "=", "[", "]", "masked_lm_weights", "=", "[", "]", "next_sentence_labels", "=", "[", "]", "valid_lengths", "=", "[", "]", "for", "inst_index", ",", "instance", "in", "enumerate", "(", "instances", ")", ":", "feature", "=", "transform", "(", "instance", ",", "tokenizer", ",", "max_seq_length", ",", "max_predictions_per_seq", ",", "False", ")", "input_ids", ".", "append", "(", "np", ".", "ascontiguousarray", "(", "feature", "[", "'input_ids'", "]", ",", "dtype", "=", "'int32'", ")", ")", "segment_ids", ".", "append", "(", "np", ".", "ascontiguousarray", "(", "feature", "[", "'segment_ids'", "]", ",", "dtype", "=", "'int32'", ")", ")", "masked_lm_positions", ".", "append", "(", "np", ".", "ascontiguousarray", "(", "feature", "[", "'masked_lm_positions'", "]", ",", "dtype", "=", "'int32'", ")", ")", "masked_lm_ids", ".", "append", "(", "np", ".", "ascontiguousarray", "(", "feature", "[", "'masked_lm_ids'", "]", ",", "dtype", "=", "'int32'", ")", ")", "masked_lm_weights", ".", "append", "(", "np", ".", "ascontiguousarray", "(", "feature", "[", "'masked_lm_weights'", "]", ",", "dtype", "=", "'float32'", ")", ")", "next_sentence_labels", ".", "append", "(", "feature", "[", "'next_sentence_labels'", "]", "[", "0", "]", ")", "valid_lengths", ".", "append", "(", "feature", "[", "'valid_lengths'", "]", "[", "0", "]", ")", "if", "inst_index", "<", "20", ":", "print_example", "(", "instance", ",", "feature", ")", "features", "=", "(", "input_ids", ",", "segment_ids", ",", "masked_lm_positions", ",", "masked_lm_ids", ",", "masked_lm_weights", ",", "next_sentence_labels", ",", "valid_lengths", ")", "logging", ".", "info", "(", "'*** Writing to output file %s ***'", ",", "out", ")", "if", "args", ".", "format", "==", "'numpy'", ":", "write_to_files_np", "(", "features", ",", "tokenizer", ",", "args", ".", "max_seq_length", ",", "args", ".", "max_predictions_per_seq", ",", "[", "out", "]", ")", "elif", "args", ".", "format", "==", "'recordio'", ":", "write_to_files_rec", "(", "instances", ",", "tokenizer", ",", "args", ".", "max_seq_length", ",", "args", ".", "max_predictions_per_seq", ",", "[", "out", "]", ")", "else", ":", "raise", "ValueError", "(", "'unsupported format: %s'", "%", "args", ".", "format", ")", "time_end", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'Process %d files took %.1f s'", ",", "len", "(", "input_files", ")", ",", "time_end", "-", "time_start", ")" ]
Create `TrainingInstance`s from raw text.
[ "Create", "TrainingInstance", "s", "from", "raw", "text", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L269-L351
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
create_instances_from_document
def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[document_index] # Account for [CLS], [SEP], [SEP] max_num_tokens = max_seq_length - 3 # We *usually* want to fill up the entire sequence since we are padding # to `max_seq_length` anyways, so short sequences are generally wasted # computation. However, we *sometimes* # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter # sequences to minimize the mismatch between pre-training and fine-tuning. # The `target_seq_length` is just a rough target however, whereas # `max_seq_length` is a hard limit. target_seq_length = max_num_tokens if rng.random() < short_seq_prob: target_seq_length = rng.randint(2, max_num_tokens) # We DON'T just concatenate all of the tokens from a document into a long # sequence and choose an arbitrary split point because this would make the # next sentence prediction task too easy. Instead, we split the input into # segments "A" and "B" based on the actual "sentences" provided by the user # input. instances = [] current_chunk = [] current_length = 0 i = 0 while i < len(document): # pylint: disable=R1702 segment = document[i] current_chunk.append(segment) current_length += len(segment) if i == len(document) - 1 or current_length >= target_seq_length: if current_chunk: # `a_end` is how many segments from `current_chunk` go into the `A` # (first) sentence. a_end = 1 if len(current_chunk) >= 2: a_end = rng.randint(1, len(current_chunk) - 1) tokens_a = [] for j in range(a_end): tokens_a.extend(current_chunk[j]) tokens_b = [] # Random next is_random_next = False if len(current_chunk) == 1 or rng.random() < 0.5: is_random_next = True target_b_length = target_seq_length - len(tokens_a) # This should rarely go for more than one iteration for large # corpora. However, just to be careful, we try to make sure that # the random document is not the same as the document # we're processing. for _ in range(10): random_document_index = rng.randint( 0, len(all_documents) - 1) if random_document_index != document_index: break random_document = all_documents[random_document_index] random_start = rng.randint(0, len(random_document) - 1) for j in range(random_start, len(random_document)): tokens_b.extend(random_document[j]) if len(tokens_b) >= target_b_length: break # We didn't actually use these segments so we 'put them back' so # they don't go to waste. num_unused_segments = len(current_chunk) - a_end i -= num_unused_segments # Actual next else: is_random_next = False for j in range(a_end, len(current_chunk)): tokens_b.extend(current_chunk[j]) truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) assert len(tokens_a) >= 1 assert len(tokens_b) >= 1 tokens = [] segment_ids = [] tokens.append('[CLS]') segment_ids.append(0) for token in tokens_a: tokens.append(token) segment_ids.append(0) tokens.append('[SEP]') segment_ids.append(0) segment_a_lengths = len(segment_ids) for token in tokens_b: tokens.append(token) segment_ids.append(1) tokens.append('[SEP]') segment_ids.append(1) segment_b_lengths = len(segment_ids) - segment_a_lengths (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng) instance = TrainingInstance( tokens=tokens, segment_ids=segment_ids, is_random_next=is_random_next, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels, segment_a_lengths=segment_a_lengths, segment_b_lengths=segment_b_lengths) instances.append(instance) current_chunk = [] current_length = 0 i += 1 return instances
python
def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[document_index] # Account for [CLS], [SEP], [SEP] max_num_tokens = max_seq_length - 3 # We *usually* want to fill up the entire sequence since we are padding # to `max_seq_length` anyways, so short sequences are generally wasted # computation. However, we *sometimes* # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter # sequences to minimize the mismatch between pre-training and fine-tuning. # The `target_seq_length` is just a rough target however, whereas # `max_seq_length` is a hard limit. target_seq_length = max_num_tokens if rng.random() < short_seq_prob: target_seq_length = rng.randint(2, max_num_tokens) # We DON'T just concatenate all of the tokens from a document into a long # sequence and choose an arbitrary split point because this would make the # next sentence prediction task too easy. Instead, we split the input into # segments "A" and "B" based on the actual "sentences" provided by the user # input. instances = [] current_chunk = [] current_length = 0 i = 0 while i < len(document): # pylint: disable=R1702 segment = document[i] current_chunk.append(segment) current_length += len(segment) if i == len(document) - 1 or current_length >= target_seq_length: if current_chunk: # `a_end` is how many segments from `current_chunk` go into the `A` # (first) sentence. a_end = 1 if len(current_chunk) >= 2: a_end = rng.randint(1, len(current_chunk) - 1) tokens_a = [] for j in range(a_end): tokens_a.extend(current_chunk[j]) tokens_b = [] # Random next is_random_next = False if len(current_chunk) == 1 or rng.random() < 0.5: is_random_next = True target_b_length = target_seq_length - len(tokens_a) # This should rarely go for more than one iteration for large # corpora. However, just to be careful, we try to make sure that # the random document is not the same as the document # we're processing. for _ in range(10): random_document_index = rng.randint( 0, len(all_documents) - 1) if random_document_index != document_index: break random_document = all_documents[random_document_index] random_start = rng.randint(0, len(random_document) - 1) for j in range(random_start, len(random_document)): tokens_b.extend(random_document[j]) if len(tokens_b) >= target_b_length: break # We didn't actually use these segments so we 'put them back' so # they don't go to waste. num_unused_segments = len(current_chunk) - a_end i -= num_unused_segments # Actual next else: is_random_next = False for j in range(a_end, len(current_chunk)): tokens_b.extend(current_chunk[j]) truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) assert len(tokens_a) >= 1 assert len(tokens_b) >= 1 tokens = [] segment_ids = [] tokens.append('[CLS]') segment_ids.append(0) for token in tokens_a: tokens.append(token) segment_ids.append(0) tokens.append('[SEP]') segment_ids.append(0) segment_a_lengths = len(segment_ids) for token in tokens_b: tokens.append(token) segment_ids.append(1) tokens.append('[SEP]') segment_ids.append(1) segment_b_lengths = len(segment_ids) - segment_a_lengths (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng) instance = TrainingInstance( tokens=tokens, segment_ids=segment_ids, is_random_next=is_random_next, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels, segment_a_lengths=segment_a_lengths, segment_b_lengths=segment_b_lengths) instances.append(instance) current_chunk = [] current_length = 0 i += 1 return instances
[ "def", "create_instances_from_document", "(", "all_documents", ",", "document_index", ",", "max_seq_length", ",", "short_seq_prob", ",", "masked_lm_prob", ",", "max_predictions_per_seq", ",", "vocab_words", ",", "rng", ")", ":", "document", "=", "all_documents", "[", "document_index", "]", "# Account for [CLS], [SEP], [SEP]", "max_num_tokens", "=", "max_seq_length", "-", "3", "# We *usually* want to fill up the entire sequence since we are padding", "# to `max_seq_length` anyways, so short sequences are generally wasted", "# computation. However, we *sometimes*", "# (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter", "# sequences to minimize the mismatch between pre-training and fine-tuning.", "# The `target_seq_length` is just a rough target however, whereas", "# `max_seq_length` is a hard limit.", "target_seq_length", "=", "max_num_tokens", "if", "rng", ".", "random", "(", ")", "<", "short_seq_prob", ":", "target_seq_length", "=", "rng", ".", "randint", "(", "2", ",", "max_num_tokens", ")", "# We DON'T just concatenate all of the tokens from a document into a long", "# sequence and choose an arbitrary split point because this would make the", "# next sentence prediction task too easy. Instead, we split the input into", "# segments \"A\" and \"B\" based on the actual \"sentences\" provided by the user", "# input.", "instances", "=", "[", "]", "current_chunk", "=", "[", "]", "current_length", "=", "0", "i", "=", "0", "while", "i", "<", "len", "(", "document", ")", ":", "# pylint: disable=R1702", "segment", "=", "document", "[", "i", "]", "current_chunk", ".", "append", "(", "segment", ")", "current_length", "+=", "len", "(", "segment", ")", "if", "i", "==", "len", "(", "document", ")", "-", "1", "or", "current_length", ">=", "target_seq_length", ":", "if", "current_chunk", ":", "# `a_end` is how many segments from `current_chunk` go into the `A`", "# (first) sentence.", "a_end", "=", "1", "if", "len", "(", "current_chunk", ")", ">=", "2", ":", "a_end", "=", "rng", ".", "randint", "(", "1", ",", "len", "(", "current_chunk", ")", "-", "1", ")", "tokens_a", "=", "[", "]", "for", "j", "in", "range", "(", "a_end", ")", ":", "tokens_a", ".", "extend", "(", "current_chunk", "[", "j", "]", ")", "tokens_b", "=", "[", "]", "# Random next", "is_random_next", "=", "False", "if", "len", "(", "current_chunk", ")", "==", "1", "or", "rng", ".", "random", "(", ")", "<", "0.5", ":", "is_random_next", "=", "True", "target_b_length", "=", "target_seq_length", "-", "len", "(", "tokens_a", ")", "# This should rarely go for more than one iteration for large", "# corpora. However, just to be careful, we try to make sure that", "# the random document is not the same as the document", "# we're processing.", "for", "_", "in", "range", "(", "10", ")", ":", "random_document_index", "=", "rng", ".", "randint", "(", "0", ",", "len", "(", "all_documents", ")", "-", "1", ")", "if", "random_document_index", "!=", "document_index", ":", "break", "random_document", "=", "all_documents", "[", "random_document_index", "]", "random_start", "=", "rng", ".", "randint", "(", "0", ",", "len", "(", "random_document", ")", "-", "1", ")", "for", "j", "in", "range", "(", "random_start", ",", "len", "(", "random_document", ")", ")", ":", "tokens_b", ".", "extend", "(", "random_document", "[", "j", "]", ")", "if", "len", "(", "tokens_b", ")", ">=", "target_b_length", ":", "break", "# We didn't actually use these segments so we 'put them back' so", "# they don't go to waste.", "num_unused_segments", "=", "len", "(", "current_chunk", ")", "-", "a_end", "i", "-=", "num_unused_segments", "# Actual next", "else", ":", "is_random_next", "=", "False", "for", "j", "in", "range", "(", "a_end", ",", "len", "(", "current_chunk", ")", ")", ":", "tokens_b", ".", "extend", "(", "current_chunk", "[", "j", "]", ")", "truncate_seq_pair", "(", "tokens_a", ",", "tokens_b", ",", "max_num_tokens", ",", "rng", ")", "assert", "len", "(", "tokens_a", ")", ">=", "1", "assert", "len", "(", "tokens_b", ")", ">=", "1", "tokens", "=", "[", "]", "segment_ids", "=", "[", "]", "tokens", ".", "append", "(", "'[CLS]'", ")", "segment_ids", ".", "append", "(", "0", ")", "for", "token", "in", "tokens_a", ":", "tokens", ".", "append", "(", "token", ")", "segment_ids", ".", "append", "(", "0", ")", "tokens", ".", "append", "(", "'[SEP]'", ")", "segment_ids", ".", "append", "(", "0", ")", "segment_a_lengths", "=", "len", "(", "segment_ids", ")", "for", "token", "in", "tokens_b", ":", "tokens", ".", "append", "(", "token", ")", "segment_ids", ".", "append", "(", "1", ")", "tokens", ".", "append", "(", "'[SEP]'", ")", "segment_ids", ".", "append", "(", "1", ")", "segment_b_lengths", "=", "len", "(", "segment_ids", ")", "-", "segment_a_lengths", "(", "tokens", ",", "masked_lm_positions", ",", "masked_lm_labels", ")", "=", "create_masked_lm_predictions", "(", "tokens", ",", "masked_lm_prob", ",", "max_predictions_per_seq", ",", "vocab_words", ",", "rng", ")", "instance", "=", "TrainingInstance", "(", "tokens", "=", "tokens", ",", "segment_ids", "=", "segment_ids", ",", "is_random_next", "=", "is_random_next", ",", "masked_lm_positions", "=", "masked_lm_positions", ",", "masked_lm_labels", "=", "masked_lm_labels", ",", "segment_a_lengths", "=", "segment_a_lengths", ",", "segment_b_lengths", "=", "segment_b_lengths", ")", "instances", ".", "append", "(", "instance", ")", "current_chunk", "=", "[", "]", "current_length", "=", "0", "i", "+=", "1", "return", "instances" ]
Creates `TrainingInstance`s for a single document.
[ "Creates", "TrainingInstance", "s", "for", "a", "single", "document", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L354-L472
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
create_masked_lm_predictions
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token in ['[CLS]', '[SEP]']: continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index in cand_indexes: if len(masked_lms) >= num_to_predict: break if index in covered_indexes: continue covered_indexes.add(index) masked_token = None # 80% of the time, replace with [MASK] if rng.random() < 0.8: masked_token = '[MASK]' else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[index] # 10% of the time, replace with random word else: masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels)
python
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token in ['[CLS]', '[SEP]']: continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index in cand_indexes: if len(masked_lms) >= num_to_predict: break if index in covered_indexes: continue covered_indexes.add(index) masked_token = None # 80% of the time, replace with [MASK] if rng.random() < 0.8: masked_token = '[MASK]' else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[index] # 10% of the time, replace with random word else: masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels)
[ "def", "create_masked_lm_predictions", "(", "tokens", ",", "masked_lm_prob", ",", "max_predictions_per_seq", ",", "vocab_words", ",", "rng", ")", ":", "cand_indexes", "=", "[", "]", "for", "(", "i", ",", "token", ")", "in", "enumerate", "(", "tokens", ")", ":", "if", "token", "in", "[", "'[CLS]'", ",", "'[SEP]'", "]", ":", "continue", "cand_indexes", ".", "append", "(", "i", ")", "rng", ".", "shuffle", "(", "cand_indexes", ")", "output_tokens", "=", "list", "(", "tokens", ")", "num_to_predict", "=", "min", "(", "max_predictions_per_seq", ",", "max", "(", "1", ",", "int", "(", "round", "(", "len", "(", "tokens", ")", "*", "masked_lm_prob", ")", ")", ")", ")", "masked_lms", "=", "[", "]", "covered_indexes", "=", "set", "(", ")", "for", "index", "in", "cand_indexes", ":", "if", "len", "(", "masked_lms", ")", ">=", "num_to_predict", ":", "break", "if", "index", "in", "covered_indexes", ":", "continue", "covered_indexes", ".", "add", "(", "index", ")", "masked_token", "=", "None", "# 80% of the time, replace with [MASK]", "if", "rng", ".", "random", "(", ")", "<", "0.8", ":", "masked_token", "=", "'[MASK]'", "else", ":", "# 10% of the time, keep original", "if", "rng", ".", "random", "(", ")", "<", "0.5", ":", "masked_token", "=", "tokens", "[", "index", "]", "# 10% of the time, replace with random word", "else", ":", "masked_token", "=", "vocab_words", "[", "rng", ".", "randint", "(", "0", ",", "len", "(", "vocab_words", ")", "-", "1", ")", "]", "output_tokens", "[", "index", "]", "=", "masked_token", "masked_lms", ".", "append", "(", "MaskedLmInstance", "(", "index", "=", "index", ",", "label", "=", "tokens", "[", "index", "]", ")", ")", "masked_lms", "=", "sorted", "(", "masked_lms", ",", "key", "=", "lambda", "x", ":", "x", ".", "index", ")", "masked_lm_positions", "=", "[", "]", "masked_lm_labels", "=", "[", "]", "for", "p", "in", "masked_lms", ":", "masked_lm_positions", ".", "append", "(", "p", ".", "index", ")", "masked_lm_labels", ".", "append", "(", "p", ".", "label", ")", "return", "(", "output_tokens", ",", "masked_lm_positions", ",", "masked_lm_labels", ")" ]
Creates the predictions for the masked LM objective.
[ "Creates", "the", "predictions", "for", "the", "masked", "LM", "objective", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L479-L530
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
truncate_seq_pair
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b assert len(trunc_tokens) >= 1 # We want to sometimes truncate from the front and sometimes from the # back to add more randomness and avoid biases. if rng.random() < 0.5: del trunc_tokens[0] else: trunc_tokens.pop()
python
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b assert len(trunc_tokens) >= 1 # We want to sometimes truncate from the front and sometimes from the # back to add more randomness and avoid biases. if rng.random() < 0.5: del trunc_tokens[0] else: trunc_tokens.pop()
[ "def", "truncate_seq_pair", "(", "tokens_a", ",", "tokens_b", ",", "max_num_tokens", ",", "rng", ")", ":", "while", "True", ":", "total_length", "=", "len", "(", "tokens_a", ")", "+", "len", "(", "tokens_b", ")", "if", "total_length", "<=", "max_num_tokens", ":", "break", "trunc_tokens", "=", "tokens_a", "if", "len", "(", "tokens_a", ")", ">", "len", "(", "tokens_b", ")", "else", "tokens_b", "assert", "len", "(", "trunc_tokens", ")", ">=", "1", "# We want to sometimes truncate from the front and sometimes from the", "# back to add more randomness and avoid biases.", "if", "rng", ".", "random", "(", ")", "<", "0.5", ":", "del", "trunc_tokens", "[", "0", "]", "else", ":", "trunc_tokens", ".", "pop", "(", ")" ]
Truncates a pair of sequences to a maximum sequence length.
[ "Truncates", "a", "pair", "of", "sequences", "to", "a", "maximum", "sequence", "length", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L533-L548
train
dmlc/gluon-nlp
scripts/bert/create_pretraining_data.py
main
def main(): """Main function.""" time_start = time.time() logging.info('loading vocab file from dataset: %s', args.vocab) vocab_obj = nlp.data.utils._load_pretrained_vocab(args.vocab) tokenizer = BERTTokenizer( vocab=vocab_obj, lower='uncased' in args.vocab) input_files = [] for input_pattern in args.input_file.split(','): input_files.extend(glob.glob(os.path.expanduser(input_pattern))) logging.info('*** Reading from %d input files ***', len(input_files)) for input_file in input_files: logging.info(' %s', input_file) num_outputs = min(args.num_outputs, len(input_files)) output_dir = os.path.expanduser(args.output_dir) if not os.path.exists(output_dir): os.makedirs(output_dir) rng = random.Random(args.random_seed) nworker = args.num_workers # calculate the number of splits file_splits = [] split_size = (len(input_files) + num_outputs - 1) // num_outputs for i in range(num_outputs - 1): file_splits.append(input_files[i*split_size:(i+1)*split_size]) file_splits.append(input_files[(num_outputs-1)*split_size:]) # prepare workload suffix = 'npz' if args.format == 'numpy' else 'rec' count = 0 map_args = [] pool_args = (tokenizer, args.max_seq_length, args.dupe_factor,\ args.short_seq_prob, args.masked_lm_prob, args.max_predictions_per_seq, rng) for i, file_split in enumerate(file_splits): out = os.path.join(output_dir, 'part-{}.{}'.format(str(i).zfill(3), suffix)) count += len(file_split) map_args.append((file_split, out) + pool_args) # sanity check assert count == len(input_files) # dispatch to workers if nworker > 1: pool = Pool(nworker) pool.map(create_training_instances, map_args) else: for map_arg in map_args: create_training_instances(map_arg) time_end = time.time() logging.info('Time cost=%.1f', time_end - time_start)
python
def main(): """Main function.""" time_start = time.time() logging.info('loading vocab file from dataset: %s', args.vocab) vocab_obj = nlp.data.utils._load_pretrained_vocab(args.vocab) tokenizer = BERTTokenizer( vocab=vocab_obj, lower='uncased' in args.vocab) input_files = [] for input_pattern in args.input_file.split(','): input_files.extend(glob.glob(os.path.expanduser(input_pattern))) logging.info('*** Reading from %d input files ***', len(input_files)) for input_file in input_files: logging.info(' %s', input_file) num_outputs = min(args.num_outputs, len(input_files)) output_dir = os.path.expanduser(args.output_dir) if not os.path.exists(output_dir): os.makedirs(output_dir) rng = random.Random(args.random_seed) nworker = args.num_workers # calculate the number of splits file_splits = [] split_size = (len(input_files) + num_outputs - 1) // num_outputs for i in range(num_outputs - 1): file_splits.append(input_files[i*split_size:(i+1)*split_size]) file_splits.append(input_files[(num_outputs-1)*split_size:]) # prepare workload suffix = 'npz' if args.format == 'numpy' else 'rec' count = 0 map_args = [] pool_args = (tokenizer, args.max_seq_length, args.dupe_factor,\ args.short_seq_prob, args.masked_lm_prob, args.max_predictions_per_seq, rng) for i, file_split in enumerate(file_splits): out = os.path.join(output_dir, 'part-{}.{}'.format(str(i).zfill(3), suffix)) count += len(file_split) map_args.append((file_split, out) + pool_args) # sanity check assert count == len(input_files) # dispatch to workers if nworker > 1: pool = Pool(nworker) pool.map(create_training_instances, map_args) else: for map_arg in map_args: create_training_instances(map_arg) time_end = time.time() logging.info('Time cost=%.1f', time_end - time_start)
[ "def", "main", "(", ")", ":", "time_start", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'loading vocab file from dataset: %s'", ",", "args", ".", "vocab", ")", "vocab_obj", "=", "nlp", ".", "data", ".", "utils", ".", "_load_pretrained_vocab", "(", "args", ".", "vocab", ")", "tokenizer", "=", "BERTTokenizer", "(", "vocab", "=", "vocab_obj", ",", "lower", "=", "'uncased'", "in", "args", ".", "vocab", ")", "input_files", "=", "[", "]", "for", "input_pattern", "in", "args", ".", "input_file", ".", "split", "(", "','", ")", ":", "input_files", ".", "extend", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "expanduser", "(", "input_pattern", ")", ")", ")", "logging", ".", "info", "(", "'*** Reading from %d input files ***'", ",", "len", "(", "input_files", ")", ")", "for", "input_file", "in", "input_files", ":", "logging", ".", "info", "(", "' %s'", ",", "input_file", ")", "num_outputs", "=", "min", "(", "args", ".", "num_outputs", ",", "len", "(", "input_files", ")", ")", "output_dir", "=", "os", ".", "path", ".", "expanduser", "(", "args", ".", "output_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "output_dir", ")", ":", "os", ".", "makedirs", "(", "output_dir", ")", "rng", "=", "random", ".", "Random", "(", "args", ".", "random_seed", ")", "nworker", "=", "args", ".", "num_workers", "# calculate the number of splits", "file_splits", "=", "[", "]", "split_size", "=", "(", "len", "(", "input_files", ")", "+", "num_outputs", "-", "1", ")", "//", "num_outputs", "for", "i", "in", "range", "(", "num_outputs", "-", "1", ")", ":", "file_splits", ".", "append", "(", "input_files", "[", "i", "*", "split_size", ":", "(", "i", "+", "1", ")", "*", "split_size", "]", ")", "file_splits", ".", "append", "(", "input_files", "[", "(", "num_outputs", "-", "1", ")", "*", "split_size", ":", "]", ")", "# prepare workload", "suffix", "=", "'npz'", "if", "args", ".", "format", "==", "'numpy'", "else", "'rec'", "count", "=", "0", "map_args", "=", "[", "]", "pool_args", "=", "(", "tokenizer", ",", "args", ".", "max_seq_length", ",", "args", ".", "dupe_factor", ",", "args", ".", "short_seq_prob", ",", "args", ".", "masked_lm_prob", ",", "args", ".", "max_predictions_per_seq", ",", "rng", ")", "for", "i", ",", "file_split", "in", "enumerate", "(", "file_splits", ")", ":", "out", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'part-{}.{}'", ".", "format", "(", "str", "(", "i", ")", ".", "zfill", "(", "3", ")", ",", "suffix", ")", ")", "count", "+=", "len", "(", "file_split", ")", "map_args", ".", "append", "(", "(", "file_split", ",", "out", ")", "+", "pool_args", ")", "# sanity check", "assert", "count", "==", "len", "(", "input_files", ")", "# dispatch to workers", "if", "nworker", ">", "1", ":", "pool", "=", "Pool", "(", "nworker", ")", "pool", ".", "map", "(", "create_training_instances", ",", "map_args", ")", "else", ":", "for", "map_arg", "in", "map_args", ":", "create_training_instances", "(", "map_arg", ")", "time_end", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'Time cost=%.1f'", ",", "time_end", "-", "time_start", ")" ]
Main function.
[ "Main", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L551-L607
train
dmlc/gluon-nlp
scripts/bert/utils.py
convert_vocab
def convert_vocab(vocab_file): """GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab.""" original_vocab = load_vocab(vocab_file) token_to_idx = dict(original_vocab) num_tokens = len(token_to_idx) idx_to_token = [None] * len(original_vocab) for word in original_vocab: idx = int(original_vocab[word]) idx_to_token[idx] = word def swap(token, target_idx, token_to_idx, idx_to_token, swap_idx): original_idx = token_to_idx[token] original_token = idx_to_token[target_idx] token_to_idx[token] = target_idx token_to_idx[original_token] = original_idx idx_to_token[target_idx] = token idx_to_token[original_idx] = original_token swap_idx.append((original_idx, target_idx)) reserved_tokens = [gluonnlp.vocab.BERTVocab.PADDING_TOKEN, gluonnlp.vocab.BERTVocab.CLS_TOKEN, gluonnlp.vocab.BERTVocab.SEP_TOKEN, gluonnlp.vocab.BERTVocab.MASK_TOKEN] unknown_token = gluonnlp.vocab.BERTVocab.UNKNOWN_TOKEN padding_token = gluonnlp.vocab.BERTVocab.PADDING_TOKEN swap_idx = [] assert unknown_token in token_to_idx assert padding_token in token_to_idx swap(unknown_token, 0, token_to_idx, idx_to_token, swap_idx) for i, token in enumerate(reserved_tokens): swap(token, i + 1, token_to_idx, idx_to_token, swap_idx) # sanity checks assert len(token_to_idx) == num_tokens assert len(idx_to_token) == num_tokens assert None not in idx_to_token assert len(set(idx_to_token)) == num_tokens bert_vocab_dict = {} bert_vocab_dict['idx_to_token'] = idx_to_token bert_vocab_dict['token_to_idx'] = token_to_idx bert_vocab_dict['reserved_tokens'] = reserved_tokens bert_vocab_dict['unknown_token'] = unknown_token bert_vocab_dict['padding_token'] = padding_token bert_vocab_dict['bos_token'] = None bert_vocab_dict['eos_token'] = None bert_vocab_dict['mask_token'] = gluonnlp.vocab.BERTVocab.MASK_TOKEN bert_vocab_dict['sep_token'] = gluonnlp.vocab.BERTVocab.SEP_TOKEN bert_vocab_dict['cls_token'] = gluonnlp.vocab.BERTVocab.CLS_TOKEN json_str = json.dumps(bert_vocab_dict) converted_vocab = gluonnlp.vocab.BERTVocab.from_json(json_str) return converted_vocab, swap_idx
python
def convert_vocab(vocab_file): """GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab.""" original_vocab = load_vocab(vocab_file) token_to_idx = dict(original_vocab) num_tokens = len(token_to_idx) idx_to_token = [None] * len(original_vocab) for word in original_vocab: idx = int(original_vocab[word]) idx_to_token[idx] = word def swap(token, target_idx, token_to_idx, idx_to_token, swap_idx): original_idx = token_to_idx[token] original_token = idx_to_token[target_idx] token_to_idx[token] = target_idx token_to_idx[original_token] = original_idx idx_to_token[target_idx] = token idx_to_token[original_idx] = original_token swap_idx.append((original_idx, target_idx)) reserved_tokens = [gluonnlp.vocab.BERTVocab.PADDING_TOKEN, gluonnlp.vocab.BERTVocab.CLS_TOKEN, gluonnlp.vocab.BERTVocab.SEP_TOKEN, gluonnlp.vocab.BERTVocab.MASK_TOKEN] unknown_token = gluonnlp.vocab.BERTVocab.UNKNOWN_TOKEN padding_token = gluonnlp.vocab.BERTVocab.PADDING_TOKEN swap_idx = [] assert unknown_token in token_to_idx assert padding_token in token_to_idx swap(unknown_token, 0, token_to_idx, idx_to_token, swap_idx) for i, token in enumerate(reserved_tokens): swap(token, i + 1, token_to_idx, idx_to_token, swap_idx) # sanity checks assert len(token_to_idx) == num_tokens assert len(idx_to_token) == num_tokens assert None not in idx_to_token assert len(set(idx_to_token)) == num_tokens bert_vocab_dict = {} bert_vocab_dict['idx_to_token'] = idx_to_token bert_vocab_dict['token_to_idx'] = token_to_idx bert_vocab_dict['reserved_tokens'] = reserved_tokens bert_vocab_dict['unknown_token'] = unknown_token bert_vocab_dict['padding_token'] = padding_token bert_vocab_dict['bos_token'] = None bert_vocab_dict['eos_token'] = None bert_vocab_dict['mask_token'] = gluonnlp.vocab.BERTVocab.MASK_TOKEN bert_vocab_dict['sep_token'] = gluonnlp.vocab.BERTVocab.SEP_TOKEN bert_vocab_dict['cls_token'] = gluonnlp.vocab.BERTVocab.CLS_TOKEN json_str = json.dumps(bert_vocab_dict) converted_vocab = gluonnlp.vocab.BERTVocab.from_json(json_str) return converted_vocab, swap_idx
[ "def", "convert_vocab", "(", "vocab_file", ")", ":", "original_vocab", "=", "load_vocab", "(", "vocab_file", ")", "token_to_idx", "=", "dict", "(", "original_vocab", ")", "num_tokens", "=", "len", "(", "token_to_idx", ")", "idx_to_token", "=", "[", "None", "]", "*", "len", "(", "original_vocab", ")", "for", "word", "in", "original_vocab", ":", "idx", "=", "int", "(", "original_vocab", "[", "word", "]", ")", "idx_to_token", "[", "idx", "]", "=", "word", "def", "swap", "(", "token", ",", "target_idx", ",", "token_to_idx", ",", "idx_to_token", ",", "swap_idx", ")", ":", "original_idx", "=", "token_to_idx", "[", "token", "]", "original_token", "=", "idx_to_token", "[", "target_idx", "]", "token_to_idx", "[", "token", "]", "=", "target_idx", "token_to_idx", "[", "original_token", "]", "=", "original_idx", "idx_to_token", "[", "target_idx", "]", "=", "token", "idx_to_token", "[", "original_idx", "]", "=", "original_token", "swap_idx", ".", "append", "(", "(", "original_idx", ",", "target_idx", ")", ")", "reserved_tokens", "=", "[", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "PADDING_TOKEN", ",", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "CLS_TOKEN", ",", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "SEP_TOKEN", ",", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "MASK_TOKEN", "]", "unknown_token", "=", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "UNKNOWN_TOKEN", "padding_token", "=", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "PADDING_TOKEN", "swap_idx", "=", "[", "]", "assert", "unknown_token", "in", "token_to_idx", "assert", "padding_token", "in", "token_to_idx", "swap", "(", "unknown_token", ",", "0", ",", "token_to_idx", ",", "idx_to_token", ",", "swap_idx", ")", "for", "i", ",", "token", "in", "enumerate", "(", "reserved_tokens", ")", ":", "swap", "(", "token", ",", "i", "+", "1", ",", "token_to_idx", ",", "idx_to_token", ",", "swap_idx", ")", "# sanity checks", "assert", "len", "(", "token_to_idx", ")", "==", "num_tokens", "assert", "len", "(", "idx_to_token", ")", "==", "num_tokens", "assert", "None", "not", "in", "idx_to_token", "assert", "len", "(", "set", "(", "idx_to_token", ")", ")", "==", "num_tokens", "bert_vocab_dict", "=", "{", "}", "bert_vocab_dict", "[", "'idx_to_token'", "]", "=", "idx_to_token", "bert_vocab_dict", "[", "'token_to_idx'", "]", "=", "token_to_idx", "bert_vocab_dict", "[", "'reserved_tokens'", "]", "=", "reserved_tokens", "bert_vocab_dict", "[", "'unknown_token'", "]", "=", "unknown_token", "bert_vocab_dict", "[", "'padding_token'", "]", "=", "padding_token", "bert_vocab_dict", "[", "'bos_token'", "]", "=", "None", "bert_vocab_dict", "[", "'eos_token'", "]", "=", "None", "bert_vocab_dict", "[", "'mask_token'", "]", "=", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "MASK_TOKEN", "bert_vocab_dict", "[", "'sep_token'", "]", "=", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "SEP_TOKEN", "bert_vocab_dict", "[", "'cls_token'", "]", "=", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "CLS_TOKEN", "json_str", "=", "json", ".", "dumps", "(", "bert_vocab_dict", ")", "converted_vocab", "=", "gluonnlp", ".", "vocab", ".", "BERTVocab", ".", "from_json", "(", "json_str", ")", "return", "converted_vocab", ",", "swap_idx" ]
GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab.
[ "GluonNLP", "specific", "code", "to", "convert", "the", "original", "vocabulary", "to", "nlp", ".", "vocab", ".", "BERTVocab", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/utils.py#L33-L83
train
dmlc/gluon-nlp
scripts/bert/utils.py
read_tf_checkpoint
def read_tf_checkpoint(path): """read tensorflow checkpoint""" from tensorflow.python import pywrap_tensorflow tensors = {} reader = pywrap_tensorflow.NewCheckpointReader(path) var_to_shape_map = reader.get_variable_to_shape_map() for key in sorted(var_to_shape_map): tensor = reader.get_tensor(key) tensors[key] = tensor return tensors
python
def read_tf_checkpoint(path): """read tensorflow checkpoint""" from tensorflow.python import pywrap_tensorflow tensors = {} reader = pywrap_tensorflow.NewCheckpointReader(path) var_to_shape_map = reader.get_variable_to_shape_map() for key in sorted(var_to_shape_map): tensor = reader.get_tensor(key) tensors[key] = tensor return tensors
[ "def", "read_tf_checkpoint", "(", "path", ")", ":", "from", "tensorflow", ".", "python", "import", "pywrap_tensorflow", "tensors", "=", "{", "}", "reader", "=", "pywrap_tensorflow", ".", "NewCheckpointReader", "(", "path", ")", "var_to_shape_map", "=", "reader", ".", "get_variable_to_shape_map", "(", ")", "for", "key", "in", "sorted", "(", "var_to_shape_map", ")", ":", "tensor", "=", "reader", ".", "get_tensor", "(", "key", ")", "tensors", "[", "key", "]", "=", "tensor", "return", "tensors" ]
read tensorflow checkpoint
[ "read", "tensorflow", "checkpoint" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/utils.py#L97-L106
train
dmlc/gluon-nlp
scripts/bert/utils.py
profile
def profile(curr_step, start_step, end_step, profile_name='profile.json', early_exit=True): """profile the program between [start_step, end_step).""" if curr_step == start_step: mx.nd.waitall() mx.profiler.set_config(profile_memory=False, profile_symbolic=True, profile_imperative=True, filename=profile_name, aggregate_stats=True) mx.profiler.set_state('run') elif curr_step == end_step: mx.nd.waitall() mx.profiler.set_state('stop') logging.info(mx.profiler.dumps()) mx.profiler.dump() if early_exit: exit()
python
def profile(curr_step, start_step, end_step, profile_name='profile.json', early_exit=True): """profile the program between [start_step, end_step).""" if curr_step == start_step: mx.nd.waitall() mx.profiler.set_config(profile_memory=False, profile_symbolic=True, profile_imperative=True, filename=profile_name, aggregate_stats=True) mx.profiler.set_state('run') elif curr_step == end_step: mx.nd.waitall() mx.profiler.set_state('stop') logging.info(mx.profiler.dumps()) mx.profiler.dump() if early_exit: exit()
[ "def", "profile", "(", "curr_step", ",", "start_step", ",", "end_step", ",", "profile_name", "=", "'profile.json'", ",", "early_exit", "=", "True", ")", ":", "if", "curr_step", "==", "start_step", ":", "mx", ".", "nd", ".", "waitall", "(", ")", "mx", ".", "profiler", ".", "set_config", "(", "profile_memory", "=", "False", ",", "profile_symbolic", "=", "True", ",", "profile_imperative", "=", "True", ",", "filename", "=", "profile_name", ",", "aggregate_stats", "=", "True", ")", "mx", ".", "profiler", ".", "set_state", "(", "'run'", ")", "elif", "curr_step", "==", "end_step", ":", "mx", ".", "nd", ".", "waitall", "(", ")", "mx", ".", "profiler", ".", "set_state", "(", "'stop'", ")", "logging", ".", "info", "(", "mx", ".", "profiler", ".", "dumps", "(", ")", ")", "mx", ".", "profiler", ".", "dump", "(", ")", "if", "early_exit", ":", "exit", "(", ")" ]
profile the program between [start_step, end_step).
[ "profile", "the", "program", "between", "[", "start_step", "end_step", ")", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/utils.py#L108-L123
train