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
scripts/sentiment_analysis/process_data.py
load_dataset
def load_dataset(data_name): """Load sentiment dataset.""" if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vocab, max_len) return vocab, max_len, output_size, train_dataset, train_data_lengths else: train_dataset, test_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, test_dataset) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vocab, max_len) test_dataset, test_data_lengths = _preprocess_dataset(test_dataset, vocab, max_len) return vocab, max_len, output_size, train_dataset, train_data_lengths, test_dataset, \ test_data_lengths
python
def load_dataset(data_name): """Load sentiment dataset.""" if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vocab, max_len) return vocab, max_len, output_size, train_dataset, train_data_lengths else: train_dataset, test_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, test_dataset) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vocab, max_len) test_dataset, test_data_lengths = _preprocess_dataset(test_dataset, vocab, max_len) return vocab, max_len, output_size, train_dataset, train_data_lengths, test_dataset, \ test_data_lengths
[ "def", "load_dataset", "(", "data_name", ")", ":", "if", "data_name", "==", "'MR'", "or", "data_name", "==", "'Subj'", ":", "train_dataset", ",", "output_size", "=", "_load_file", "(", "data_name", ")", "vocab", ",", "max_len", "=", "_build_vocab", "(", "data_name", ",", "train_dataset", ",", "[", "]", ")", "train_dataset", ",", "train_data_lengths", "=", "_preprocess_dataset", "(", "train_dataset", ",", "vocab", ",", "max_len", ")", "return", "vocab", ",", "max_len", ",", "output_size", ",", "train_dataset", ",", "train_data_lengths", "else", ":", "train_dataset", ",", "test_dataset", ",", "output_size", "=", "_load_file", "(", "data_name", ")", "vocab", ",", "max_len", "=", "_build_vocab", "(", "data_name", ",", "train_dataset", ",", "test_dataset", ")", "train_dataset", ",", "train_data_lengths", "=", "_preprocess_dataset", "(", "train_dataset", ",", "vocab", ",", "max_len", ")", "test_dataset", ",", "test_data_lengths", "=", "_preprocess_dataset", "(", "test_dataset", ",", "vocab", ",", "max_len", ")", "return", "vocab", ",", "max_len", ",", "output_size", ",", "train_dataset", ",", "train_data_lengths", ",", "test_dataset", ",", "test_data_lengths" ]
Load sentiment dataset.
[ "Load", "sentiment", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/process_data.py#L120-L133
train
dmlc/gluon-nlp
src/gluonnlp/base.py
get_home_dir
def get_home_dir(): """Get home directory for storing datasets/models/pre-trained word embeddings""" _home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet')) # expand ~ to actual path _home_dir = os.path.expanduser(_home_dir) return _home_dir
python
def get_home_dir(): """Get home directory for storing datasets/models/pre-trained word embeddings""" _home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet')) # expand ~ to actual path _home_dir = os.path.expanduser(_home_dir) return _home_dir
[ "def", "get_home_dir", "(", ")", ":", "_home_dir", "=", "os", ".", "environ", ".", "get", "(", "'MXNET_HOME'", ",", "os", ".", "path", ".", "join", "(", "'~'", ",", "'.mxnet'", ")", ")", "# expand ~ to actual path", "_home_dir", "=", "os", ".", "path", ".", "expanduser", "(", "_home_dir", ")", "return", "_home_dir" ]
Get home directory for storing datasets/models/pre-trained word embeddings
[ "Get", "home", "directory", "for", "storing", "datasets", "/", "models", "/", "pre", "-", "trained", "word", "embeddings" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/base.py#L68-L73
train
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
read_dataset
def read_dataset(args, dataset): """ Read dataset from tokenized files. """ path = os.path.join(vars(args)[dataset]) logger.info('reading data from {}'.format(path)) examples = [line.strip().split('\t') for line in open(path)] if args.max_num_examples > 0: examples = examples[:args.max_num_examples] # NOTE: assume data has been tokenized dataset = gluon.data.SimpleDataset([(e[0], e[1], LABEL_TO_IDX[e[2]]) for e in examples]) dataset = dataset.transform(lambda s1, s2, label: ( ['NULL'] + s1.lower().split(), ['NULL'] + s2.lower().split(), label), lazy=False) logger.info('read {} examples'.format(len(dataset))) return dataset
python
def read_dataset(args, dataset): """ Read dataset from tokenized files. """ path = os.path.join(vars(args)[dataset]) logger.info('reading data from {}'.format(path)) examples = [line.strip().split('\t') for line in open(path)] if args.max_num_examples > 0: examples = examples[:args.max_num_examples] # NOTE: assume data has been tokenized dataset = gluon.data.SimpleDataset([(e[0], e[1], LABEL_TO_IDX[e[2]]) for e in examples]) dataset = dataset.transform(lambda s1, s2, label: ( ['NULL'] + s1.lower().split(), ['NULL'] + s2.lower().split(), label), lazy=False) logger.info('read {} examples'.format(len(dataset))) return dataset
[ "def", "read_dataset", "(", "args", ",", "dataset", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "vars", "(", "args", ")", "[", "dataset", "]", ")", "logger", ".", "info", "(", "'reading data from {}'", ".", "format", "(", "path", ")", ")", "examples", "=", "[", "line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", "for", "line", "in", "open", "(", "path", ")", "]", "if", "args", ".", "max_num_examples", ">", "0", ":", "examples", "=", "examples", "[", ":", "args", ".", "max_num_examples", "]", "# NOTE: assume data has been tokenized", "dataset", "=", "gluon", ".", "data", ".", "SimpleDataset", "(", "[", "(", "e", "[", "0", "]", ",", "e", "[", "1", "]", ",", "LABEL_TO_IDX", "[", "e", "[", "2", "]", "]", ")", "for", "e", "in", "examples", "]", ")", "dataset", "=", "dataset", ".", "transform", "(", "lambda", "s1", ",", "s2", ",", "label", ":", "(", "[", "'NULL'", "]", "+", "s1", ".", "lower", "(", ")", ".", "split", "(", ")", ",", "[", "'NULL'", "]", "+", "s2", ".", "lower", "(", ")", ".", "split", "(", ")", ",", "label", ")", ",", "lazy", "=", "False", ")", "logger", ".", "info", "(", "'read {} examples'", ".", "format", "(", "len", "(", "dataset", ")", ")", ")", "return", "dataset" ]
Read dataset from tokenized files.
[ "Read", "dataset", "from", "tokenized", "files", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L35-L51
train
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
build_vocab
def build_vocab(dataset): """ Build vocab given a dataset. """ counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s], to_lower=True) vocab = nlp.Vocab(counter) return vocab
python
def build_vocab(dataset): """ Build vocab given a dataset. """ counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s], to_lower=True) vocab = nlp.Vocab(counter) return vocab
[ "def", "build_vocab", "(", "dataset", ")", ":", "counter", "=", "nlp", ".", "data", ".", "count_tokens", "(", "[", "w", "for", "e", "in", "dataset", "for", "s", "in", "e", "[", ":", "2", "]", "for", "w", "in", "s", "]", ",", "to_lower", "=", "True", ")", "vocab", "=", "nlp", ".", "Vocab", "(", "counter", ")", "return", "vocab" ]
Build vocab given a dataset.
[ "Build", "vocab", "given", "a", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L53-L60
train
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
prepare_data_loader
def prepare_data_loader(args, dataset, vocab, test=False): """ Read data and build data loader. """ # Preprocess dataset = dataset.transform(lambda s1, s2, label: (vocab(s1), vocab(s2), label), lazy=False) # Batching batchify_fn = btf.Tuple(btf.Pad(), btf.Pad(), btf.Stack(dtype='int32')) data_lengths = [max(len(d[0]), len(d[1])) for d in dataset] batch_sampler = nlp.data.FixedBucketSampler(lengths=data_lengths, batch_size=args.batch_size, shuffle=(not test)) data_loader = gluon.data.DataLoader(dataset=dataset, batch_sampler=batch_sampler, batchify_fn=batchify_fn) return data_loader
python
def prepare_data_loader(args, dataset, vocab, test=False): """ Read data and build data loader. """ # Preprocess dataset = dataset.transform(lambda s1, s2, label: (vocab(s1), vocab(s2), label), lazy=False) # Batching batchify_fn = btf.Tuple(btf.Pad(), btf.Pad(), btf.Stack(dtype='int32')) data_lengths = [max(len(d[0]), len(d[1])) for d in dataset] batch_sampler = nlp.data.FixedBucketSampler(lengths=data_lengths, batch_size=args.batch_size, shuffle=(not test)) data_loader = gluon.data.DataLoader(dataset=dataset, batch_sampler=batch_sampler, batchify_fn=batchify_fn) return data_loader
[ "def", "prepare_data_loader", "(", "args", ",", "dataset", ",", "vocab", ",", "test", "=", "False", ")", ":", "# Preprocess", "dataset", "=", "dataset", ".", "transform", "(", "lambda", "s1", ",", "s2", ",", "label", ":", "(", "vocab", "(", "s1", ")", ",", "vocab", "(", "s2", ")", ",", "label", ")", ",", "lazy", "=", "False", ")", "# Batching", "batchify_fn", "=", "btf", ".", "Tuple", "(", "btf", ".", "Pad", "(", ")", ",", "btf", ".", "Pad", "(", ")", ",", "btf", ".", "Stack", "(", "dtype", "=", "'int32'", ")", ")", "data_lengths", "=", "[", "max", "(", "len", "(", "d", "[", "0", "]", ")", ",", "len", "(", "d", "[", "1", "]", ")", ")", "for", "d", "in", "dataset", "]", "batch_sampler", "=", "nlp", ".", "data", ".", "FixedBucketSampler", "(", "lengths", "=", "data_lengths", ",", "batch_size", "=", "args", ".", "batch_size", ",", "shuffle", "=", "(", "not", "test", ")", ")", "data_loader", "=", "gluon", ".", "data", ".", "DataLoader", "(", "dataset", "=", "dataset", ",", "batch_sampler", "=", "batch_sampler", ",", "batchify_fn", "=", "batchify_fn", ")", "return", "data_loader" ]
Read data and build data loader.
[ "Read", "data", "and", "build", "data", "loader", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L62-L79
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
mxnet_prefer_gpu
def mxnet_prefer_gpu(): """If gpu available return gpu, else cpu Returns ------- context : Context The preferable GPU context. """ gpu = int(os.environ.get('MXNET_GPU', default=0)) if gpu in mx.test_utils.list_gpus(): return mx.gpu(gpu) return mx.cpu()
python
def mxnet_prefer_gpu(): """If gpu available return gpu, else cpu Returns ------- context : Context The preferable GPU context. """ gpu = int(os.environ.get('MXNET_GPU', default=0)) if gpu in mx.test_utils.list_gpus(): return mx.gpu(gpu) return mx.cpu()
[ "def", "mxnet_prefer_gpu", "(", ")", ":", "gpu", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'MXNET_GPU'", ",", "default", "=", "0", ")", ")", "if", "gpu", "in", "mx", ".", "test_utils", ".", "list_gpus", "(", ")", ":", "return", "mx", ".", "gpu", "(", "gpu", ")", "return", "mx", ".", "cpu", "(", ")" ]
If gpu available return gpu, else cpu Returns ------- context : Context The preferable GPU context.
[ "If", "gpu", "available", "return", "gpu", "else", "cpu" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L150-L161
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
init_logger
def init_logger(root_dir, name="train.log"): """Initialize a logger Parameters ---------- root_dir : str directory for saving log name : str name of logger Returns ------- logger : logging.Logger a logger """ os.makedirs(root_dir, exist_ok=True) log_formatter = logging.Formatter("%(message)s") logger = logging.getLogger(name) file_handler = logging.FileHandler("{0}/{1}".format(root_dir, name), mode='w') file_handler.setFormatter(log_formatter) logger.addHandler(file_handler) console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) logger.setLevel(logging.INFO) return logger
python
def init_logger(root_dir, name="train.log"): """Initialize a logger Parameters ---------- root_dir : str directory for saving log name : str name of logger Returns ------- logger : logging.Logger a logger """ os.makedirs(root_dir, exist_ok=True) log_formatter = logging.Formatter("%(message)s") logger = logging.getLogger(name) file_handler = logging.FileHandler("{0}/{1}".format(root_dir, name), mode='w') file_handler.setFormatter(log_formatter) logger.addHandler(file_handler) console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) logger.setLevel(logging.INFO) return logger
[ "def", "init_logger", "(", "root_dir", ",", "name", "=", "\"train.log\"", ")", ":", "os", ".", "makedirs", "(", "root_dir", ",", "exist_ok", "=", "True", ")", "log_formatter", "=", "logging", ".", "Formatter", "(", "\"%(message)s\"", ")", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "file_handler", "=", "logging", ".", "FileHandler", "(", "\"{0}/{1}\"", ".", "format", "(", "root_dir", ",", "name", ")", ",", "mode", "=", "'w'", ")", "file_handler", ".", "setFormatter", "(", "log_formatter", ")", "logger", ".", "addHandler", "(", "file_handler", ")", "console_handler", "=", "logging", ".", "StreamHandler", "(", ")", "console_handler", ".", "setFormatter", "(", "log_formatter", ")", "logger", ".", "addHandler", "(", "console_handler", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "return", "logger" ]
Initialize a logger Parameters ---------- root_dir : str directory for saving log name : str name of logger Returns ------- logger : logging.Logger a logger
[ "Initialize", "a", "logger" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L164-L189
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
orthonormal_VanillaLSTMBuilder
def orthonormal_VanillaLSTMBuilder(lstm_layers, input_dims, lstm_hiddens, dropout_x=0., dropout_h=0., debug=False): """Build a standard LSTM cell, with variational dropout, with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120) Parameters ---------- lstm_layers : int Currently only support one layer input_dims : int word vector dimensions lstm_hiddens : int hidden size dropout_x : float dropout on inputs, not used in this implementation, see `biLSTM` below dropout_h : float dropout on hidden states debug : bool set to True to skip orthonormal initialization Returns ------- lstm_cell : VariationalDropoutCell A LSTM cell """ assert lstm_layers == 1, 'only accept one layer lstm' W = orthonormal_initializer(lstm_hiddens, lstm_hiddens + input_dims, debug) W_h, W_x = W[:, :lstm_hiddens], W[:, lstm_hiddens:] b = nd.zeros((4 * lstm_hiddens,)) b[lstm_hiddens:2 * lstm_hiddens] = -1.0 lstm_cell = rnn.LSTMCell(input_size=input_dims, hidden_size=lstm_hiddens, i2h_weight_initializer=mx.init.Constant(np.concatenate([W_x] * 4, 0)), h2h_weight_initializer=mx.init.Constant(np.concatenate([W_h] * 4, 0)), h2h_bias_initializer=mx.init.Constant(b)) wrapper = VariationalDropoutCell(lstm_cell, drop_states=dropout_h) return wrapper
python
def orthonormal_VanillaLSTMBuilder(lstm_layers, input_dims, lstm_hiddens, dropout_x=0., dropout_h=0., debug=False): """Build a standard LSTM cell, with variational dropout, with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120) Parameters ---------- lstm_layers : int Currently only support one layer input_dims : int word vector dimensions lstm_hiddens : int hidden size dropout_x : float dropout on inputs, not used in this implementation, see `biLSTM` below dropout_h : float dropout on hidden states debug : bool set to True to skip orthonormal initialization Returns ------- lstm_cell : VariationalDropoutCell A LSTM cell """ assert lstm_layers == 1, 'only accept one layer lstm' W = orthonormal_initializer(lstm_hiddens, lstm_hiddens + input_dims, debug) W_h, W_x = W[:, :lstm_hiddens], W[:, lstm_hiddens:] b = nd.zeros((4 * lstm_hiddens,)) b[lstm_hiddens:2 * lstm_hiddens] = -1.0 lstm_cell = rnn.LSTMCell(input_size=input_dims, hidden_size=lstm_hiddens, i2h_weight_initializer=mx.init.Constant(np.concatenate([W_x] * 4, 0)), h2h_weight_initializer=mx.init.Constant(np.concatenate([W_h] * 4, 0)), h2h_bias_initializer=mx.init.Constant(b)) wrapper = VariationalDropoutCell(lstm_cell, drop_states=dropout_h) return wrapper
[ "def", "orthonormal_VanillaLSTMBuilder", "(", "lstm_layers", ",", "input_dims", ",", "lstm_hiddens", ",", "dropout_x", "=", "0.", ",", "dropout_h", "=", "0.", ",", "debug", "=", "False", ")", ":", "assert", "lstm_layers", "==", "1", ",", "'only accept one layer lstm'", "W", "=", "orthonormal_initializer", "(", "lstm_hiddens", ",", "lstm_hiddens", "+", "input_dims", ",", "debug", ")", "W_h", ",", "W_x", "=", "W", "[", ":", ",", ":", "lstm_hiddens", "]", ",", "W", "[", ":", ",", "lstm_hiddens", ":", "]", "b", "=", "nd", ".", "zeros", "(", "(", "4", "*", "lstm_hiddens", ",", ")", ")", "b", "[", "lstm_hiddens", ":", "2", "*", "lstm_hiddens", "]", "=", "-", "1.0", "lstm_cell", "=", "rnn", ".", "LSTMCell", "(", "input_size", "=", "input_dims", ",", "hidden_size", "=", "lstm_hiddens", ",", "i2h_weight_initializer", "=", "mx", ".", "init", ".", "Constant", "(", "np", ".", "concatenate", "(", "[", "W_x", "]", "*", "4", ",", "0", ")", ")", ",", "h2h_weight_initializer", "=", "mx", ".", "init", ".", "Constant", "(", "np", ".", "concatenate", "(", "[", "W_h", "]", "*", "4", ",", "0", ")", ")", ",", "h2h_bias_initializer", "=", "mx", ".", "init", ".", "Constant", "(", "b", ")", ")", "wrapper", "=", "VariationalDropoutCell", "(", "lstm_cell", ",", "drop_states", "=", "dropout_h", ")", "return", "wrapper" ]
Build a standard LSTM cell, with variational dropout, with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120) Parameters ---------- lstm_layers : int Currently only support one layer input_dims : int word vector dimensions lstm_hiddens : int hidden size dropout_x : float dropout on inputs, not used in this implementation, see `biLSTM` below dropout_h : float dropout on hidden states debug : bool set to True to skip orthonormal initialization Returns ------- lstm_cell : VariationalDropoutCell A LSTM cell
[ "Build", "a", "standard", "LSTM", "cell", "with", "variational", "dropout", "with", "weights", "initialized", "to", "be", "orthonormal", "(", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1312", ".", "6120", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L192-L226
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
biLSTM
def biLSTM(f_lstm, b_lstm, inputs, batch_size=None, dropout_x=0., dropout_h=0.): """Feature extraction through BiLSTM Parameters ---------- f_lstm : VariationalDropoutCell Forward cell b_lstm : VariationalDropoutCell Backward cell inputs : NDArray seq_len x batch_size dropout_x : float Variational dropout on inputs dropout_h : Not used Returns ------- outputs : NDArray Outputs of BiLSTM layers, seq_len x 2 hidden_dims x batch_size """ for f, b in zip(f_lstm, b_lstm): inputs = nd.Dropout(inputs, dropout_x, axes=[0]) # important for variational dropout fo, fs = f.unroll(length=inputs.shape[0], inputs=inputs, layout='TNC', merge_outputs=True) bo, bs = b.unroll(length=inputs.shape[0], inputs=inputs.flip(axis=0), layout='TNC', merge_outputs=True) f.reset(), b.reset() inputs = nd.concat(fo, bo.flip(axis=0), dim=2) return inputs
python
def biLSTM(f_lstm, b_lstm, inputs, batch_size=None, dropout_x=0., dropout_h=0.): """Feature extraction through BiLSTM Parameters ---------- f_lstm : VariationalDropoutCell Forward cell b_lstm : VariationalDropoutCell Backward cell inputs : NDArray seq_len x batch_size dropout_x : float Variational dropout on inputs dropout_h : Not used Returns ------- outputs : NDArray Outputs of BiLSTM layers, seq_len x 2 hidden_dims x batch_size """ for f, b in zip(f_lstm, b_lstm): inputs = nd.Dropout(inputs, dropout_x, axes=[0]) # important for variational dropout fo, fs = f.unroll(length=inputs.shape[0], inputs=inputs, layout='TNC', merge_outputs=True) bo, bs = b.unroll(length=inputs.shape[0], inputs=inputs.flip(axis=0), layout='TNC', merge_outputs=True) f.reset(), b.reset() inputs = nd.concat(fo, bo.flip(axis=0), dim=2) return inputs
[ "def", "biLSTM", "(", "f_lstm", ",", "b_lstm", ",", "inputs", ",", "batch_size", "=", "None", ",", "dropout_x", "=", "0.", ",", "dropout_h", "=", "0.", ")", ":", "for", "f", ",", "b", "in", "zip", "(", "f_lstm", ",", "b_lstm", ")", ":", "inputs", "=", "nd", ".", "Dropout", "(", "inputs", ",", "dropout_x", ",", "axes", "=", "[", "0", "]", ")", "# important for variational dropout", "fo", ",", "fs", "=", "f", ".", "unroll", "(", "length", "=", "inputs", ".", "shape", "[", "0", "]", ",", "inputs", "=", "inputs", ",", "layout", "=", "'TNC'", ",", "merge_outputs", "=", "True", ")", "bo", ",", "bs", "=", "b", ".", "unroll", "(", "length", "=", "inputs", ".", "shape", "[", "0", "]", ",", "inputs", "=", "inputs", ".", "flip", "(", "axis", "=", "0", ")", ",", "layout", "=", "'TNC'", ",", "merge_outputs", "=", "True", ")", "f", ".", "reset", "(", ")", ",", "b", ".", "reset", "(", ")", "inputs", "=", "nd", ".", "concat", "(", "fo", ",", "bo", ".", "flip", "(", "axis", "=", "0", ")", ",", "dim", "=", "2", ")", "return", "inputs" ]
Feature extraction through BiLSTM Parameters ---------- f_lstm : VariationalDropoutCell Forward cell b_lstm : VariationalDropoutCell Backward cell inputs : NDArray seq_len x batch_size dropout_x : float Variational dropout on inputs dropout_h : Not used Returns ------- outputs : NDArray Outputs of BiLSTM layers, seq_len x 2 hidden_dims x batch_size
[ "Feature", "extraction", "through", "BiLSTM" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L229-L256
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
bilinear
def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False): """Do xWy Parameters ---------- x : NDArray (input_size x seq_len) x batch_size W : NDArray (num_outputs x ny) x nx y : NDArray (input_size x seq_len) x batch_size input_size : int input dimension seq_len : int sequence length batch_size : int batch size num_outputs : int number of outputs bias_x : bool whether concat bias vector to input x bias_y : bool whether concat bias vector to input y Returns ------- output : NDArray [seq_len_y x seq_len_x if output_size == 1 else seq_len_y x num_outputs x seq_len_x] x batch_size """ if bias_x: x = nd.concat(x, nd.ones((1, seq_len, batch_size)), dim=0) if bias_y: y = nd.concat(y, nd.ones((1, seq_len, batch_size)), dim=0) nx, ny = input_size + bias_x, input_size + bias_y # W: (num_outputs x ny) x nx lin = nd.dot(W, x) if num_outputs > 1: lin = reshape_fortran(lin, (ny, num_outputs * seq_len, batch_size)) y = y.transpose([2, 1, 0]) # May cause performance issues lin = lin.transpose([2, 1, 0]) blin = nd.batch_dot(lin, y, transpose_b=True) blin = blin.transpose([2, 1, 0]) if num_outputs > 1: blin = reshape_fortran(blin, (seq_len, num_outputs, seq_len, batch_size)) return blin
python
def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False): """Do xWy Parameters ---------- x : NDArray (input_size x seq_len) x batch_size W : NDArray (num_outputs x ny) x nx y : NDArray (input_size x seq_len) x batch_size input_size : int input dimension seq_len : int sequence length batch_size : int batch size num_outputs : int number of outputs bias_x : bool whether concat bias vector to input x bias_y : bool whether concat bias vector to input y Returns ------- output : NDArray [seq_len_y x seq_len_x if output_size == 1 else seq_len_y x num_outputs x seq_len_x] x batch_size """ if bias_x: x = nd.concat(x, nd.ones((1, seq_len, batch_size)), dim=0) if bias_y: y = nd.concat(y, nd.ones((1, seq_len, batch_size)), dim=0) nx, ny = input_size + bias_x, input_size + bias_y # W: (num_outputs x ny) x nx lin = nd.dot(W, x) if num_outputs > 1: lin = reshape_fortran(lin, (ny, num_outputs * seq_len, batch_size)) y = y.transpose([2, 1, 0]) # May cause performance issues lin = lin.transpose([2, 1, 0]) blin = nd.batch_dot(lin, y, transpose_b=True) blin = blin.transpose([2, 1, 0]) if num_outputs > 1: blin = reshape_fortran(blin, (seq_len, num_outputs, seq_len, batch_size)) return blin
[ "def", "bilinear", "(", "x", ",", "W", ",", "y", ",", "input_size", ",", "seq_len", ",", "batch_size", ",", "num_outputs", "=", "1", ",", "bias_x", "=", "False", ",", "bias_y", "=", "False", ")", ":", "if", "bias_x", ":", "x", "=", "nd", ".", "concat", "(", "x", ",", "nd", ".", "ones", "(", "(", "1", ",", "seq_len", ",", "batch_size", ")", ")", ",", "dim", "=", "0", ")", "if", "bias_y", ":", "y", "=", "nd", ".", "concat", "(", "y", ",", "nd", ".", "ones", "(", "(", "1", ",", "seq_len", ",", "batch_size", ")", ")", ",", "dim", "=", "0", ")", "nx", ",", "ny", "=", "input_size", "+", "bias_x", ",", "input_size", "+", "bias_y", "# W: (num_outputs x ny) x nx", "lin", "=", "nd", ".", "dot", "(", "W", ",", "x", ")", "if", "num_outputs", ">", "1", ":", "lin", "=", "reshape_fortran", "(", "lin", ",", "(", "ny", ",", "num_outputs", "*", "seq_len", ",", "batch_size", ")", ")", "y", "=", "y", ".", "transpose", "(", "[", "2", ",", "1", ",", "0", "]", ")", "# May cause performance issues", "lin", "=", "lin", ".", "transpose", "(", "[", "2", ",", "1", ",", "0", "]", ")", "blin", "=", "nd", ".", "batch_dot", "(", "lin", ",", "y", ",", "transpose_b", "=", "True", ")", "blin", "=", "blin", ".", "transpose", "(", "[", "2", ",", "1", ",", "0", "]", ")", "if", "num_outputs", ">", "1", ":", "blin", "=", "reshape_fortran", "(", "blin", ",", "(", "seq_len", ",", "num_outputs", ",", "seq_len", ",", "batch_size", ")", ")", "return", "blin" ]
Do xWy Parameters ---------- x : NDArray (input_size x seq_len) x batch_size W : NDArray (num_outputs x ny) x nx y : NDArray (input_size x seq_len) x batch_size input_size : int input dimension seq_len : int sequence length batch_size : int batch size num_outputs : int number of outputs bias_x : bool whether concat bias vector to input x bias_y : bool whether concat bias vector to input y Returns ------- output : NDArray [seq_len_y x seq_len_x if output_size == 1 else seq_len_y x num_outputs x seq_len_x] x batch_size
[ "Do", "xWy" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L275-L320
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
orthonormal_initializer
def orthonormal_initializer(output_size, input_size, debug=False): """adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py Parameters ---------- output_size : int input_size : int debug : bool Whether to skip this initializer Returns ------- Q : np.ndarray The orthonormal weight matrix of input_size x output_size """ print((output_size, input_size)) if debug: Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) return np.transpose(Q.astype(np.float32)) I = np.eye(output_size) lr = .1 eps = .05 / (output_size + input_size) success = False tries = 0 while not success and tries < 10: Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) for i in range(100): QTQmI = Q.T.dot(Q) - I loss = np.sum(QTQmI ** 2 / 2) Q2 = Q ** 2 Q -= lr * Q.dot(QTQmI) / ( np.abs(Q2 + Q2.sum(axis=0, keepdims=True) + Q2.sum(axis=1, keepdims=True) - 1) + eps) if np.max(Q) > 1e6 or loss > 1e6 or not np.isfinite(loss): tries += 1 lr /= 2 break success = True if success: print(('Orthogonal pretrainer loss: %.2e' % loss)) else: print('Orthogonal pretrainer failed, using non-orthogonal random matrix') Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) return np.transpose(Q.astype(np.float32))
python
def orthonormal_initializer(output_size, input_size, debug=False): """adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py Parameters ---------- output_size : int input_size : int debug : bool Whether to skip this initializer Returns ------- Q : np.ndarray The orthonormal weight matrix of input_size x output_size """ print((output_size, input_size)) if debug: Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) return np.transpose(Q.astype(np.float32)) I = np.eye(output_size) lr = .1 eps = .05 / (output_size + input_size) success = False tries = 0 while not success and tries < 10: Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) for i in range(100): QTQmI = Q.T.dot(Q) - I loss = np.sum(QTQmI ** 2 / 2) Q2 = Q ** 2 Q -= lr * Q.dot(QTQmI) / ( np.abs(Q2 + Q2.sum(axis=0, keepdims=True) + Q2.sum(axis=1, keepdims=True) - 1) + eps) if np.max(Q) > 1e6 or loss > 1e6 or not np.isfinite(loss): tries += 1 lr /= 2 break success = True if success: print(('Orthogonal pretrainer loss: %.2e' % loss)) else: print('Orthogonal pretrainer failed, using non-orthogonal random matrix') Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) return np.transpose(Q.astype(np.float32))
[ "def", "orthonormal_initializer", "(", "output_size", ",", "input_size", ",", "debug", "=", "False", ")", ":", "print", "(", "(", "output_size", ",", "input_size", ")", ")", "if", "debug", ":", "Q", "=", "np", ".", "random", ".", "randn", "(", "input_size", ",", "output_size", ")", "/", "np", ".", "sqrt", "(", "output_size", ")", "return", "np", ".", "transpose", "(", "Q", ".", "astype", "(", "np", ".", "float32", ")", ")", "I", "=", "np", ".", "eye", "(", "output_size", ")", "lr", "=", ".1", "eps", "=", ".05", "/", "(", "output_size", "+", "input_size", ")", "success", "=", "False", "tries", "=", "0", "while", "not", "success", "and", "tries", "<", "10", ":", "Q", "=", "np", ".", "random", ".", "randn", "(", "input_size", ",", "output_size", ")", "/", "np", ".", "sqrt", "(", "output_size", ")", "for", "i", "in", "range", "(", "100", ")", ":", "QTQmI", "=", "Q", ".", "T", ".", "dot", "(", "Q", ")", "-", "I", "loss", "=", "np", ".", "sum", "(", "QTQmI", "**", "2", "/", "2", ")", "Q2", "=", "Q", "**", "2", "Q", "-=", "lr", "*", "Q", ".", "dot", "(", "QTQmI", ")", "/", "(", "np", ".", "abs", "(", "Q2", "+", "Q2", ".", "sum", "(", "axis", "=", "0", ",", "keepdims", "=", "True", ")", "+", "Q2", ".", "sum", "(", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "-", "1", ")", "+", "eps", ")", "if", "np", ".", "max", "(", "Q", ")", ">", "1e6", "or", "loss", ">", "1e6", "or", "not", "np", ".", "isfinite", "(", "loss", ")", ":", "tries", "+=", "1", "lr", "/=", "2", "break", "success", "=", "True", "if", "success", ":", "print", "(", "(", "'Orthogonal pretrainer loss: %.2e'", "%", "loss", ")", ")", "else", ":", "print", "(", "'Orthogonal pretrainer failed, using non-orthogonal random matrix'", ")", "Q", "=", "np", ".", "random", ".", "randn", "(", "input_size", ",", "output_size", ")", "/", "np", ".", "sqrt", "(", "output_size", ")", "return", "np", ".", "transpose", "(", "Q", ".", "astype", "(", "np", ".", "float32", ")", ")" ]
adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py Parameters ---------- output_size : int input_size : int debug : bool Whether to skip this initializer Returns ------- Q : np.ndarray The orthonormal weight matrix of input_size x output_size
[ "adopted", "from", "Timothy", "Dozat", "https", ":", "//", "github", ".", "com", "/", "tdozat", "/", "Parser", "/", "blob", "/", "master", "/", "lib", "/", "linalg", ".", "py" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L323-L364
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
arc_argmax
def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): """MST Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real sentence length tokens_to_keep : NDArray mask matrix ensure_tree : whether to ensure tree structure of output (apply MST) Returns ------- parse_preds : np.ndarray prediction of arc parsing with size of (seq_len,) """ if ensure_tree: I = np.eye(len(tokens_to_keep)) # block loops and pad heads parse_probs = parse_probs * tokens_to_keep * (1 - I) parse_preds = np.argmax(parse_probs, axis=1) tokens = np.arange(1, length) roots = np.where(parse_preds[tokens] == 0)[0] + 1 # ensure at least one root if len(roots) < 1: # The current root probabilities root_probs = parse_probs[tokens, 0] # The current head probabilities old_head_probs = parse_probs[tokens, parse_preds[tokens]] # Get new potential root probabilities new_root_probs = root_probs / old_head_probs # Select the most probable root new_root = tokens[np.argmax(new_root_probs)] # Make the change parse_preds[new_root] = 0 # ensure at most one root elif len(roots) > 1: # The probabilities of the current heads root_probs = parse_probs[roots, 0] # Set the probability of depending on the root zero parse_probs[roots, 0] = 0 # Get new potential heads and their probabilities new_heads = np.argmax(parse_probs[roots][:, tokens], axis=1) + 1 new_head_probs = parse_probs[roots, new_heads] / root_probs # Select the most probable root new_root = roots[np.argmin(new_head_probs)] # Make the change parse_preds[roots] = new_heads parse_preds[new_root] = 0 # remove cycles tarjan = Tarjan(parse_preds, tokens) for SCC in tarjan.SCCs: if len(SCC) > 1: dependents = set() to_visit = set(SCC) while len(to_visit) > 0: node = to_visit.pop() if not node in dependents: dependents.add(node) to_visit.update(tarjan.edges[node]) # The indices of the nodes that participate in the cycle cycle = np.array(list(SCC)) # The probabilities of the current heads old_heads = parse_preds[cycle] old_head_probs = parse_probs[cycle, old_heads] # Set the probability of depending on a non-head to zero non_heads = np.array(list(dependents)) parse_probs[np.repeat(cycle, len(non_heads)), np.repeat([non_heads], len(cycle), axis=0).flatten()] = 0 # Get new potential heads and their probabilities new_heads = np.argmax(parse_probs[cycle][:, tokens], axis=1) + 1 new_head_probs = parse_probs[cycle, new_heads] / old_head_probs # Select the most probable change change = np.argmax(new_head_probs) changed_cycle = cycle[change] old_head = old_heads[change] new_head = new_heads[change] # Make the change parse_preds[changed_cycle] = new_head tarjan.edges[new_head].add(changed_cycle) tarjan.edges[old_head].remove(changed_cycle) return parse_preds else: # block and pad heads parse_probs = parse_probs * tokens_to_keep parse_preds = np.argmax(parse_probs, axis=1) return parse_preds
python
def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): """MST Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real sentence length tokens_to_keep : NDArray mask matrix ensure_tree : whether to ensure tree structure of output (apply MST) Returns ------- parse_preds : np.ndarray prediction of arc parsing with size of (seq_len,) """ if ensure_tree: I = np.eye(len(tokens_to_keep)) # block loops and pad heads parse_probs = parse_probs * tokens_to_keep * (1 - I) parse_preds = np.argmax(parse_probs, axis=1) tokens = np.arange(1, length) roots = np.where(parse_preds[tokens] == 0)[0] + 1 # ensure at least one root if len(roots) < 1: # The current root probabilities root_probs = parse_probs[tokens, 0] # The current head probabilities old_head_probs = parse_probs[tokens, parse_preds[tokens]] # Get new potential root probabilities new_root_probs = root_probs / old_head_probs # Select the most probable root new_root = tokens[np.argmax(new_root_probs)] # Make the change parse_preds[new_root] = 0 # ensure at most one root elif len(roots) > 1: # The probabilities of the current heads root_probs = parse_probs[roots, 0] # Set the probability of depending on the root zero parse_probs[roots, 0] = 0 # Get new potential heads and their probabilities new_heads = np.argmax(parse_probs[roots][:, tokens], axis=1) + 1 new_head_probs = parse_probs[roots, new_heads] / root_probs # Select the most probable root new_root = roots[np.argmin(new_head_probs)] # Make the change parse_preds[roots] = new_heads parse_preds[new_root] = 0 # remove cycles tarjan = Tarjan(parse_preds, tokens) for SCC in tarjan.SCCs: if len(SCC) > 1: dependents = set() to_visit = set(SCC) while len(to_visit) > 0: node = to_visit.pop() if not node in dependents: dependents.add(node) to_visit.update(tarjan.edges[node]) # The indices of the nodes that participate in the cycle cycle = np.array(list(SCC)) # The probabilities of the current heads old_heads = parse_preds[cycle] old_head_probs = parse_probs[cycle, old_heads] # Set the probability of depending on a non-head to zero non_heads = np.array(list(dependents)) parse_probs[np.repeat(cycle, len(non_heads)), np.repeat([non_heads], len(cycle), axis=0).flatten()] = 0 # Get new potential heads and their probabilities new_heads = np.argmax(parse_probs[cycle][:, tokens], axis=1) + 1 new_head_probs = parse_probs[cycle, new_heads] / old_head_probs # Select the most probable change change = np.argmax(new_head_probs) changed_cycle = cycle[change] old_head = old_heads[change] new_head = new_heads[change] # Make the change parse_preds[changed_cycle] = new_head tarjan.edges[new_head].add(changed_cycle) tarjan.edges[old_head].remove(changed_cycle) return parse_preds else: # block and pad heads parse_probs = parse_probs * tokens_to_keep parse_preds = np.argmax(parse_probs, axis=1) return parse_preds
[ "def", "arc_argmax", "(", "parse_probs", ",", "length", ",", "tokens_to_keep", ",", "ensure_tree", "=", "True", ")", ":", "if", "ensure_tree", ":", "I", "=", "np", ".", "eye", "(", "len", "(", "tokens_to_keep", ")", ")", "# block loops and pad heads", "parse_probs", "=", "parse_probs", "*", "tokens_to_keep", "*", "(", "1", "-", "I", ")", "parse_preds", "=", "np", ".", "argmax", "(", "parse_probs", ",", "axis", "=", "1", ")", "tokens", "=", "np", ".", "arange", "(", "1", ",", "length", ")", "roots", "=", "np", ".", "where", "(", "parse_preds", "[", "tokens", "]", "==", "0", ")", "[", "0", "]", "+", "1", "# ensure at least one root", "if", "len", "(", "roots", ")", "<", "1", ":", "# The current root probabilities", "root_probs", "=", "parse_probs", "[", "tokens", ",", "0", "]", "# The current head probabilities", "old_head_probs", "=", "parse_probs", "[", "tokens", ",", "parse_preds", "[", "tokens", "]", "]", "# Get new potential root probabilities", "new_root_probs", "=", "root_probs", "/", "old_head_probs", "# Select the most probable root", "new_root", "=", "tokens", "[", "np", ".", "argmax", "(", "new_root_probs", ")", "]", "# Make the change", "parse_preds", "[", "new_root", "]", "=", "0", "# ensure at most one root", "elif", "len", "(", "roots", ")", ">", "1", ":", "# The probabilities of the current heads", "root_probs", "=", "parse_probs", "[", "roots", ",", "0", "]", "# Set the probability of depending on the root zero", "parse_probs", "[", "roots", ",", "0", "]", "=", "0", "# Get new potential heads and their probabilities", "new_heads", "=", "np", ".", "argmax", "(", "parse_probs", "[", "roots", "]", "[", ":", ",", "tokens", "]", ",", "axis", "=", "1", ")", "+", "1", "new_head_probs", "=", "parse_probs", "[", "roots", ",", "new_heads", "]", "/", "root_probs", "# Select the most probable root", "new_root", "=", "roots", "[", "np", ".", "argmin", "(", "new_head_probs", ")", "]", "# Make the change", "parse_preds", "[", "roots", "]", "=", "new_heads", "parse_preds", "[", "new_root", "]", "=", "0", "# remove cycles", "tarjan", "=", "Tarjan", "(", "parse_preds", ",", "tokens", ")", "for", "SCC", "in", "tarjan", ".", "SCCs", ":", "if", "len", "(", "SCC", ")", ">", "1", ":", "dependents", "=", "set", "(", ")", "to_visit", "=", "set", "(", "SCC", ")", "while", "len", "(", "to_visit", ")", ">", "0", ":", "node", "=", "to_visit", ".", "pop", "(", ")", "if", "not", "node", "in", "dependents", ":", "dependents", ".", "add", "(", "node", ")", "to_visit", ".", "update", "(", "tarjan", ".", "edges", "[", "node", "]", ")", "# The indices of the nodes that participate in the cycle", "cycle", "=", "np", ".", "array", "(", "list", "(", "SCC", ")", ")", "# The probabilities of the current heads", "old_heads", "=", "parse_preds", "[", "cycle", "]", "old_head_probs", "=", "parse_probs", "[", "cycle", ",", "old_heads", "]", "# Set the probability of depending on a non-head to zero", "non_heads", "=", "np", ".", "array", "(", "list", "(", "dependents", ")", ")", "parse_probs", "[", "np", ".", "repeat", "(", "cycle", ",", "len", "(", "non_heads", ")", ")", ",", "np", ".", "repeat", "(", "[", "non_heads", "]", ",", "len", "(", "cycle", ")", ",", "axis", "=", "0", ")", ".", "flatten", "(", ")", "]", "=", "0", "# Get new potential heads and their probabilities", "new_heads", "=", "np", ".", "argmax", "(", "parse_probs", "[", "cycle", "]", "[", ":", ",", "tokens", "]", ",", "axis", "=", "1", ")", "+", "1", "new_head_probs", "=", "parse_probs", "[", "cycle", ",", "new_heads", "]", "/", "old_head_probs", "# Select the most probable change", "change", "=", "np", ".", "argmax", "(", "new_head_probs", ")", "changed_cycle", "=", "cycle", "[", "change", "]", "old_head", "=", "old_heads", "[", "change", "]", "new_head", "=", "new_heads", "[", "change", "]", "# Make the change", "parse_preds", "[", "changed_cycle", "]", "=", "new_head", "tarjan", ".", "edges", "[", "new_head", "]", ".", "add", "(", "changed_cycle", ")", "tarjan", ".", "edges", "[", "old_head", "]", ".", "remove", "(", "changed_cycle", ")", "return", "parse_preds", "else", ":", "# block and pad heads", "parse_probs", "=", "parse_probs", "*", "tokens_to_keep", "parse_preds", "=", "np", ".", "argmax", "(", "parse_probs", ",", "axis", "=", "1", ")", "return", "parse_preds" ]
MST Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real sentence length tokens_to_keep : NDArray mask matrix ensure_tree : whether to ensure tree structure of output (apply MST) Returns ------- parse_preds : np.ndarray prediction of arc parsing with size of (seq_len,)
[ "MST", "Adopted", "from", "Timothy", "Dozat", "https", ":", "//", "github", ".", "com", "/", "tdozat", "/", "Parser", "/", "blob", "/", "master", "/", "lib", "/", "models", "/", "nn", ".", "py" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L367-L455
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
rel_argmax
def rel_argmax(rel_probs, length, ensure_tree=True): """Fix the relation prediction by heuristic rules Parameters ---------- rel_probs : NDArray seq_len x rel_size length : real sentence length ensure_tree : whether to apply rules Returns ------- rel_preds : np.ndarray prediction of relations of size (seq_len,) """ if ensure_tree: rel_probs[:, ParserVocabulary.PAD] = 0 root = ParserVocabulary.ROOT tokens = np.arange(1, length) rel_preds = np.argmax(rel_probs, axis=1) roots = np.where(rel_preds[tokens] == root)[0] + 1 if len(roots) < 1: rel_preds[1 + np.argmax(rel_probs[tokens, root])] = root elif len(roots) > 1: root_probs = rel_probs[roots, root] rel_probs[roots, root] = 0 new_rel_preds = np.argmax(rel_probs[roots], axis=1) new_rel_probs = rel_probs[roots, new_rel_preds] / root_probs new_root = roots[np.argmin(new_rel_probs)] rel_preds[roots] = new_rel_preds rel_preds[new_root] = root return rel_preds else: rel_probs[:, ParserVocabulary.PAD] = 0 rel_preds = np.argmax(rel_probs, axis=1) return rel_preds
python
def rel_argmax(rel_probs, length, ensure_tree=True): """Fix the relation prediction by heuristic rules Parameters ---------- rel_probs : NDArray seq_len x rel_size length : real sentence length ensure_tree : whether to apply rules Returns ------- rel_preds : np.ndarray prediction of relations of size (seq_len,) """ if ensure_tree: rel_probs[:, ParserVocabulary.PAD] = 0 root = ParserVocabulary.ROOT tokens = np.arange(1, length) rel_preds = np.argmax(rel_probs, axis=1) roots = np.where(rel_preds[tokens] == root)[0] + 1 if len(roots) < 1: rel_preds[1 + np.argmax(rel_probs[tokens, root])] = root elif len(roots) > 1: root_probs = rel_probs[roots, root] rel_probs[roots, root] = 0 new_rel_preds = np.argmax(rel_probs[roots], axis=1) new_rel_probs = rel_probs[roots, new_rel_preds] / root_probs new_root = roots[np.argmin(new_rel_probs)] rel_preds[roots] = new_rel_preds rel_preds[new_root] = root return rel_preds else: rel_probs[:, ParserVocabulary.PAD] = 0 rel_preds = np.argmax(rel_probs, axis=1) return rel_preds
[ "def", "rel_argmax", "(", "rel_probs", ",", "length", ",", "ensure_tree", "=", "True", ")", ":", "if", "ensure_tree", ":", "rel_probs", "[", ":", ",", "ParserVocabulary", ".", "PAD", "]", "=", "0", "root", "=", "ParserVocabulary", ".", "ROOT", "tokens", "=", "np", ".", "arange", "(", "1", ",", "length", ")", "rel_preds", "=", "np", ".", "argmax", "(", "rel_probs", ",", "axis", "=", "1", ")", "roots", "=", "np", ".", "where", "(", "rel_preds", "[", "tokens", "]", "==", "root", ")", "[", "0", "]", "+", "1", "if", "len", "(", "roots", ")", "<", "1", ":", "rel_preds", "[", "1", "+", "np", ".", "argmax", "(", "rel_probs", "[", "tokens", ",", "root", "]", ")", "]", "=", "root", "elif", "len", "(", "roots", ")", ">", "1", ":", "root_probs", "=", "rel_probs", "[", "roots", ",", "root", "]", "rel_probs", "[", "roots", ",", "root", "]", "=", "0", "new_rel_preds", "=", "np", ".", "argmax", "(", "rel_probs", "[", "roots", "]", ",", "axis", "=", "1", ")", "new_rel_probs", "=", "rel_probs", "[", "roots", ",", "new_rel_preds", "]", "/", "root_probs", "new_root", "=", "roots", "[", "np", ".", "argmin", "(", "new_rel_probs", ")", "]", "rel_preds", "[", "roots", "]", "=", "new_rel_preds", "rel_preds", "[", "new_root", "]", "=", "root", "return", "rel_preds", "else", ":", "rel_probs", "[", ":", ",", "ParserVocabulary", ".", "PAD", "]", "=", "0", "rel_preds", "=", "np", ".", "argmax", "(", "rel_probs", ",", "axis", "=", "1", ")", "return", "rel_preds" ]
Fix the relation prediction by heuristic rules Parameters ---------- rel_probs : NDArray seq_len x rel_size length : real sentence length ensure_tree : whether to apply rules Returns ------- rel_preds : np.ndarray prediction of relations of size (seq_len,)
[ "Fix", "the", "relation", "prediction", "by", "heuristic", "rules" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L458-L494
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
reshape_fortran
def reshape_fortran(tensor, shape): """The missing Fortran reshape for mx.NDArray Parameters ---------- tensor : NDArray source tensor shape : NDArray desired shape Returns ------- output : NDArray reordered result """ return tensor.T.reshape(tuple(reversed(shape))).T
python
def reshape_fortran(tensor, shape): """The missing Fortran reshape for mx.NDArray Parameters ---------- tensor : NDArray source tensor shape : NDArray desired shape Returns ------- output : NDArray reordered result """ return tensor.T.reshape(tuple(reversed(shape))).T
[ "def", "reshape_fortran", "(", "tensor", ",", "shape", ")", ":", "return", "tensor", ".", "T", ".", "reshape", "(", "tuple", "(", "reversed", "(", "shape", ")", ")", ")", ".", "T" ]
The missing Fortran reshape for mx.NDArray Parameters ---------- tensor : NDArray source tensor shape : NDArray desired shape Returns ------- output : NDArray reordered result
[ "The", "missing", "Fortran", "reshape", "for", "mx", ".", "NDArray" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L497-L512
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
Progbar.update
def update(self, current, values=[], exact=[], strict=[]): """ Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. exact: List of tuples (name, value_for_last_step). The progress bar will display these values directly. """ for k, v in values: if k not in self.sum_values: self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far] self.unique_values.append(k) else: self.sum_values[k][0] += v * (current - self.seen_so_far) self.sum_values[k][1] += (current - self.seen_so_far) for cells in exact: k, v, w = cells[0], cells[1], 4 if len(cells) == 3: w = cells[2] if k not in self.sum_values: self.unique_values.append(k) self.sum_values[k] = [v, 1, w] for k, v in strict: if k not in self.sum_values: self.unique_values.append(k) self.sum_values[k] = v self.seen_so_far = current now = time.time() if self.verbose == 1: prev_total_width = self.total_width sys.stdout.write("\b" * prev_total_width) sys.stdout.write("\r") numdigits = 0 if self.target == 0 or math.isnan(self.target) else int(np.floor(np.log10(self.target))) + 1 barstr = '%%%dd/%%%dd [' % (numdigits, numdigits) bar = barstr % (current, self.target) prog = 0 if self.target == 0 else float(current) / self.target prog_width = int(self.width * prog) if prog_width > 0: bar += ('=' * (prog_width - 1)) if current < self.target: bar += '>' else: bar += '=' bar += ('.' * (self.width - prog_width)) bar += ']' sys.stdout.write(bar) self.total_width = len(bar) if current: time_per_unit = (now - self.start) / current else: time_per_unit = 0 eta = time_per_unit * (self.target - current) info = '' if current < self.target: info += ' - ETA: %ds' % eta else: info += ' - %ds' % (now - self.start) for k in self.unique_values: if type(self.sum_values[k]) is list: info += (' - %s: %.' + str(self.sum_values[k][2]) + 'f') % ( k, self.sum_values[k][0] / max(1, self.sum_values[k][1])) else: info += ' - %s: %s' % (k, self.sum_values[k]) self.total_width += len(info) if prev_total_width > self.total_width: info += ((prev_total_width - self.total_width) * " ") sys.stdout.write(info) sys.stdout.flush() if current >= self.target: sys.stdout.write("\n") if self.verbose == 2: if current >= self.target: info = '%ds' % (now - self.start) for k in self.unique_values: info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1])) sys.stdout.write(info + "\n")
python
def update(self, current, values=[], exact=[], strict=[]): """ Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. exact: List of tuples (name, value_for_last_step). The progress bar will display these values directly. """ for k, v in values: if k not in self.sum_values: self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far] self.unique_values.append(k) else: self.sum_values[k][0] += v * (current - self.seen_so_far) self.sum_values[k][1] += (current - self.seen_so_far) for cells in exact: k, v, w = cells[0], cells[1], 4 if len(cells) == 3: w = cells[2] if k not in self.sum_values: self.unique_values.append(k) self.sum_values[k] = [v, 1, w] for k, v in strict: if k not in self.sum_values: self.unique_values.append(k) self.sum_values[k] = v self.seen_so_far = current now = time.time() if self.verbose == 1: prev_total_width = self.total_width sys.stdout.write("\b" * prev_total_width) sys.stdout.write("\r") numdigits = 0 if self.target == 0 or math.isnan(self.target) else int(np.floor(np.log10(self.target))) + 1 barstr = '%%%dd/%%%dd [' % (numdigits, numdigits) bar = barstr % (current, self.target) prog = 0 if self.target == 0 else float(current) / self.target prog_width = int(self.width * prog) if prog_width > 0: bar += ('=' * (prog_width - 1)) if current < self.target: bar += '>' else: bar += '=' bar += ('.' * (self.width - prog_width)) bar += ']' sys.stdout.write(bar) self.total_width = len(bar) if current: time_per_unit = (now - self.start) / current else: time_per_unit = 0 eta = time_per_unit * (self.target - current) info = '' if current < self.target: info += ' - ETA: %ds' % eta else: info += ' - %ds' % (now - self.start) for k in self.unique_values: if type(self.sum_values[k]) is list: info += (' - %s: %.' + str(self.sum_values[k][2]) + 'f') % ( k, self.sum_values[k][0] / max(1, self.sum_values[k][1])) else: info += ' - %s: %s' % (k, self.sum_values[k]) self.total_width += len(info) if prev_total_width > self.total_width: info += ((prev_total_width - self.total_width) * " ") sys.stdout.write(info) sys.stdout.flush() if current >= self.target: sys.stdout.write("\n") if self.verbose == 2: if current >= self.target: info = '%ds' % (now - self.start) for k in self.unique_values: info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1])) sys.stdout.write(info + "\n")
[ "def", "update", "(", "self", ",", "current", ",", "values", "=", "[", "]", ",", "exact", "=", "[", "]", ",", "strict", "=", "[", "]", ")", ":", "for", "k", ",", "v", "in", "values", ":", "if", "k", "not", "in", "self", ".", "sum_values", ":", "self", ".", "sum_values", "[", "k", "]", "=", "[", "v", "*", "(", "current", "-", "self", ".", "seen_so_far", ")", ",", "current", "-", "self", ".", "seen_so_far", "]", "self", ".", "unique_values", ".", "append", "(", "k", ")", "else", ":", "self", ".", "sum_values", "[", "k", "]", "[", "0", "]", "+=", "v", "*", "(", "current", "-", "self", ".", "seen_so_far", ")", "self", ".", "sum_values", "[", "k", "]", "[", "1", "]", "+=", "(", "current", "-", "self", ".", "seen_so_far", ")", "for", "cells", "in", "exact", ":", "k", ",", "v", ",", "w", "=", "cells", "[", "0", "]", ",", "cells", "[", "1", "]", ",", "4", "if", "len", "(", "cells", ")", "==", "3", ":", "w", "=", "cells", "[", "2", "]", "if", "k", "not", "in", "self", ".", "sum_values", ":", "self", ".", "unique_values", ".", "append", "(", "k", ")", "self", ".", "sum_values", "[", "k", "]", "=", "[", "v", ",", "1", ",", "w", "]", "for", "k", ",", "v", "in", "strict", ":", "if", "k", "not", "in", "self", ".", "sum_values", ":", "self", ".", "unique_values", ".", "append", "(", "k", ")", "self", ".", "sum_values", "[", "k", "]", "=", "v", "self", ".", "seen_so_far", "=", "current", "now", "=", "time", ".", "time", "(", ")", "if", "self", ".", "verbose", "==", "1", ":", "prev_total_width", "=", "self", ".", "total_width", "sys", ".", "stdout", ".", "write", "(", "\"\\b\"", "*", "prev_total_width", ")", "sys", ".", "stdout", ".", "write", "(", "\"\\r\"", ")", "numdigits", "=", "0", "if", "self", ".", "target", "==", "0", "or", "math", ".", "isnan", "(", "self", ".", "target", ")", "else", "int", "(", "np", ".", "floor", "(", "np", ".", "log10", "(", "self", ".", "target", ")", ")", ")", "+", "1", "barstr", "=", "'%%%dd/%%%dd ['", "%", "(", "numdigits", ",", "numdigits", ")", "bar", "=", "barstr", "%", "(", "current", ",", "self", ".", "target", ")", "prog", "=", "0", "if", "self", ".", "target", "==", "0", "else", "float", "(", "current", ")", "/", "self", ".", "target", "prog_width", "=", "int", "(", "self", ".", "width", "*", "prog", ")", "if", "prog_width", ">", "0", ":", "bar", "+=", "(", "'='", "*", "(", "prog_width", "-", "1", ")", ")", "if", "current", "<", "self", ".", "target", ":", "bar", "+=", "'>'", "else", ":", "bar", "+=", "'='", "bar", "+=", "(", "'.'", "*", "(", "self", ".", "width", "-", "prog_width", ")", ")", "bar", "+=", "']'", "sys", ".", "stdout", ".", "write", "(", "bar", ")", "self", ".", "total_width", "=", "len", "(", "bar", ")", "if", "current", ":", "time_per_unit", "=", "(", "now", "-", "self", ".", "start", ")", "/", "current", "else", ":", "time_per_unit", "=", "0", "eta", "=", "time_per_unit", "*", "(", "self", ".", "target", "-", "current", ")", "info", "=", "''", "if", "current", "<", "self", ".", "target", ":", "info", "+=", "' - ETA: %ds'", "%", "eta", "else", ":", "info", "+=", "' - %ds'", "%", "(", "now", "-", "self", ".", "start", ")", "for", "k", "in", "self", ".", "unique_values", ":", "if", "type", "(", "self", ".", "sum_values", "[", "k", "]", ")", "is", "list", ":", "info", "+=", "(", "' - %s: %.'", "+", "str", "(", "self", ".", "sum_values", "[", "k", "]", "[", "2", "]", ")", "+", "'f'", ")", "%", "(", "k", ",", "self", ".", "sum_values", "[", "k", "]", "[", "0", "]", "/", "max", "(", "1", ",", "self", ".", "sum_values", "[", "k", "]", "[", "1", "]", ")", ")", "else", ":", "info", "+=", "' - %s: %s'", "%", "(", "k", ",", "self", ".", "sum_values", "[", "k", "]", ")", "self", ".", "total_width", "+=", "len", "(", "info", ")", "if", "prev_total_width", ">", "self", ".", "total_width", ":", "info", "+=", "(", "(", "prev_total_width", "-", "self", ".", "total_width", ")", "*", "\" \"", ")", "sys", ".", "stdout", ".", "write", "(", "info", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "current", ">=", "self", ".", "target", ":", "sys", ".", "stdout", ".", "write", "(", "\"\\n\"", ")", "if", "self", ".", "verbose", "==", "2", ":", "if", "current", ">=", "self", ".", "target", ":", "info", "=", "'%ds'", "%", "(", "now", "-", "self", ".", "start", ")", "for", "k", "in", "self", ".", "unique_values", ":", "info", "+=", "' - %s: %.4f'", "%", "(", "k", ",", "self", ".", "sum_values", "[", "k", "]", "[", "0", "]", "/", "max", "(", "1", ",", "self", ".", "sum_values", "[", "k", "]", "[", "1", "]", ")", ")", "sys", ".", "stdout", ".", "write", "(", "info", "+", "\"\\n\"", ")" ]
Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. exact: List of tuples (name, value_for_last_step). The progress bar will display these values directly.
[ "Updates", "the", "progress", "bar", ".", "#", "Arguments", "current", ":", "Index", "of", "current", "step", ".", "values", ":", "List", "of", "tuples", "(", "name", "value_for_last_step", ")", ".", "The", "progress", "bar", "will", "display", "averages", "for", "these", "values", ".", "exact", ":", "List", "of", "tuples", "(", "name", "value_for_last_step", ")", ".", "The", "progress", "bar", "will", "display", "these", "values", "directly", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L56-L144
train
dmlc/gluon-nlp
scripts/language_model/word_language_model.py
get_batch
def get_batch(data_source, i, seq_len=None): """Get mini-batches of the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. i : int The index of the batch, starting from 0. seq_len : int The length of each sample in the batch. Returns ------- data: NDArray The context target: NDArray The words to predict """ seq_len = min(seq_len if seq_len else args.bptt, len(data_source) - 1 - i) data = data_source[i:i+seq_len] target = data_source[i+1:i+1+seq_len] return data, target
python
def get_batch(data_source, i, seq_len=None): """Get mini-batches of the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. i : int The index of the batch, starting from 0. seq_len : int The length of each sample in the batch. Returns ------- data: NDArray The context target: NDArray The words to predict """ seq_len = min(seq_len if seq_len else args.bptt, len(data_source) - 1 - i) data = data_source[i:i+seq_len] target = data_source[i+1:i+1+seq_len] return data, target
[ "def", "get_batch", "(", "data_source", ",", "i", ",", "seq_len", "=", "None", ")", ":", "seq_len", "=", "min", "(", "seq_len", "if", "seq_len", "else", "args", ".", "bptt", ",", "len", "(", "data_source", ")", "-", "1", "-", "i", ")", "data", "=", "data_source", "[", "i", ":", "i", "+", "seq_len", "]", "target", "=", "data_source", "[", "i", "+", "1", ":", "i", "+", "1", "+", "seq_len", "]", "return", "data", ",", "target" ]
Get mini-batches of the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. i : int The index of the batch, starting from 0. seq_len : int The length of each sample in the batch. Returns ------- data: NDArray The context target: NDArray The words to predict
[ "Get", "mini", "-", "batches", "of", "the", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L275-L297
train
dmlc/gluon-nlp
scripts/language_model/word_language_model.py
evaluate
def evaluate(data_source, batch_size, params_file_name, ctx=None): """Evaluate the model on the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. params_file_name : str The parameter file to use to evaluate, e.g., val.params or args.save ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float The loss on the dataset """ total_L = 0.0 ntotal = 0 model_eval.load_parameters(params_file_name, context) hidden = model_eval.begin_state(batch_size=batch_size, func=mx.nd.zeros, ctx=context[0]) i = 0 while i < len(data_source) - 1 - 1: data, target = get_batch(data_source, i, seq_len=args.bptt) data = data.as_in_context(ctx) target = target.as_in_context(ctx) output, hidden = model_eval(data, hidden) hidden = detach(hidden) L = loss(output.reshape(-3, -1), target.reshape(-1,)) total_L += mx.nd.sum(L).asscalar() ntotal += L.size i += args.bptt return total_L / ntotal
python
def evaluate(data_source, batch_size, params_file_name, ctx=None): """Evaluate the model on the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. params_file_name : str The parameter file to use to evaluate, e.g., val.params or args.save ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float The loss on the dataset """ total_L = 0.0 ntotal = 0 model_eval.load_parameters(params_file_name, context) hidden = model_eval.begin_state(batch_size=batch_size, func=mx.nd.zeros, ctx=context[0]) i = 0 while i < len(data_source) - 1 - 1: data, target = get_batch(data_source, i, seq_len=args.bptt) data = data.as_in_context(ctx) target = target.as_in_context(ctx) output, hidden = model_eval(data, hidden) hidden = detach(hidden) L = loss(output.reshape(-3, -1), target.reshape(-1,)) total_L += mx.nd.sum(L).asscalar() ntotal += L.size i += args.bptt return total_L / ntotal
[ "def", "evaluate", "(", "data_source", ",", "batch_size", ",", "params_file_name", ",", "ctx", "=", "None", ")", ":", "total_L", "=", "0.0", "ntotal", "=", "0", "model_eval", ".", "load_parameters", "(", "params_file_name", ",", "context", ")", "hidden", "=", "model_eval", ".", "begin_state", "(", "batch_size", "=", "batch_size", ",", "func", "=", "mx", ".", "nd", ".", "zeros", ",", "ctx", "=", "context", "[", "0", "]", ")", "i", "=", "0", "while", "i", "<", "len", "(", "data_source", ")", "-", "1", "-", "1", ":", "data", ",", "target", "=", "get_batch", "(", "data_source", ",", "i", ",", "seq_len", "=", "args", ".", "bptt", ")", "data", "=", "data", ".", "as_in_context", "(", "ctx", ")", "target", "=", "target", ".", "as_in_context", "(", "ctx", ")", "output", ",", "hidden", "=", "model_eval", "(", "data", ",", "hidden", ")", "hidden", "=", "detach", "(", "hidden", ")", "L", "=", "loss", "(", "output", ".", "reshape", "(", "-", "3", ",", "-", "1", ")", ",", "target", ".", "reshape", "(", "-", "1", ",", ")", ")", "total_L", "+=", "mx", ".", "nd", ".", "sum", "(", "L", ")", ".", "asscalar", "(", ")", "ntotal", "+=", "L", ".", "size", "i", "+=", "args", ".", "bptt", "return", "total_L", "/", "ntotal" ]
Evaluate the model on the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. params_file_name : str The parameter file to use to evaluate, e.g., val.params or args.save ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float The loss on the dataset
[ "Evaluate", "the", "model", "on", "the", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L300-L339
train
dmlc/gluon-nlp
scripts/language_model/word_language_model.py
train
def train(): """Training loop for awd language model. """ ntasgd = False best_val = float('Inf') start_train_time = time.time() parameters = model.collect_params() param_dict_avg = None t = 0 avg_trigger = 0 n = 5 valid_losses = [] for epoch in range(args.epochs): total_L = 0.0 start_epoch_time = time.time() start_log_interval_time = time.time() hiddens = [model.begin_state(args.batch_size//len(context), func=mx.nd.zeros, ctx=ctx) for ctx in context] batch_i, i = 0, 0 while i < len(train_data) - 1 - 1: bptt = args.bptt if mx.nd.random.uniform().asscalar() < 0.95 else args.bptt / 2 seq_len = max(5, int(mx.nd.random.normal(bptt, 5).asscalar())) lr_batch_start = trainer.learning_rate trainer.set_learning_rate(lr_batch_start*seq_len/args.bptt) data, target = get_batch(train_data, i, seq_len=seq_len) data_list = gluon.utils.split_and_load(data, context, batch_axis=1, even_split=True) target_list = gluon.utils.split_and_load(target, context, batch_axis=1, even_split=True) hiddens = detach(hiddens) Ls = [] with autograd.record(): for j, (X, y, h) in enumerate(zip(data_list, target_list, hiddens)): output, h, encoder_hs, dropped_encoder_hs = model(X, h) l = joint_loss(output, y, encoder_hs, dropped_encoder_hs) Ls.append(l / (len(context) * X.size)) hiddens[j] = h for L in Ls: L.backward() grads = [p.grad(d.context) for p in parameters.values() for d in data_list] gluon.utils.clip_global_norm(grads, args.clip) if args.ntasgd and ntasgd: if param_dict_avg is None: param_dict_avg = {k.split(model._prefix)[1]: v.data(context[0]).copy() for k, v in parameters.items()} trainer.step(1) if args.ntasgd and ntasgd: gamma = 1.0 / max(1, epoch * (len(train_data) // args.bptt) + batch_i - avg_trigger + 2) for name, param_avg in param_dict_avg.items(): param_avg[:] += gamma * (parameters['{}{}'.format(model._prefix, name)] .data(context[0]) - param_avg) total_L += sum([mx.nd.sum(L).asscalar() for L in Ls]) trainer.set_learning_rate(lr_batch_start) if batch_i % args.log_interval == 0 and batch_i > 0: cur_L = total_L / args.log_interval print('[Epoch %d Batch %d/%d] current loss %.2f, ppl %.2f, ' 'throughput %.2f samples/s, lr %.2f' % (epoch, batch_i, len(train_data) // args.bptt, cur_L, math.exp(cur_L), args.batch_size * args.log_interval / (time.time() - start_log_interval_time), lr_batch_start * seq_len / args.bptt)) total_L = 0.0 start_log_interval_time = time.time() i += seq_len batch_i += 1 mx.nd.waitall() print('[Epoch %d] throughput %.2f samples/s' % ( epoch, (args.batch_size * len(train_data)) / (time.time() - start_epoch_time))) if args.ntasgd and ntasgd: mx.nd.save('{}.val.params'.format(args.save), param_dict_avg) else: model.save_parameters('{}.val.params'.format(args.save)) val_L = evaluate(val_data, val_batch_size, '{}.val.params'.format(args.save), context[0]) print('[Epoch %d] time cost %.2fs, valid loss %.2f, valid ppl %.2f,lr %.2f' % ( epoch, time.time() - start_epoch_time, val_L, math.exp(val_L), trainer.learning_rate)) if args.ntasgd and avg_trigger == 0: if t > n and val_L > min(valid_losses[-n:]): if param_dict_avg is None: param_dict_avg = {k.split(model._prefix)[1]: v.data(context[0]).copy() for k, v in parameters.items()} else: for k, v in parameters.items(): param_dict_avg[k.split(model._prefix)[1]] \ = v.data(context[0]).copy() avg_trigger = epoch * (len(train_data) // args.bptt) + len(train_data) // args.bptt print('Switching to NTASGD and avg_trigger is : %d' % avg_trigger) ntasgd = True valid_losses.append(val_L) t += 1 if val_L < best_val: update_lr_epoch = 0 best_val = val_L if args.ntasgd and ntasgd: mx.nd.save(args.save, param_dict_avg) else: model.save_parameters(args.save) test_L = evaluate(test_data, test_batch_size, args.save, context[0]) print('[Epoch %d] test loss %.2f, test ppl %.2f' % (epoch, test_L, math.exp(test_L))) else: update_lr_epoch += 1 if update_lr_epoch % args.lr_update_interval == 0 and update_lr_epoch != 0: lr_scale = trainer.learning_rate * args.lr_update_factor print('Learning rate after interval update %f' % lr_scale) trainer.set_learning_rate(lr_scale) update_lr_epoch = 0 print('Total training throughput %.2f samples/s' % ((args.batch_size * len(train_data) * args.epochs) / (time.time() - start_train_time)))
python
def train(): """Training loop for awd language model. """ ntasgd = False best_val = float('Inf') start_train_time = time.time() parameters = model.collect_params() param_dict_avg = None t = 0 avg_trigger = 0 n = 5 valid_losses = [] for epoch in range(args.epochs): total_L = 0.0 start_epoch_time = time.time() start_log_interval_time = time.time() hiddens = [model.begin_state(args.batch_size//len(context), func=mx.nd.zeros, ctx=ctx) for ctx in context] batch_i, i = 0, 0 while i < len(train_data) - 1 - 1: bptt = args.bptt if mx.nd.random.uniform().asscalar() < 0.95 else args.bptt / 2 seq_len = max(5, int(mx.nd.random.normal(bptt, 5).asscalar())) lr_batch_start = trainer.learning_rate trainer.set_learning_rate(lr_batch_start*seq_len/args.bptt) data, target = get_batch(train_data, i, seq_len=seq_len) data_list = gluon.utils.split_and_load(data, context, batch_axis=1, even_split=True) target_list = gluon.utils.split_and_load(target, context, batch_axis=1, even_split=True) hiddens = detach(hiddens) Ls = [] with autograd.record(): for j, (X, y, h) in enumerate(zip(data_list, target_list, hiddens)): output, h, encoder_hs, dropped_encoder_hs = model(X, h) l = joint_loss(output, y, encoder_hs, dropped_encoder_hs) Ls.append(l / (len(context) * X.size)) hiddens[j] = h for L in Ls: L.backward() grads = [p.grad(d.context) for p in parameters.values() for d in data_list] gluon.utils.clip_global_norm(grads, args.clip) if args.ntasgd and ntasgd: if param_dict_avg is None: param_dict_avg = {k.split(model._prefix)[1]: v.data(context[0]).copy() for k, v in parameters.items()} trainer.step(1) if args.ntasgd and ntasgd: gamma = 1.0 / max(1, epoch * (len(train_data) // args.bptt) + batch_i - avg_trigger + 2) for name, param_avg in param_dict_avg.items(): param_avg[:] += gamma * (parameters['{}{}'.format(model._prefix, name)] .data(context[0]) - param_avg) total_L += sum([mx.nd.sum(L).asscalar() for L in Ls]) trainer.set_learning_rate(lr_batch_start) if batch_i % args.log_interval == 0 and batch_i > 0: cur_L = total_L / args.log_interval print('[Epoch %d Batch %d/%d] current loss %.2f, ppl %.2f, ' 'throughput %.2f samples/s, lr %.2f' % (epoch, batch_i, len(train_data) // args.bptt, cur_L, math.exp(cur_L), args.batch_size * args.log_interval / (time.time() - start_log_interval_time), lr_batch_start * seq_len / args.bptt)) total_L = 0.0 start_log_interval_time = time.time() i += seq_len batch_i += 1 mx.nd.waitall() print('[Epoch %d] throughput %.2f samples/s' % ( epoch, (args.batch_size * len(train_data)) / (time.time() - start_epoch_time))) if args.ntasgd and ntasgd: mx.nd.save('{}.val.params'.format(args.save), param_dict_avg) else: model.save_parameters('{}.val.params'.format(args.save)) val_L = evaluate(val_data, val_batch_size, '{}.val.params'.format(args.save), context[0]) print('[Epoch %d] time cost %.2fs, valid loss %.2f, valid ppl %.2f,lr %.2f' % ( epoch, time.time() - start_epoch_time, val_L, math.exp(val_L), trainer.learning_rate)) if args.ntasgd and avg_trigger == 0: if t > n and val_L > min(valid_losses[-n:]): if param_dict_avg is None: param_dict_avg = {k.split(model._prefix)[1]: v.data(context[0]).copy() for k, v in parameters.items()} else: for k, v in parameters.items(): param_dict_avg[k.split(model._prefix)[1]] \ = v.data(context[0]).copy() avg_trigger = epoch * (len(train_data) // args.bptt) + len(train_data) // args.bptt print('Switching to NTASGD and avg_trigger is : %d' % avg_trigger) ntasgd = True valid_losses.append(val_L) t += 1 if val_L < best_val: update_lr_epoch = 0 best_val = val_L if args.ntasgd and ntasgd: mx.nd.save(args.save, param_dict_avg) else: model.save_parameters(args.save) test_L = evaluate(test_data, test_batch_size, args.save, context[0]) print('[Epoch %d] test loss %.2f, test ppl %.2f' % (epoch, test_L, math.exp(test_L))) else: update_lr_epoch += 1 if update_lr_epoch % args.lr_update_interval == 0 and update_lr_epoch != 0: lr_scale = trainer.learning_rate * args.lr_update_factor print('Learning rate after interval update %f' % lr_scale) trainer.set_learning_rate(lr_scale) update_lr_epoch = 0 print('Total training throughput %.2f samples/s' % ((args.batch_size * len(train_data) * args.epochs) / (time.time() - start_train_time)))
[ "def", "train", "(", ")", ":", "ntasgd", "=", "False", "best_val", "=", "float", "(", "'Inf'", ")", "start_train_time", "=", "time", ".", "time", "(", ")", "parameters", "=", "model", ".", "collect_params", "(", ")", "param_dict_avg", "=", "None", "t", "=", "0", "avg_trigger", "=", "0", "n", "=", "5", "valid_losses", "=", "[", "]", "for", "epoch", "in", "range", "(", "args", ".", "epochs", ")", ":", "total_L", "=", "0.0", "start_epoch_time", "=", "time", ".", "time", "(", ")", "start_log_interval_time", "=", "time", ".", "time", "(", ")", "hiddens", "=", "[", "model", ".", "begin_state", "(", "args", ".", "batch_size", "//", "len", "(", "context", ")", ",", "func", "=", "mx", ".", "nd", ".", "zeros", ",", "ctx", "=", "ctx", ")", "for", "ctx", "in", "context", "]", "batch_i", ",", "i", "=", "0", ",", "0", "while", "i", "<", "len", "(", "train_data", ")", "-", "1", "-", "1", ":", "bptt", "=", "args", ".", "bptt", "if", "mx", ".", "nd", ".", "random", ".", "uniform", "(", ")", ".", "asscalar", "(", ")", "<", "0.95", "else", "args", ".", "bptt", "/", "2", "seq_len", "=", "max", "(", "5", ",", "int", "(", "mx", ".", "nd", ".", "random", ".", "normal", "(", "bptt", ",", "5", ")", ".", "asscalar", "(", ")", ")", ")", "lr_batch_start", "=", "trainer", ".", "learning_rate", "trainer", ".", "set_learning_rate", "(", "lr_batch_start", "*", "seq_len", "/", "args", ".", "bptt", ")", "data", ",", "target", "=", "get_batch", "(", "train_data", ",", "i", ",", "seq_len", "=", "seq_len", ")", "data_list", "=", "gluon", ".", "utils", ".", "split_and_load", "(", "data", ",", "context", ",", "batch_axis", "=", "1", ",", "even_split", "=", "True", ")", "target_list", "=", "gluon", ".", "utils", ".", "split_and_load", "(", "target", ",", "context", ",", "batch_axis", "=", "1", ",", "even_split", "=", "True", ")", "hiddens", "=", "detach", "(", "hiddens", ")", "Ls", "=", "[", "]", "with", "autograd", ".", "record", "(", ")", ":", "for", "j", ",", "(", "X", ",", "y", ",", "h", ")", "in", "enumerate", "(", "zip", "(", "data_list", ",", "target_list", ",", "hiddens", ")", ")", ":", "output", ",", "h", ",", "encoder_hs", ",", "dropped_encoder_hs", "=", "model", "(", "X", ",", "h", ")", "l", "=", "joint_loss", "(", "output", ",", "y", ",", "encoder_hs", ",", "dropped_encoder_hs", ")", "Ls", ".", "append", "(", "l", "/", "(", "len", "(", "context", ")", "*", "X", ".", "size", ")", ")", "hiddens", "[", "j", "]", "=", "h", "for", "L", "in", "Ls", ":", "L", ".", "backward", "(", ")", "grads", "=", "[", "p", ".", "grad", "(", "d", ".", "context", ")", "for", "p", "in", "parameters", ".", "values", "(", ")", "for", "d", "in", "data_list", "]", "gluon", ".", "utils", ".", "clip_global_norm", "(", "grads", ",", "args", ".", "clip", ")", "if", "args", ".", "ntasgd", "and", "ntasgd", ":", "if", "param_dict_avg", "is", "None", ":", "param_dict_avg", "=", "{", "k", ".", "split", "(", "model", ".", "_prefix", ")", "[", "1", "]", ":", "v", ".", "data", "(", "context", "[", "0", "]", ")", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "parameters", ".", "items", "(", ")", "}", "trainer", ".", "step", "(", "1", ")", "if", "args", ".", "ntasgd", "and", "ntasgd", ":", "gamma", "=", "1.0", "/", "max", "(", "1", ",", "epoch", "*", "(", "len", "(", "train_data", ")", "//", "args", ".", "bptt", ")", "+", "batch_i", "-", "avg_trigger", "+", "2", ")", "for", "name", ",", "param_avg", "in", "param_dict_avg", ".", "items", "(", ")", ":", "param_avg", "[", ":", "]", "+=", "gamma", "*", "(", "parameters", "[", "'{}{}'", ".", "format", "(", "model", ".", "_prefix", ",", "name", ")", "]", ".", "data", "(", "context", "[", "0", "]", ")", "-", "param_avg", ")", "total_L", "+=", "sum", "(", "[", "mx", ".", "nd", ".", "sum", "(", "L", ")", ".", "asscalar", "(", ")", "for", "L", "in", "Ls", "]", ")", "trainer", ".", "set_learning_rate", "(", "lr_batch_start", ")", "if", "batch_i", "%", "args", ".", "log_interval", "==", "0", "and", "batch_i", ">", "0", ":", "cur_L", "=", "total_L", "/", "args", ".", "log_interval", "print", "(", "'[Epoch %d Batch %d/%d] current loss %.2f, ppl %.2f, '", "'throughput %.2f samples/s, lr %.2f'", "%", "(", "epoch", ",", "batch_i", ",", "len", "(", "train_data", ")", "//", "args", ".", "bptt", ",", "cur_L", ",", "math", ".", "exp", "(", "cur_L", ")", ",", "args", ".", "batch_size", "*", "args", ".", "log_interval", "/", "(", "time", ".", "time", "(", ")", "-", "start_log_interval_time", ")", ",", "lr_batch_start", "*", "seq_len", "/", "args", ".", "bptt", ")", ")", "total_L", "=", "0.0", "start_log_interval_time", "=", "time", ".", "time", "(", ")", "i", "+=", "seq_len", "batch_i", "+=", "1", "mx", ".", "nd", ".", "waitall", "(", ")", "print", "(", "'[Epoch %d] throughput %.2f samples/s'", "%", "(", "epoch", ",", "(", "args", ".", "batch_size", "*", "len", "(", "train_data", ")", ")", "/", "(", "time", ".", "time", "(", ")", "-", "start_epoch_time", ")", ")", ")", "if", "args", ".", "ntasgd", "and", "ntasgd", ":", "mx", ".", "nd", ".", "save", "(", "'{}.val.params'", ".", "format", "(", "args", ".", "save", ")", ",", "param_dict_avg", ")", "else", ":", "model", ".", "save_parameters", "(", "'{}.val.params'", ".", "format", "(", "args", ".", "save", ")", ")", "val_L", "=", "evaluate", "(", "val_data", ",", "val_batch_size", ",", "'{}.val.params'", ".", "format", "(", "args", ".", "save", ")", ",", "context", "[", "0", "]", ")", "print", "(", "'[Epoch %d] time cost %.2fs, valid loss %.2f, valid ppl %.2f,lr %.2f' %", "(", "", "epoch", ",", "time", ".", "time", "(", ")", "-", "start_epoch_time", ",", "val_L", ",", "math", ".", "exp", "(", "val_L", ")", ",", "trainer", ".", "learning_rate", ")", ")", "if", "args", ".", "ntasgd", "and", "avg_trigger", "==", "0", ":", "if", "t", ">", "n", "and", "val_L", ">", "min", "(", "valid_losses", "[", "-", "n", ":", "]", ")", ":", "if", "param_dict_avg", "is", "None", ":", "param_dict_avg", "=", "{", "k", ".", "split", "(", "model", ".", "_prefix", ")", "[", "1", "]", ":", "v", ".", "data", "(", "context", "[", "0", "]", ")", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "parameters", ".", "items", "(", ")", "}", "else", ":", "for", "k", ",", "v", "in", "parameters", ".", "items", "(", ")", ":", "param_dict_avg", "[", "k", ".", "split", "(", "model", ".", "_prefix", ")", "[", "1", "]", "]", "=", "v", ".", "data", "(", "context", "[", "0", "]", ")", ".", "copy", "(", ")", "avg_trigger", "=", "epoch", "*", "(", "len", "(", "train_data", ")", "//", "args", ".", "bptt", ")", "+", "len", "(", "train_data", ")", "//", "args", ".", "bptt", "print", "(", "'Switching to NTASGD and avg_trigger is : %d'", "%", "avg_trigger", ")", "ntasgd", "=", "True", "valid_losses", ".", "append", "(", "val_L", ")", "t", "+=", "1", "if", "val_L", "<", "best_val", ":", "update_lr_epoch", "=", "0", "best_val", "=", "val_L", "if", "args", ".", "ntasgd", "and", "ntasgd", ":", "mx", ".", "nd", ".", "save", "(", "args", ".", "save", ",", "param_dict_avg", ")", "else", ":", "model", ".", "save_parameters", "(", "args", ".", "save", ")", "test_L", "=", "evaluate", "(", "test_data", ",", "test_batch_size", ",", "args", ".", "save", ",", "context", "[", "0", "]", ")", "print", "(", "'[Epoch %d] test loss %.2f, test ppl %.2f'", "%", "(", "epoch", ",", "test_L", ",", "math", ".", "exp", "(", "test_L", ")", ")", ")", "else", ":", "update_lr_epoch", "+=", "1", "if", "update_lr_epoch", "%", "args", ".", "lr_update_interval", "==", "0", "and", "update_lr_epoch", "!=", "0", ":", "lr_scale", "=", "trainer", ".", "learning_rate", "*", "args", ".", "lr_update_factor", "print", "(", "'Learning rate after interval update %f'", "%", "lr_scale", ")", "trainer", ".", "set_learning_rate", "(", "lr_scale", ")", "update_lr_epoch", "=", "0", "print", "(", "'Total training throughput %.2f samples/s'", "%", "(", "(", "args", ".", "batch_size", "*", "len", "(", "train_data", ")", "*", "args", ".", "epochs", ")", "/", "(", "time", ".", "time", "(", ")", "-", "start_train_time", ")", ")", ")" ]
Training loop for awd language model.
[ "Training", "loop", "for", "awd", "language", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L342-L463
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
register
def register(class_): """Registers a new word embedding evaluation function. Once registered, we can create an instance with :func:`~gluonnlp.embedding.evaluation.create`. Examples -------- >>> @gluonnlp.embedding.evaluation.register ... class MySimilarityFunction(gluonnlp.embedding.evaluation.WordEmbeddingSimilarityFunction): ... def __init__(self, eps=1e-10): ... pass >>> similarity_function = gluonnlp.embedding.evaluation.create('similarity', ... 'MySimilarityFunction') >>> print(type(similarity_function)) <class 'MySimilarityFunction'> >>> @gluonnlp.embedding.evaluation.register ... class MyAnalogyFunction(gluonnlp.embedding.evaluation.WordEmbeddingAnalogyFunction): ... def __init__(self, k=1, eps=1E-10): ... pass >>> analogy_function = gluonnlp.embedding.evaluation.create('analogy', 'MyAnalogyFunction') >>> print(type(analogy_function)) <class 'MyAnalogyFunction'> """ if issubclass(class_, WordEmbeddingSimilarityFunction): register_ = registry.get_register_func( WordEmbeddingSimilarityFunction, 'word embedding similarity evaluation function') elif issubclass(class_, WordEmbeddingAnalogyFunction): register_ = registry.get_register_func( WordEmbeddingAnalogyFunction, 'word embedding analogy evaluation function') else: raise RuntimeError( 'The custom function must either subclass ' 'WordEmbeddingSimilarityFunction or WordEmbeddingAnalogyFunction') return register_(class_)
python
def register(class_): """Registers a new word embedding evaluation function. Once registered, we can create an instance with :func:`~gluonnlp.embedding.evaluation.create`. Examples -------- >>> @gluonnlp.embedding.evaluation.register ... class MySimilarityFunction(gluonnlp.embedding.evaluation.WordEmbeddingSimilarityFunction): ... def __init__(self, eps=1e-10): ... pass >>> similarity_function = gluonnlp.embedding.evaluation.create('similarity', ... 'MySimilarityFunction') >>> print(type(similarity_function)) <class 'MySimilarityFunction'> >>> @gluonnlp.embedding.evaluation.register ... class MyAnalogyFunction(gluonnlp.embedding.evaluation.WordEmbeddingAnalogyFunction): ... def __init__(self, k=1, eps=1E-10): ... pass >>> analogy_function = gluonnlp.embedding.evaluation.create('analogy', 'MyAnalogyFunction') >>> print(type(analogy_function)) <class 'MyAnalogyFunction'> """ if issubclass(class_, WordEmbeddingSimilarityFunction): register_ = registry.get_register_func( WordEmbeddingSimilarityFunction, 'word embedding similarity evaluation function') elif issubclass(class_, WordEmbeddingAnalogyFunction): register_ = registry.get_register_func( WordEmbeddingAnalogyFunction, 'word embedding analogy evaluation function') else: raise RuntimeError( 'The custom function must either subclass ' 'WordEmbeddingSimilarityFunction or WordEmbeddingAnalogyFunction') return register_(class_)
[ "def", "register", "(", "class_", ")", ":", "if", "issubclass", "(", "class_", ",", "WordEmbeddingSimilarityFunction", ")", ":", "register_", "=", "registry", ".", "get_register_func", "(", "WordEmbeddingSimilarityFunction", ",", "'word embedding similarity evaluation function'", ")", "elif", "issubclass", "(", "class_", ",", "WordEmbeddingAnalogyFunction", ")", ":", "register_", "=", "registry", ".", "get_register_func", "(", "WordEmbeddingAnalogyFunction", ",", "'word embedding analogy evaluation function'", ")", "else", ":", "raise", "RuntimeError", "(", "'The custom function must either subclass '", "'WordEmbeddingSimilarityFunction or WordEmbeddingAnalogyFunction'", ")", "return", "register_", "(", "class_", ")" ]
Registers a new word embedding evaluation function. Once registered, we can create an instance with :func:`~gluonnlp.embedding.evaluation.create`. Examples -------- >>> @gluonnlp.embedding.evaluation.register ... class MySimilarityFunction(gluonnlp.embedding.evaluation.WordEmbeddingSimilarityFunction): ... def __init__(self, eps=1e-10): ... pass >>> similarity_function = gluonnlp.embedding.evaluation.create('similarity', ... 'MySimilarityFunction') >>> print(type(similarity_function)) <class 'MySimilarityFunction'> >>> @gluonnlp.embedding.evaluation.register ... class MyAnalogyFunction(gluonnlp.embedding.evaluation.WordEmbeddingAnalogyFunction): ... def __init__(self, k=1, eps=1E-10): ... pass >>> analogy_function = gluonnlp.embedding.evaluation.create('analogy', 'MyAnalogyFunction') >>> print(type(analogy_function)) <class 'MyAnalogyFunction'>
[ "Registers", "a", "new", "word", "embedding", "evaluation", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L67-L107
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
create
def create(kind, name, **kwargs): """Creates an instance of a registered word embedding evaluation function. Parameters ---------- kind : ['similarity', 'analogy'] Return only valid names for similarity, analogy or both kinds of functions. name : str The evaluation function name (case-insensitive). Returns ------- An instance of :class:`gluonnlp.embedding.evaluation.WordEmbeddingAnalogyFunction`: or :class:`gluonnlp.embedding.evaluation.WordEmbeddingSimilarityFunction`: An instance of the specified evaluation function. """ if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `kind` {}. Use ' '`list_evaluation_functions(kind=None).keys()` to get' 'all the valid kinds of evaluation functions.'.format(kind)) create_ = registry.get_create_func( _REGSITRY_KIND_CLASS_MAP[kind], 'word embedding {} evaluation function'.format(kind)) return create_(name, **kwargs)
python
def create(kind, name, **kwargs): """Creates an instance of a registered word embedding evaluation function. Parameters ---------- kind : ['similarity', 'analogy'] Return only valid names for similarity, analogy or both kinds of functions. name : str The evaluation function name (case-insensitive). Returns ------- An instance of :class:`gluonnlp.embedding.evaluation.WordEmbeddingAnalogyFunction`: or :class:`gluonnlp.embedding.evaluation.WordEmbeddingSimilarityFunction`: An instance of the specified evaluation function. """ if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `kind` {}. Use ' '`list_evaluation_functions(kind=None).keys()` to get' 'all the valid kinds of evaluation functions.'.format(kind)) create_ = registry.get_create_func( _REGSITRY_KIND_CLASS_MAP[kind], 'word embedding {} evaluation function'.format(kind)) return create_(name, **kwargs)
[ "def", "create", "(", "kind", ",", "name", ",", "*", "*", "kwargs", ")", ":", "if", "kind", "not", "in", "_REGSITRY_KIND_CLASS_MAP", ".", "keys", "(", ")", ":", "raise", "KeyError", "(", "'Cannot find `kind` {}. Use '", "'`list_evaluation_functions(kind=None).keys()` to get'", "'all the valid kinds of evaluation functions.'", ".", "format", "(", "kind", ")", ")", "create_", "=", "registry", ".", "get_create_func", "(", "_REGSITRY_KIND_CLASS_MAP", "[", "kind", "]", ",", "'word embedding {} evaluation function'", ".", "format", "(", "kind", ")", ")", "return", "create_", "(", "name", ",", "*", "*", "kwargs", ")" ]
Creates an instance of a registered word embedding evaluation function. Parameters ---------- kind : ['similarity', 'analogy'] Return only valid names for similarity, analogy or both kinds of functions. name : str The evaluation function name (case-insensitive). Returns ------- An instance of :class:`gluonnlp.embedding.evaluation.WordEmbeddingAnalogyFunction`: or :class:`gluonnlp.embedding.evaluation.WordEmbeddingSimilarityFunction`: An instance of the specified evaluation function.
[ "Creates", "an", "instance", "of", "a", "registered", "word", "embedding", "evaluation", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L110-L141
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
list_evaluation_functions
def list_evaluation_functions(kind=None): """Get valid word embedding functions names. Parameters ---------- kind : ['similarity', 'analogy', None] Return only valid names for similarity, analogy or both kinds of functions. Returns ------- dict or list: A list of all the valid evaluation function names for the specified kind. If kind is set to None, returns a dict mapping each valid name to its respective output list. The valid names can be plugged in `gluonnlp.model.word_evaluation_model.create(name)`. """ if kind is None: kind = tuple(_REGSITRY_KIND_CLASS_MAP.keys()) if not isinstance(kind, tuple): if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `kind` {}. Use ' '`list_evaluation_functions(kind=None).keys()` to get all the' 'valid kinds of evaluation functions.'.format(kind)) reg = registry.get_registry(_REGSITRY_KIND_CLASS_MAP[kind]) return list(reg.keys()) else: return {name: list_evaluation_functions(kind=name) for name in kind}
python
def list_evaluation_functions(kind=None): """Get valid word embedding functions names. Parameters ---------- kind : ['similarity', 'analogy', None] Return only valid names for similarity, analogy or both kinds of functions. Returns ------- dict or list: A list of all the valid evaluation function names for the specified kind. If kind is set to None, returns a dict mapping each valid name to its respective output list. The valid names can be plugged in `gluonnlp.model.word_evaluation_model.create(name)`. """ if kind is None: kind = tuple(_REGSITRY_KIND_CLASS_MAP.keys()) if not isinstance(kind, tuple): if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `kind` {}. Use ' '`list_evaluation_functions(kind=None).keys()` to get all the' 'valid kinds of evaluation functions.'.format(kind)) reg = registry.get_registry(_REGSITRY_KIND_CLASS_MAP[kind]) return list(reg.keys()) else: return {name: list_evaluation_functions(kind=name) for name in kind}
[ "def", "list_evaluation_functions", "(", "kind", "=", "None", ")", ":", "if", "kind", "is", "None", ":", "kind", "=", "tuple", "(", "_REGSITRY_KIND_CLASS_MAP", ".", "keys", "(", ")", ")", "if", "not", "isinstance", "(", "kind", ",", "tuple", ")", ":", "if", "kind", "not", "in", "_REGSITRY_KIND_CLASS_MAP", ".", "keys", "(", ")", ":", "raise", "KeyError", "(", "'Cannot find `kind` {}. Use '", "'`list_evaluation_functions(kind=None).keys()` to get all the'", "'valid kinds of evaluation functions.'", ".", "format", "(", "kind", ")", ")", "reg", "=", "registry", ".", "get_registry", "(", "_REGSITRY_KIND_CLASS_MAP", "[", "kind", "]", ")", "return", "list", "(", "reg", ".", "keys", "(", ")", ")", "else", ":", "return", "{", "name", ":", "list_evaluation_functions", "(", "kind", "=", "name", ")", "for", "name", "in", "kind", "}" ]
Get valid word embedding functions names. Parameters ---------- kind : ['similarity', 'analogy', None] Return only valid names for similarity, analogy or both kinds of functions. Returns ------- dict or list: A list of all the valid evaluation function names for the specified kind. If kind is set to None, returns a dict mapping each valid name to its respective output list. The valid names can be plugged in `gluonnlp.model.word_evaluation_model.create(name)`.
[ "Get", "valid", "word", "embedding", "functions", "names", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L144-L175
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
WordEmbeddingSimilarity.hybrid_forward
def hybrid_forward(self, F, words1, words2, weight): # pylint: disable=arguments-differ """Predict the similarity of words1 and words2. Parameters ---------- words1 : Symbol or NDArray The indices of the words the we wish to compare to the words in words2. words2 : Symbol or NDArray The indices of the words the we wish to compare to the words in words1. Returns ------- similarity : Symbol or NDArray The similarity computed by WordEmbeddingSimilarity.similarity_function. """ embeddings_words1 = F.Embedding(words1, weight, input_dim=self._vocab_size, output_dim=self._embed_size) embeddings_words2 = F.Embedding(words2, weight, input_dim=self._vocab_size, output_dim=self._embed_size) similarity = self.similarity(embeddings_words1, embeddings_words2) return similarity
python
def hybrid_forward(self, F, words1, words2, weight): # pylint: disable=arguments-differ """Predict the similarity of words1 and words2. Parameters ---------- words1 : Symbol or NDArray The indices of the words the we wish to compare to the words in words2. words2 : Symbol or NDArray The indices of the words the we wish to compare to the words in words1. Returns ------- similarity : Symbol or NDArray The similarity computed by WordEmbeddingSimilarity.similarity_function. """ embeddings_words1 = F.Embedding(words1, weight, input_dim=self._vocab_size, output_dim=self._embed_size) embeddings_words2 = F.Embedding(words2, weight, input_dim=self._vocab_size, output_dim=self._embed_size) similarity = self.similarity(embeddings_words1, embeddings_words2) return similarity
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "words1", ",", "words2", ",", "weight", ")", ":", "# pylint: disable=arguments-differ", "embeddings_words1", "=", "F", ".", "Embedding", "(", "words1", ",", "weight", ",", "input_dim", "=", "self", ".", "_vocab_size", ",", "output_dim", "=", "self", ".", "_embed_size", ")", "embeddings_words2", "=", "F", ".", "Embedding", "(", "words2", ",", "weight", ",", "input_dim", "=", "self", ".", "_vocab_size", ",", "output_dim", "=", "self", ".", "_embed_size", ")", "similarity", "=", "self", ".", "similarity", "(", "embeddings_words1", ",", "embeddings_words2", ")", "return", "similarity" ]
Predict the similarity of words1 and words2. Parameters ---------- words1 : Symbol or NDArray The indices of the words the we wish to compare to the words in words2. words2 : Symbol or NDArray The indices of the words the we wish to compare to the words in words1. Returns ------- similarity : Symbol or NDArray The similarity computed by WordEmbeddingSimilarity.similarity_function.
[ "Predict", "the", "similarity", "of", "words1", "and", "words2", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L439-L461
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
WordEmbeddingAnalogy.hybrid_forward
def hybrid_forward(self, F, words1, words2, words3): # pylint: disable=arguments-differ, unused-argument """Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words2 : Symbol or NDArray Word indices of second question words. Shape (batch_size, ). words3 : Symbol or NDArray Word indices of third question words. Shape (batch_size, ). Returns ------- predicted_indices : Symbol or NDArray Indices of predicted analogies of shape (batch_size, k) """ return self.analogy(words1, words2, words3)
python
def hybrid_forward(self, F, words1, words2, words3): # pylint: disable=arguments-differ, unused-argument """Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words2 : Symbol or NDArray Word indices of second question words. Shape (batch_size, ). words3 : Symbol or NDArray Word indices of third question words. Shape (batch_size, ). Returns ------- predicted_indices : Symbol or NDArray Indices of predicted analogies of shape (batch_size, k) """ return self.analogy(words1, words2, words3)
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "words1", ",", "words2", ",", "words3", ")", ":", "# pylint: disable=arguments-differ, unused-argument", "return", "self", ".", "analogy", "(", "words1", ",", "words2", ",", "words3", ")" ]
Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words2 : Symbol or NDArray Word indices of second question words. Shape (batch_size, ). words3 : Symbol or NDArray Word indices of third question words. Shape (batch_size, ). Returns ------- predicted_indices : Symbol or NDArray Indices of predicted analogies of shape (batch_size, k)
[ "Compute", "analogies", "for", "given", "question", "words", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L501-L518
train
dmlc/gluon-nlp
scripts/language_model/cache_language_model.py
evaluate
def evaluate(data_source, batch_size, ctx=None): """Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float The loss on the dataset """ total_L = 0 hidden = cache_cell.\ begin_state(func=mx.nd.zeros, batch_size=batch_size, ctx=context[0]) next_word_history = None cache_history = None for i in range(0, len(data_source) - 1, args.bptt): if i > 0: print('Batch %d/%d, ppl %f'% (i, len(data_source), math.exp(total_L/i))) data, target = get_batch(data_source, i) data = data.as_in_context(ctx) target = target.as_in_context(ctx) L = 0 outs, next_word_history, cache_history, hidden = \ cache_cell(data, target, next_word_history, cache_history, hidden) for out in outs: L += (-mx.nd.log(out)).asscalar() total_L += L / data.shape[1] hidden = detach(hidden) return total_L / len(data_source)
python
def evaluate(data_source, batch_size, ctx=None): """Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float The loss on the dataset """ total_L = 0 hidden = cache_cell.\ begin_state(func=mx.nd.zeros, batch_size=batch_size, ctx=context[0]) next_word_history = None cache_history = None for i in range(0, len(data_source) - 1, args.bptt): if i > 0: print('Batch %d/%d, ppl %f'% (i, len(data_source), math.exp(total_L/i))) data, target = get_batch(data_source, i) data = data.as_in_context(ctx) target = target.as_in_context(ctx) L = 0 outs, next_word_history, cache_history, hidden = \ cache_cell(data, target, next_word_history, cache_history, hidden) for out in outs: L += (-mx.nd.log(out)).asscalar() total_L += L / data.shape[1] hidden = detach(hidden) return total_L / len(data_source)
[ "def", "evaluate", "(", "data_source", ",", "batch_size", ",", "ctx", "=", "None", ")", ":", "total_L", "=", "0", "hidden", "=", "cache_cell", ".", "begin_state", "(", "func", "=", "mx", ".", "nd", ".", "zeros", ",", "batch_size", "=", "batch_size", ",", "ctx", "=", "context", "[", "0", "]", ")", "next_word_history", "=", "None", "cache_history", "=", "None", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data_source", ")", "-", "1", ",", "args", ".", "bptt", ")", ":", "if", "i", ">", "0", ":", "print", "(", "'Batch %d/%d, ppl %f'", "%", "(", "i", ",", "len", "(", "data_source", ")", ",", "math", ".", "exp", "(", "total_L", "/", "i", ")", ")", ")", "data", ",", "target", "=", "get_batch", "(", "data_source", ",", "i", ")", "data", "=", "data", ".", "as_in_context", "(", "ctx", ")", "target", "=", "target", ".", "as_in_context", "(", "ctx", ")", "L", "=", "0", "outs", ",", "next_word_history", ",", "cache_history", ",", "hidden", "=", "cache_cell", "(", "data", ",", "target", ",", "next_word_history", ",", "cache_history", ",", "hidden", ")", "for", "out", "in", "outs", ":", "L", "+=", "(", "-", "mx", ".", "nd", ".", "log", "(", "out", ")", ")", ".", "asscalar", "(", ")", "total_L", "+=", "L", "/", "data", ".", "shape", "[", "1", "]", "hidden", "=", "detach", "(", "hidden", ")", "return", "total_L", "/", "len", "(", "data_source", ")" ]
Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float The loss on the dataset
[ "Evaluate", "the", "model", "on", "the", "dataset", "with", "cache", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/cache_language_model.py#L167-L203
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert.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'. 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 = {'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'. 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 = {'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", "=", "{", "'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'. 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/scripts/bert/staticbert/static_bert.py#L572-L605
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert.py
bert_12_768_12
def bert_12_768_12(dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), use_pooler=True, use_decoder=True, use_classifier=True, input_size=None, seq_length=None, **kwargs): """Static BERT BASE model. The number of layers (L) is 12, number of units (H) is 768, and the number of self-attention heads (A) is 12. Parameters ---------- dataset_name : str or None, default None Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased', 'wiki_cn_cased', 'wiki_multilingual_uncased' and 'wiki_multilingual_cased'. vocab : gluonnlp.vocab.BERTVocab or None, default None Vocabulary for the dataset. Must be provided if dataset is not specified. pretrained : bool, default True Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. use_pooler : bool, default True Whether to include the pooler which converts the encoded sequence tensor of shape (batch_size, seq_length, units) to a tensor of shape (batch_size, units) for for segment level classification task. use_decoder : bool, default True Whether to include the decoder for masked language model prediction. use_classifier : bool, default True Whether to include the classifier for next sentence classification. input_size : int, default None Represents the embedding size of the input. seq_length : int, default None Stands for the sequence length of the input. Returns ------- StaticBERTModel, gluonnlp.vocab.BERTVocab """ return get_static_bert_model(model_name='bert_12_768_12', vocab=vocab, dataset_name=dataset_name, pretrained=pretrained, ctx=ctx, use_pooler=use_pooler, use_decoder=use_decoder, use_classifier=use_classifier, root=root, input_size=input_size, seq_length=seq_length, **kwargs)
python
def bert_12_768_12(dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), use_pooler=True, use_decoder=True, use_classifier=True, input_size=None, seq_length=None, **kwargs): """Static BERT BASE model. The number of layers (L) is 12, number of units (H) is 768, and the number of self-attention heads (A) is 12. Parameters ---------- dataset_name : str or None, default None Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased', 'wiki_cn_cased', 'wiki_multilingual_uncased' and 'wiki_multilingual_cased'. vocab : gluonnlp.vocab.BERTVocab or None, default None Vocabulary for the dataset. Must be provided if dataset is not specified. pretrained : bool, default True Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. use_pooler : bool, default True Whether to include the pooler which converts the encoded sequence tensor of shape (batch_size, seq_length, units) to a tensor of shape (batch_size, units) for for segment level classification task. use_decoder : bool, default True Whether to include the decoder for masked language model prediction. use_classifier : bool, default True Whether to include the classifier for next sentence classification. input_size : int, default None Represents the embedding size of the input. seq_length : int, default None Stands for the sequence length of the input. Returns ------- StaticBERTModel, gluonnlp.vocab.BERTVocab """ return get_static_bert_model(model_name='bert_12_768_12', vocab=vocab, dataset_name=dataset_name, pretrained=pretrained, ctx=ctx, use_pooler=use_pooler, use_decoder=use_decoder, use_classifier=use_classifier, root=root, input_size=input_size, seq_length=seq_length, **kwargs)
[ "def", "bert_12_768_12", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "True", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ")", ",", "use_pooler", "=", "True", ",", "use_decoder", "=", "True", ",", "use_classifier", "=", "True", ",", "input_size", "=", "None", ",", "seq_length", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "get_static_bert_model", "(", "model_name", "=", "'bert_12_768_12'", ",", "vocab", "=", "vocab", ",", "dataset_name", "=", "dataset_name", ",", "pretrained", "=", "pretrained", ",", "ctx", "=", "ctx", ",", "use_pooler", "=", "use_pooler", ",", "use_decoder", "=", "use_decoder", ",", "use_classifier", "=", "use_classifier", ",", "root", "=", "root", ",", "input_size", "=", "input_size", ",", "seq_length", "=", "seq_length", ",", "*", "*", "kwargs", ")" ]
Static BERT BASE model. The number of layers (L) is 12, number of units (H) is 768, and the number of self-attention heads (A) is 12. Parameters ---------- dataset_name : str or None, default None Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased', 'wiki_cn_cased', 'wiki_multilingual_uncased' and 'wiki_multilingual_cased'. vocab : gluonnlp.vocab.BERTVocab or None, default None Vocabulary for the dataset. Must be provided if dataset is not specified. pretrained : bool, default True Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. MXNET_HOME defaults to '~/.mxnet'. use_pooler : bool, default True Whether to include the pooler which converts the encoded sequence tensor of shape (batch_size, seq_length, units) to a tensor of shape (batch_size, units) for for segment level classification task. use_decoder : bool, default True Whether to include the decoder for masked language model prediction. use_classifier : bool, default True Whether to include the classifier for next sentence classification. input_size : int, default None Represents the embedding size of the input. seq_length : int, default None Stands for the sequence length of the input. Returns ------- StaticBERTModel, gluonnlp.vocab.BERTVocab
[ "Static", "BERT", "BASE", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L608-L652
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert.py
StaticBERTModel.hybrid_forward
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model. """ outputs = [] seq_out, attention_out = self._encode_sequence(F, inputs, token_types, valid_length) outputs.append(seq_out) if self.encoder._output_all_encodings: assert isinstance(seq_out, list) output = seq_out[-1] else: output = seq_out if attention_out: outputs.append(attention_out) if self._use_pooler: pooled_out = self._apply_pooling(output) outputs.append(pooled_out) if self._use_classifier: next_sentence_classifier_out = self.classifier(pooled_out) outputs.append(next_sentence_classifier_out) if self._use_decoder: assert masked_positions is not None, \ 'masked_positions tensor is required for decoding masked language model' decoder_out = self._decode(output, masked_positions) outputs.append(decoder_out) return tuple(outputs) if len(outputs) > 1 else outputs[0]
python
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model. """ outputs = [] seq_out, attention_out = self._encode_sequence(F, inputs, token_types, valid_length) outputs.append(seq_out) if self.encoder._output_all_encodings: assert isinstance(seq_out, list) output = seq_out[-1] else: output = seq_out if attention_out: outputs.append(attention_out) if self._use_pooler: pooled_out = self._apply_pooling(output) outputs.append(pooled_out) if self._use_classifier: next_sentence_classifier_out = self.classifier(pooled_out) outputs.append(next_sentence_classifier_out) if self._use_decoder: assert masked_positions is not None, \ 'masked_positions tensor is required for decoding masked language model' decoder_out = self._decode(output, masked_positions) outputs.append(decoder_out) return tuple(outputs) if len(outputs) > 1 else outputs[0]
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ",", "masked_positions", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "outputs", "=", "[", "]", "seq_out", ",", "attention_out", "=", "self", ".", "_encode_sequence", "(", "F", ",", "inputs", ",", "token_types", ",", "valid_length", ")", "outputs", ".", "append", "(", "seq_out", ")", "if", "self", ".", "encoder", ".", "_output_all_encodings", ":", "assert", "isinstance", "(", "seq_out", ",", "list", ")", "output", "=", "seq_out", "[", "-", "1", "]", "else", ":", "output", "=", "seq_out", "if", "attention_out", ":", "outputs", ".", "append", "(", "attention_out", ")", "if", "self", ".", "_use_pooler", ":", "pooled_out", "=", "self", ".", "_apply_pooling", "(", "output", ")", "outputs", ".", "append", "(", "pooled_out", ")", "if", "self", ".", "_use_classifier", ":", "next_sentence_classifier_out", "=", "self", ".", "classifier", "(", "pooled_out", ")", "outputs", ".", "append", "(", "next_sentence_classifier_out", ")", "if", "self", ".", "_use_decoder", ":", "assert", "masked_positions", "is", "not", "None", ",", "'masked_positions tensor is required for decoding masked language model'", "decoder_out", "=", "self", ".", "_decode", "(", "output", ",", "masked_positions", ")", "outputs", ".", "append", "(", "decoder_out", ")", "return", "tuple", "(", "outputs", ")", "if", "len", "(", "outputs", ")", ">", "1", "else", "outputs", "[", "0", "]" ]
Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model.
[ "Generate", "the", "representation", "given", "the", "inputs", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L481-L512
train
dmlc/gluon-nlp
src/gluonnlp/model/train/cache.py
CacheCell.load_parameters
def load_parameters(self, filename, ctx=mx.cpu()): # pylint: disable=arguments-differ """Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on. """ self.lm_model.load_parameters(filename, ctx=ctx)
python
def load_parameters(self, filename, ctx=mx.cpu()): # pylint: disable=arguments-differ """Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on. """ self.lm_model.load_parameters(filename, ctx=ctx)
[ "def", "load_parameters", "(", "self", ",", "filename", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ")", ":", "# pylint: disable=arguments-differ", "self", ".", "lm_model", ".", "load_parameters", "(", "filename", ",", "ctx", "=", "ctx", ")" ]
Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on.
[ "Load", "parameters", "from", "file", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/cache.py#L84-L92
train
dmlc/gluon-nlp
src/gluonnlp/model/train/cache.py
CacheCell.forward
def forward(self, inputs, target, next_word_history, cache_history, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray The input data target: NDArray The label next_word_history: NDArray The next word in memory cache_history: NDArray The hidden state in cache history Returns -------- out: NDArray The linear interpolation of the cache language model with the regular word-level language model next_word_history: NDArray The next words to be kept in the memory for look up (size is equal to the window size) cache_history: NDArray The hidden states to be kept in the memory for look up (size is equal to the window size) """ output, hidden, encoder_hs, _ = \ super(self.lm_model.__class__, self.lm_model).\ forward(inputs, begin_state) encoder_h = encoder_hs[-1].reshape(-3, -2) output = output.reshape(-1, self._vocab_size) start_idx = len(next_word_history) \ if next_word_history is not None else 0 next_word_history = nd.concat(*[nd.one_hot(t[0], self._vocab_size, on_value=1, off_value=0) for t in target], dim=0) if next_word_history is None \ else nd.concat(next_word_history, nd.concat(*[nd.one_hot(t[0], self._vocab_size, on_value=1, off_value=0) for t in target], dim=0), dim=0) cache_history = encoder_h if cache_history is None \ else nd.concat(cache_history, encoder_h, dim=0) out = None softmax_output = nd.softmax(output) for idx, vocab_L in enumerate(softmax_output): joint_p = vocab_L if start_idx + idx > self._window: valid_next_word = next_word_history[start_idx + idx - self._window:start_idx + idx] valid_cache_history = cache_history[start_idx + idx - self._window:start_idx + idx] logits = nd.dot(valid_cache_history, encoder_h[idx]) cache_attn = nd.softmax(self._theta * logits).reshape(-1, 1) cache_dist = (cache_attn.broadcast_to(valid_next_word.shape) * valid_next_word).sum(axis=0) joint_p = self._lambdas * cache_dist + (1 - self._lambdas) * vocab_L out = joint_p[target[idx]] if out is None \ else nd.concat(out, joint_p[target[idx]], dim=0) next_word_history = next_word_history[-self._window:] cache_history = cache_history[-self._window:] return out, next_word_history, cache_history, hidden
python
def forward(self, inputs, target, next_word_history, cache_history, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray The input data target: NDArray The label next_word_history: NDArray The next word in memory cache_history: NDArray The hidden state in cache history Returns -------- out: NDArray The linear interpolation of the cache language model with the regular word-level language model next_word_history: NDArray The next words to be kept in the memory for look up (size is equal to the window size) cache_history: NDArray The hidden states to be kept in the memory for look up (size is equal to the window size) """ output, hidden, encoder_hs, _ = \ super(self.lm_model.__class__, self.lm_model).\ forward(inputs, begin_state) encoder_h = encoder_hs[-1].reshape(-3, -2) output = output.reshape(-1, self._vocab_size) start_idx = len(next_word_history) \ if next_word_history is not None else 0 next_word_history = nd.concat(*[nd.one_hot(t[0], self._vocab_size, on_value=1, off_value=0) for t in target], dim=0) if next_word_history is None \ else nd.concat(next_word_history, nd.concat(*[nd.one_hot(t[0], self._vocab_size, on_value=1, off_value=0) for t in target], dim=0), dim=0) cache_history = encoder_h if cache_history is None \ else nd.concat(cache_history, encoder_h, dim=0) out = None softmax_output = nd.softmax(output) for idx, vocab_L in enumerate(softmax_output): joint_p = vocab_L if start_idx + idx > self._window: valid_next_word = next_word_history[start_idx + idx - self._window:start_idx + idx] valid_cache_history = cache_history[start_idx + idx - self._window:start_idx + idx] logits = nd.dot(valid_cache_history, encoder_h[idx]) cache_attn = nd.softmax(self._theta * logits).reshape(-1, 1) cache_dist = (cache_attn.broadcast_to(valid_next_word.shape) * valid_next_word).sum(axis=0) joint_p = self._lambdas * cache_dist + (1 - self._lambdas) * vocab_L out = joint_p[target[idx]] if out is None \ else nd.concat(out, joint_p[target[idx]], dim=0) next_word_history = next_word_history[-self._window:] cache_history = cache_history[-self._window:] return out, next_word_history, cache_history, hidden
[ "def", "forward", "(", "self", ",", "inputs", ",", "target", ",", "next_word_history", ",", "cache_history", ",", "begin_state", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "output", ",", "hidden", ",", "encoder_hs", ",", "_", "=", "super", "(", "self", ".", "lm_model", ".", "__class__", ",", "self", ".", "lm_model", ")", ".", "forward", "(", "inputs", ",", "begin_state", ")", "encoder_h", "=", "encoder_hs", "[", "-", "1", "]", ".", "reshape", "(", "-", "3", ",", "-", "2", ")", "output", "=", "output", ".", "reshape", "(", "-", "1", ",", "self", ".", "_vocab_size", ")", "start_idx", "=", "len", "(", "next_word_history", ")", "if", "next_word_history", "is", "not", "None", "else", "0", "next_word_history", "=", "nd", ".", "concat", "(", "*", "[", "nd", ".", "one_hot", "(", "t", "[", "0", "]", ",", "self", ".", "_vocab_size", ",", "on_value", "=", "1", ",", "off_value", "=", "0", ")", "for", "t", "in", "target", "]", ",", "dim", "=", "0", ")", "if", "next_word_history", "is", "None", "else", "nd", ".", "concat", "(", "next_word_history", ",", "nd", ".", "concat", "(", "*", "[", "nd", ".", "one_hot", "(", "t", "[", "0", "]", ",", "self", ".", "_vocab_size", ",", "on_value", "=", "1", ",", "off_value", "=", "0", ")", "for", "t", "in", "target", "]", ",", "dim", "=", "0", ")", ",", "dim", "=", "0", ")", "cache_history", "=", "encoder_h", "if", "cache_history", "is", "None", "else", "nd", ".", "concat", "(", "cache_history", ",", "encoder_h", ",", "dim", "=", "0", ")", "out", "=", "None", "softmax_output", "=", "nd", ".", "softmax", "(", "output", ")", "for", "idx", ",", "vocab_L", "in", "enumerate", "(", "softmax_output", ")", ":", "joint_p", "=", "vocab_L", "if", "start_idx", "+", "idx", ">", "self", ".", "_window", ":", "valid_next_word", "=", "next_word_history", "[", "start_idx", "+", "idx", "-", "self", ".", "_window", ":", "start_idx", "+", "idx", "]", "valid_cache_history", "=", "cache_history", "[", "start_idx", "+", "idx", "-", "self", ".", "_window", ":", "start_idx", "+", "idx", "]", "logits", "=", "nd", ".", "dot", "(", "valid_cache_history", ",", "encoder_h", "[", "idx", "]", ")", "cache_attn", "=", "nd", ".", "softmax", "(", "self", ".", "_theta", "*", "logits", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", "cache_dist", "=", "(", "cache_attn", ".", "broadcast_to", "(", "valid_next_word", ".", "shape", ")", "*", "valid_next_word", ")", ".", "sum", "(", "axis", "=", "0", ")", "joint_p", "=", "self", ".", "_lambdas", "*", "cache_dist", "+", "(", "1", "-", "self", ".", "_lambdas", ")", "*", "vocab_L", "out", "=", "joint_p", "[", "target", "[", "idx", "]", "]", "if", "out", "is", "None", "else", "nd", ".", "concat", "(", "out", ",", "joint_p", "[", "target", "[", "idx", "]", "]", ",", "dim", "=", "0", ")", "next_word_history", "=", "next_word_history", "[", "-", "self", ".", "_window", ":", "]", "cache_history", "=", "cache_history", "[", "-", "self", ".", "_window", ":", "]", "return", "out", ",", "next_word_history", ",", "cache_history", ",", "hidden" ]
Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray The input data target: NDArray The label next_word_history: NDArray The next word in memory cache_history: NDArray The hidden state in cache history Returns -------- out: NDArray The linear interpolation of the cache language model with the regular word-level language model next_word_history: NDArray The next words to be kept in the memory for look up (size is equal to the window size) cache_history: NDArray The hidden states to be kept in the memory for look up (size is equal to the window size)
[ "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/train/cache.py#L100-L161
train
dmlc/gluon-nlp
src/gluonnlp/utils/parallel.py
Parallel.put
def put(self, x): """Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x. """ if self._num_serial > 0 or len(self._threads) == 0: self._num_serial -= 1 out = self._parallizable.forward_backward(x) self._out_queue.put(out) else: self._in_queue.put(x)
python
def put(self, x): """Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x. """ if self._num_serial > 0 or len(self._threads) == 0: self._num_serial -= 1 out = self._parallizable.forward_backward(x) self._out_queue.put(out) else: self._in_queue.put(x)
[ "def", "put", "(", "self", ",", "x", ")", ":", "if", "self", ".", "_num_serial", ">", "0", "or", "len", "(", "self", ".", "_threads", ")", "==", "0", ":", "self", ".", "_num_serial", "-=", "1", "out", "=", "self", ".", "_parallizable", ".", "forward_backward", "(", "x", ")", "self", ".", "_out_queue", ".", "put", "(", "out", ")", "else", ":", "self", ".", "_in_queue", ".", "put", "(", "x", ")" ]
Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x.
[ "Assign", "input", "x", "to", "an", "available", "worker", "and", "invoke", "parallizable", ".", "forward_backward", "with", "x", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/utils/parallel.py#L130-L138
train
dmlc/gluon-nlp
src/gluonnlp/vocab/bert.py
BERTVocab.from_json
def from_json(cls, json_str): """Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab """ vocab_dict = json.loads(json_str) unknown_token = vocab_dict.get('unknown_token') bert_vocab = cls(unknown_token=unknown_token) bert_vocab._idx_to_token = vocab_dict.get('idx_to_token') bert_vocab._token_to_idx = vocab_dict.get('token_to_idx') if unknown_token: bert_vocab._token_to_idx = DefaultLookupDict(bert_vocab._token_to_idx[unknown_token], bert_vocab._token_to_idx) bert_vocab._reserved_tokens = vocab_dict.get('reserved_tokens') bert_vocab._padding_token = vocab_dict.get('padding_token') bert_vocab._bos_token = vocab_dict.get('bos_token') bert_vocab._eos_token = vocab_dict.get('eos_token') bert_vocab._mask_token = vocab_dict.get('mask_token') bert_vocab._sep_token = vocab_dict.get('sep_token') bert_vocab._cls_token = vocab_dict.get('cls_token') return bert_vocab
python
def from_json(cls, json_str): """Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab """ vocab_dict = json.loads(json_str) unknown_token = vocab_dict.get('unknown_token') bert_vocab = cls(unknown_token=unknown_token) bert_vocab._idx_to_token = vocab_dict.get('idx_to_token') bert_vocab._token_to_idx = vocab_dict.get('token_to_idx') if unknown_token: bert_vocab._token_to_idx = DefaultLookupDict(bert_vocab._token_to_idx[unknown_token], bert_vocab._token_to_idx) bert_vocab._reserved_tokens = vocab_dict.get('reserved_tokens') bert_vocab._padding_token = vocab_dict.get('padding_token') bert_vocab._bos_token = vocab_dict.get('bos_token') bert_vocab._eos_token = vocab_dict.get('eos_token') bert_vocab._mask_token = vocab_dict.get('mask_token') bert_vocab._sep_token = vocab_dict.get('sep_token') bert_vocab._cls_token = vocab_dict.get('cls_token') return bert_vocab
[ "def", "from_json", "(", "cls", ",", "json_str", ")", ":", "vocab_dict", "=", "json", ".", "loads", "(", "json_str", ")", "unknown_token", "=", "vocab_dict", ".", "get", "(", "'unknown_token'", ")", "bert_vocab", "=", "cls", "(", "unknown_token", "=", "unknown_token", ")", "bert_vocab", ".", "_idx_to_token", "=", "vocab_dict", ".", "get", "(", "'idx_to_token'", ")", "bert_vocab", ".", "_token_to_idx", "=", "vocab_dict", ".", "get", "(", "'token_to_idx'", ")", "if", "unknown_token", ":", "bert_vocab", ".", "_token_to_idx", "=", "DefaultLookupDict", "(", "bert_vocab", ".", "_token_to_idx", "[", "unknown_token", "]", ",", "bert_vocab", ".", "_token_to_idx", ")", "bert_vocab", ".", "_reserved_tokens", "=", "vocab_dict", ".", "get", "(", "'reserved_tokens'", ")", "bert_vocab", ".", "_padding_token", "=", "vocab_dict", ".", "get", "(", "'padding_token'", ")", "bert_vocab", ".", "_bos_token", "=", "vocab_dict", ".", "get", "(", "'bos_token'", ")", "bert_vocab", ".", "_eos_token", "=", "vocab_dict", ".", "get", "(", "'eos_token'", ")", "bert_vocab", ".", "_mask_token", "=", "vocab_dict", ".", "get", "(", "'mask_token'", ")", "bert_vocab", ".", "_sep_token", "=", "vocab_dict", ".", "get", "(", "'sep_token'", ")", "bert_vocab", ".", "_cls_token", "=", "vocab_dict", ".", "get", "(", "'cls_token'", ")", "return", "bert_vocab" ]
Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab
[ "Deserialize", "BERTVocab", "object", "from", "json", "string", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/bert.py#L174-L203
train
dmlc/gluon-nlp
src/gluonnlp/model/train/language_model.py
StandardRNN.forward
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. 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-1. the initial state with shape `(num_layers, 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-1. the state with shape `(num_layers, batch_size, num_hidden)` encoded_raw: list The list of last output of the model's encoder. the shape of last encoder's output `(sequence_length, batch_size, num_hidden)` encoded_dropped: list The list of last output with dropout of the model's encoder. the shape of last encoder's dropped output `(sequence_length, batch_size, num_hidden)` """ encoded = self.embedding(inputs) if not begin_state: begin_state = self.begin_state(batch_size=inputs.shape[1]) encoded_raw = [] encoded_dropped = [] encoded, state = self.encoder(encoded, begin_state) encoded_raw.append(encoded) if self._dropout: encoded = nd.Dropout(encoded, p=self._dropout, axes=(0,)) out = self.decoder(encoded) return out, state, encoded_raw, encoded_dropped
python
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. 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-1. the initial state with shape `(num_layers, 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-1. the state with shape `(num_layers, batch_size, num_hidden)` encoded_raw: list The list of last output of the model's encoder. the shape of last encoder's output `(sequence_length, batch_size, num_hidden)` encoded_dropped: list The list of last output with dropout of the model's encoder. the shape of last encoder's dropped output `(sequence_length, batch_size, num_hidden)` """ encoded = self.embedding(inputs) if not begin_state: begin_state = self.begin_state(batch_size=inputs.shape[1]) encoded_raw = [] encoded_dropped = [] encoded, state = self.encoder(encoded, begin_state) encoded_raw.append(encoded) if self._dropout: encoded = nd.Dropout(encoded, p=self._dropout, axes=(0,)) out = self.decoder(encoded) return out, state, encoded_raw, encoded_dropped
[ "def", "forward", "(", "self", ",", "inputs", ",", "begin_state", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "if", "not", "begin_state", ":", "begin_state", "=", "self", ".", "begin_state", "(", "batch_size", "=", "inputs", ".", "shape", "[", "1", "]", ")", "encoded_raw", "=", "[", "]", "encoded_dropped", "=", "[", "]", "encoded", ",", "state", "=", "self", ".", "encoder", "(", "encoded", ",", "begin_state", ")", "encoded_raw", ".", "append", "(", "encoded", ")", "if", "self", ".", "_dropout", ":", "encoded", "=", "nd", ".", "Dropout", "(", "encoded", ",", "p", "=", "self", ".", "_dropout", ",", "axes", "=", "(", "0", ",", ")", ")", "out", "=", "self", ".", "decoder", "(", "encoded", ")", "return", "out", ",", "state", ",", "encoded_raw", ",", "encoded_dropped" ]
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. 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-1. the initial state with shape `(num_layers, 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-1. the state with shape `(num_layers, batch_size, num_hidden)` encoded_raw: list The list of last output of the model's encoder. the shape of last encoder's output `(sequence_length, batch_size, num_hidden)` encoded_dropped: list The list of last output with dropout of the model's encoder. the shape of last encoder's dropped output `(sequence_length, batch_size, num_hidden)`
[ "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/train/language_model.py#L238-L276
train
dmlc/gluon-nlp
src/gluonnlp/model/train/language_model.py
BigRNN.forward
def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ """Defines the 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)` sampled_values : list a list of three tensors for `sampled_classes` with shape `(num_samples,)`, `expected_count_sampled` with shape `(num_samples,)`, and `expected_count_true` with shape `(sequence_length, batch_size)`. Returns -------- out : NDArray output tensor with shape `(sequence_length, batch_size, 1+num_samples)` 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)` new_target : NDArray output tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". """ encoded = self.embedding(inputs) length = inputs.shape[0] batch_size = inputs.shape[1] encoded, out_states = self.encoder.unroll(length, encoded, begin_state, layout='TNC', merge_outputs=True) out, new_target = self.decoder(encoded, sampled_values, label) out = out.reshape((length, batch_size, -1)) new_target = new_target.reshape((length, batch_size)) return out, out_states, new_target
python
def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ """Defines the 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)` sampled_values : list a list of three tensors for `sampled_classes` with shape `(num_samples,)`, `expected_count_sampled` with shape `(num_samples,)`, and `expected_count_true` with shape `(sequence_length, batch_size)`. Returns -------- out : NDArray output tensor with shape `(sequence_length, batch_size, 1+num_samples)` 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)` new_target : NDArray output tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". """ encoded = self.embedding(inputs) length = inputs.shape[0] batch_size = inputs.shape[1] encoded, out_states = self.encoder.unroll(length, encoded, begin_state, layout='TNC', merge_outputs=True) out, new_target = self.decoder(encoded, sampled_values, label) out = out.reshape((length, batch_size, -1)) new_target = new_target.reshape((length, batch_size)) return out, out_states, new_target
[ "def", "forward", "(", "self", ",", "inputs", ",", "label", ",", "begin_state", ",", "sampled_values", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "length", "=", "inputs", ".", "shape", "[", "0", "]", "batch_size", "=", "inputs", ".", "shape", "[", "1", "]", "encoded", ",", "out_states", "=", "self", ".", "encoder", ".", "unroll", "(", "length", ",", "encoded", ",", "begin_state", ",", "layout", "=", "'TNC'", ",", "merge_outputs", "=", "True", ")", "out", ",", "new_target", "=", "self", ".", "decoder", "(", "encoded", ",", "sampled_values", ",", "label", ")", "out", "=", "out", ".", "reshape", "(", "(", "length", ",", "batch_size", ",", "-", "1", ")", ")", "new_target", "=", "new_target", ".", "reshape", "(", "(", "length", ",", "batch_size", ")", ")", "return", "out", ",", "out_states", ",", "new_target" ]
Defines the 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)` sampled_values : list a list of three tensors for `sampled_classes` with shape `(num_samples,)`, `expected_count_sampled` with shape `(num_samples,)`, and `expected_count_true` with shape `(sequence_length, batch_size)`. Returns -------- out : NDArray output tensor with shape `(sequence_length, batch_size, 1+num_samples)` 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)` new_target : NDArray output tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC".
[ "Defines", "the", "forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/language_model.py#L389-L427
train
dmlc/gluon-nlp
scripts/word_embeddings/model.py
SG.hybrid_forward
def hybrid_forward(self, F, center, context, center_words): """SkipGram forward pass. Parameters ---------- center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array of word / subword indices of shape (batch_size, len(token_to_idx) + num_subwords). Embedding for center words are computed via F.sparse.dot between the CSR center array and the weight matrix. context : mxnet.nd.NDArray or mxnet.sym.Symbol Dense array of context words of shape (batch_size, ). Also used for row-wise independently masking negatives equal to one of context. center_words : mxnet.nd.NDArray or mxnet.sym.Symbol Dense array of center words of shape (batch_size, ). Only used for row-wise independently masking negatives equal to one of center_words. """ # negatives sampling negatives = [] mask = [] for _ in range(self._kwargs['num_negatives']): negatives.append(self.negatives_sampler(center_words)) mask_ = negatives[-1] != center_words mask_ = F.stack(mask_, (negatives[-1] != context)) mask.append(mask_.min(axis=0)) negatives = F.stack(*negatives, axis=1) mask = F.stack(*mask, axis=1).astype(np.float32) # center - context pairs emb_center = self.embedding(center).expand_dims(1) emb_context = self.embedding_out(context).expand_dims(2) pred_pos = F.batch_dot(emb_center, emb_context).squeeze() loss_pos = (F.relu(pred_pos) - pred_pos + F.Activation( -F.abs(pred_pos), act_type='softrelu')) / (mask.sum(axis=1) + 1) # center - negatives pairs emb_negatives = self.embedding_out(negatives).reshape( (-1, self._kwargs['num_negatives'], self._kwargs['output_dim'])).swapaxes(1, 2) pred_neg = F.batch_dot(emb_center, emb_negatives).squeeze() mask = mask.reshape((-1, self._kwargs['num_negatives'])) loss_neg = (F.relu(pred_neg) + F.Activation( -F.abs(pred_neg), act_type='softrelu')) * mask loss_neg = loss_neg.sum(axis=1) / (mask.sum(axis=1) + 1) return loss_pos + loss_neg
python
def hybrid_forward(self, F, center, context, center_words): """SkipGram forward pass. Parameters ---------- center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array of word / subword indices of shape (batch_size, len(token_to_idx) + num_subwords). Embedding for center words are computed via F.sparse.dot between the CSR center array and the weight matrix. context : mxnet.nd.NDArray or mxnet.sym.Symbol Dense array of context words of shape (batch_size, ). Also used for row-wise independently masking negatives equal to one of context. center_words : mxnet.nd.NDArray or mxnet.sym.Symbol Dense array of center words of shape (batch_size, ). Only used for row-wise independently masking negatives equal to one of center_words. """ # negatives sampling negatives = [] mask = [] for _ in range(self._kwargs['num_negatives']): negatives.append(self.negatives_sampler(center_words)) mask_ = negatives[-1] != center_words mask_ = F.stack(mask_, (negatives[-1] != context)) mask.append(mask_.min(axis=0)) negatives = F.stack(*negatives, axis=1) mask = F.stack(*mask, axis=1).astype(np.float32) # center - context pairs emb_center = self.embedding(center).expand_dims(1) emb_context = self.embedding_out(context).expand_dims(2) pred_pos = F.batch_dot(emb_center, emb_context).squeeze() loss_pos = (F.relu(pred_pos) - pred_pos + F.Activation( -F.abs(pred_pos), act_type='softrelu')) / (mask.sum(axis=1) + 1) # center - negatives pairs emb_negatives = self.embedding_out(negatives).reshape( (-1, self._kwargs['num_negatives'], self._kwargs['output_dim'])).swapaxes(1, 2) pred_neg = F.batch_dot(emb_center, emb_negatives).squeeze() mask = mask.reshape((-1, self._kwargs['num_negatives'])) loss_neg = (F.relu(pred_neg) + F.Activation( -F.abs(pred_neg), act_type='softrelu')) * mask loss_neg = loss_neg.sum(axis=1) / (mask.sum(axis=1) + 1) return loss_pos + loss_neg
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "center", ",", "context", ",", "center_words", ")", ":", "# negatives sampling", "negatives", "=", "[", "]", "mask", "=", "[", "]", "for", "_", "in", "range", "(", "self", ".", "_kwargs", "[", "'num_negatives'", "]", ")", ":", "negatives", ".", "append", "(", "self", ".", "negatives_sampler", "(", "center_words", ")", ")", "mask_", "=", "negatives", "[", "-", "1", "]", "!=", "center_words", "mask_", "=", "F", ".", "stack", "(", "mask_", ",", "(", "negatives", "[", "-", "1", "]", "!=", "context", ")", ")", "mask", ".", "append", "(", "mask_", ".", "min", "(", "axis", "=", "0", ")", ")", "negatives", "=", "F", ".", "stack", "(", "*", "negatives", ",", "axis", "=", "1", ")", "mask", "=", "F", ".", "stack", "(", "*", "mask", ",", "axis", "=", "1", ")", ".", "astype", "(", "np", ".", "float32", ")", "# center - context pairs", "emb_center", "=", "self", ".", "embedding", "(", "center", ")", ".", "expand_dims", "(", "1", ")", "emb_context", "=", "self", ".", "embedding_out", "(", "context", ")", ".", "expand_dims", "(", "2", ")", "pred_pos", "=", "F", ".", "batch_dot", "(", "emb_center", ",", "emb_context", ")", ".", "squeeze", "(", ")", "loss_pos", "=", "(", "F", ".", "relu", "(", "pred_pos", ")", "-", "pred_pos", "+", "F", ".", "Activation", "(", "-", "F", ".", "abs", "(", "pred_pos", ")", ",", "act_type", "=", "'softrelu'", ")", ")", "/", "(", "mask", ".", "sum", "(", "axis", "=", "1", ")", "+", "1", ")", "# center - negatives pairs", "emb_negatives", "=", "self", ".", "embedding_out", "(", "negatives", ")", ".", "reshape", "(", "(", "-", "1", ",", "self", ".", "_kwargs", "[", "'num_negatives'", "]", ",", "self", ".", "_kwargs", "[", "'output_dim'", "]", ")", ")", ".", "swapaxes", "(", "1", ",", "2", ")", "pred_neg", "=", "F", ".", "batch_dot", "(", "emb_center", ",", "emb_negatives", ")", ".", "squeeze", "(", ")", "mask", "=", "mask", ".", "reshape", "(", "(", "-", "1", ",", "self", ".", "_kwargs", "[", "'num_negatives'", "]", ")", ")", "loss_neg", "=", "(", "F", ".", "relu", "(", "pred_neg", ")", "+", "F", ".", "Activation", "(", "-", "F", ".", "abs", "(", "pred_neg", ")", ",", "act_type", "=", "'softrelu'", ")", ")", "*", "mask", "loss_neg", "=", "loss_neg", ".", "sum", "(", "axis", "=", "1", ")", "/", "(", "mask", ".", "sum", "(", "axis", "=", "1", ")", "+", "1", ")", "return", "loss_pos", "+", "loss_neg" ]
SkipGram forward pass. Parameters ---------- center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array of word / subword indices of shape (batch_size, len(token_to_idx) + num_subwords). Embedding for center words are computed via F.sparse.dot between the CSR center array and the weight matrix. context : mxnet.nd.NDArray or mxnet.sym.Symbol Dense array of context words of shape (batch_size, ). Also used for row-wise independently masking negatives equal to one of context. center_words : mxnet.nd.NDArray or mxnet.sym.Symbol Dense array of center words of shape (batch_size, ). Only used for row-wise independently masking negatives equal to one of center_words.
[ "SkipGram", "forward", "pass", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/model.py#L101-L149
train
dmlc/gluon-nlp
scripts/sentiment_analysis/finetune_lm.py
evaluate
def evaluate(dataloader): """Evaluate network on the specified dataset""" total_L = 0.0 total_sample_num = 0 total_correct_num = 0 start_log_interval_time = time.time() print('Begin Testing...') for i, ((data, valid_length), label) in enumerate(dataloader): data = mx.nd.transpose(data.as_in_context(context)) valid_length = valid_length.as_in_context(context).astype(np.float32) label = label.as_in_context(context) output = net(data, valid_length) L = loss(output, label) pred = (output > 0.5).reshape((-1,)) total_L += L.sum().asscalar() total_sample_num += label.shape[0] total_correct_num += (pred == label).sum().asscalar() if (i + 1) % args.log_interval == 0: print('[Batch {}/{}] elapsed {:.2f} s'.format( i + 1, len(dataloader), time.time() - start_log_interval_time)) start_log_interval_time = time.time() avg_L = total_L / float(total_sample_num) acc = total_correct_num / float(total_sample_num) return avg_L, acc
python
def evaluate(dataloader): """Evaluate network on the specified dataset""" total_L = 0.0 total_sample_num = 0 total_correct_num = 0 start_log_interval_time = time.time() print('Begin Testing...') for i, ((data, valid_length), label) in enumerate(dataloader): data = mx.nd.transpose(data.as_in_context(context)) valid_length = valid_length.as_in_context(context).astype(np.float32) label = label.as_in_context(context) output = net(data, valid_length) L = loss(output, label) pred = (output > 0.5).reshape((-1,)) total_L += L.sum().asscalar() total_sample_num += label.shape[0] total_correct_num += (pred == label).sum().asscalar() if (i + 1) % args.log_interval == 0: print('[Batch {}/{}] elapsed {:.2f} s'.format( i + 1, len(dataloader), time.time() - start_log_interval_time)) start_log_interval_time = time.time() avg_L = total_L / float(total_sample_num) acc = total_correct_num / float(total_sample_num) return avg_L, acc
[ "def", "evaluate", "(", "dataloader", ")", ":", "total_L", "=", "0.0", "total_sample_num", "=", "0", "total_correct_num", "=", "0", "start_log_interval_time", "=", "time", ".", "time", "(", ")", "print", "(", "'Begin Testing...'", ")", "for", "i", ",", "(", "(", "data", ",", "valid_length", ")", ",", "label", ")", "in", "enumerate", "(", "dataloader", ")", ":", "data", "=", "mx", ".", "nd", ".", "transpose", "(", "data", ".", "as_in_context", "(", "context", ")", ")", "valid_length", "=", "valid_length", ".", "as_in_context", "(", "context", ")", ".", "astype", "(", "np", ".", "float32", ")", "label", "=", "label", ".", "as_in_context", "(", "context", ")", "output", "=", "net", "(", "data", ",", "valid_length", ")", "L", "=", "loss", "(", "output", ",", "label", ")", "pred", "=", "(", "output", ">", "0.5", ")", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "total_L", "+=", "L", ".", "sum", "(", ")", ".", "asscalar", "(", ")", "total_sample_num", "+=", "label", ".", "shape", "[", "0", "]", "total_correct_num", "+=", "(", "pred", "==", "label", ")", ".", "sum", "(", ")", ".", "asscalar", "(", ")", "if", "(", "i", "+", "1", ")", "%", "args", ".", "log_interval", "==", "0", ":", "print", "(", "'[Batch {}/{}] elapsed {:.2f} s'", ".", "format", "(", "i", "+", "1", ",", "len", "(", "dataloader", ")", ",", "time", ".", "time", "(", ")", "-", "start_log_interval_time", ")", ")", "start_log_interval_time", "=", "time", ".", "time", "(", ")", "avg_L", "=", "total_L", "/", "float", "(", "total_sample_num", ")", "acc", "=", "total_correct_num", "/", "float", "(", "total_sample_num", ")", "return", "avg_L", ",", "acc" ]
Evaluate network on the specified dataset
[ "Evaluate", "network", "on", "the", "specified", "dataset" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L237-L260
train
dmlc/gluon-nlp
scripts/sentiment_analysis/finetune_lm.py
train
def train(): """Training process""" start_pipeline_time = time.time() # Training/Testing best_valid_acc = 0 stop_early = 0 for epoch in range(args.epochs): # Epoch training stats start_epoch_time = time.time() epoch_L = 0.0 epoch_sent_num = 0 epoch_wc = 0 # Log interval training stats start_log_interval_time = time.time() log_interval_wc = 0 log_interval_sent_num = 0 log_interval_L = 0.0 for i, ((data, valid_length), label) in enumerate(train_dataloader): data = mx.nd.transpose(data.as_in_context(context)) label = label.as_in_context(context) valid_length = valid_length.as_in_context(context).astype(np.float32) wc = valid_length.sum().asscalar() log_interval_wc += wc epoch_wc += wc log_interval_sent_num += data.shape[1] epoch_sent_num += data.shape[1] with autograd.record(): output = net(data, valid_length) L = loss(output, label).mean() L.backward() # Clip gradient if args.clip is not None: grads = [p.grad(context) for p in net.collect_params().values()] gluon.utils.clip_global_norm(grads, args.clip) # Update parameter trainer.step(1) log_interval_L += L.asscalar() epoch_L += L.asscalar() if (i + 1) % args.log_interval == 0: print('[Epoch %d Batch %d/%d] avg loss %g, throughput %gK wps' % ( epoch, i + 1, len(train_dataloader), log_interval_L / log_interval_sent_num, log_interval_wc / 1000 / (time.time() - start_log_interval_time))) # Clear log interval training stats start_log_interval_time = time.time() log_interval_wc = 0 log_interval_sent_num = 0 log_interval_L = 0 end_epoch_time = time.time() valid_avg_L, valid_acc = evaluate(valid_dataloader) test_avg_L, test_acc = evaluate(test_dataloader) print('[Epoch %d] train avg loss %g, ' 'valid acc %.4f, valid avg loss %g, ' 'test acc %.4f, test avg loss %g, throughput %gK wps' % ( epoch, epoch_L / epoch_sent_num, valid_acc, valid_avg_L, test_acc, test_avg_L, epoch_wc / 1000 / (end_epoch_time - start_epoch_time))) if valid_acc < best_valid_acc: print('No Improvement.') stop_early += 1 if stop_early == 3: break else: # Reset stop_early if the validation loss finds a new low value print('Observed Improvement.') stop_early = 0 net.save_parameters(args.save_prefix + '_{:04d}.params'.format(epoch)) best_valid_acc = valid_acc net.load_parameters(glob.glob(args.save_prefix+'_*.params')[-1], context) valid_avg_L, valid_acc = evaluate(valid_dataloader) test_avg_L, test_acc = evaluate(test_dataloader) print('Best validation loss %g, validation acc %.4f'%(valid_avg_L, valid_acc)) print('Best test loss %g, test acc %.4f'%(test_avg_L, test_acc)) print('Total time cost %.2fs'%(time.time()-start_pipeline_time))
python
def train(): """Training process""" start_pipeline_time = time.time() # Training/Testing best_valid_acc = 0 stop_early = 0 for epoch in range(args.epochs): # Epoch training stats start_epoch_time = time.time() epoch_L = 0.0 epoch_sent_num = 0 epoch_wc = 0 # Log interval training stats start_log_interval_time = time.time() log_interval_wc = 0 log_interval_sent_num = 0 log_interval_L = 0.0 for i, ((data, valid_length), label) in enumerate(train_dataloader): data = mx.nd.transpose(data.as_in_context(context)) label = label.as_in_context(context) valid_length = valid_length.as_in_context(context).astype(np.float32) wc = valid_length.sum().asscalar() log_interval_wc += wc epoch_wc += wc log_interval_sent_num += data.shape[1] epoch_sent_num += data.shape[1] with autograd.record(): output = net(data, valid_length) L = loss(output, label).mean() L.backward() # Clip gradient if args.clip is not None: grads = [p.grad(context) for p in net.collect_params().values()] gluon.utils.clip_global_norm(grads, args.clip) # Update parameter trainer.step(1) log_interval_L += L.asscalar() epoch_L += L.asscalar() if (i + 1) % args.log_interval == 0: print('[Epoch %d Batch %d/%d] avg loss %g, throughput %gK wps' % ( epoch, i + 1, len(train_dataloader), log_interval_L / log_interval_sent_num, log_interval_wc / 1000 / (time.time() - start_log_interval_time))) # Clear log interval training stats start_log_interval_time = time.time() log_interval_wc = 0 log_interval_sent_num = 0 log_interval_L = 0 end_epoch_time = time.time() valid_avg_L, valid_acc = evaluate(valid_dataloader) test_avg_L, test_acc = evaluate(test_dataloader) print('[Epoch %d] train avg loss %g, ' 'valid acc %.4f, valid avg loss %g, ' 'test acc %.4f, test avg loss %g, throughput %gK wps' % ( epoch, epoch_L / epoch_sent_num, valid_acc, valid_avg_L, test_acc, test_avg_L, epoch_wc / 1000 / (end_epoch_time - start_epoch_time))) if valid_acc < best_valid_acc: print('No Improvement.') stop_early += 1 if stop_early == 3: break else: # Reset stop_early if the validation loss finds a new low value print('Observed Improvement.') stop_early = 0 net.save_parameters(args.save_prefix + '_{:04d}.params'.format(epoch)) best_valid_acc = valid_acc net.load_parameters(glob.glob(args.save_prefix+'_*.params')[-1], context) valid_avg_L, valid_acc = evaluate(valid_dataloader) test_avg_L, test_acc = evaluate(test_dataloader) print('Best validation loss %g, validation acc %.4f'%(valid_avg_L, valid_acc)) print('Best test loss %g, test acc %.4f'%(test_avg_L, test_acc)) print('Total time cost %.2fs'%(time.time()-start_pipeline_time))
[ "def", "train", "(", ")", ":", "start_pipeline_time", "=", "time", ".", "time", "(", ")", "# Training/Testing", "best_valid_acc", "=", "0", "stop_early", "=", "0", "for", "epoch", "in", "range", "(", "args", ".", "epochs", ")", ":", "# Epoch training stats", "start_epoch_time", "=", "time", ".", "time", "(", ")", "epoch_L", "=", "0.0", "epoch_sent_num", "=", "0", "epoch_wc", "=", "0", "# Log interval training stats", "start_log_interval_time", "=", "time", ".", "time", "(", ")", "log_interval_wc", "=", "0", "log_interval_sent_num", "=", "0", "log_interval_L", "=", "0.0", "for", "i", ",", "(", "(", "data", ",", "valid_length", ")", ",", "label", ")", "in", "enumerate", "(", "train_dataloader", ")", ":", "data", "=", "mx", ".", "nd", ".", "transpose", "(", "data", ".", "as_in_context", "(", "context", ")", ")", "label", "=", "label", ".", "as_in_context", "(", "context", ")", "valid_length", "=", "valid_length", ".", "as_in_context", "(", "context", ")", ".", "astype", "(", "np", ".", "float32", ")", "wc", "=", "valid_length", ".", "sum", "(", ")", ".", "asscalar", "(", ")", "log_interval_wc", "+=", "wc", "epoch_wc", "+=", "wc", "log_interval_sent_num", "+=", "data", ".", "shape", "[", "1", "]", "epoch_sent_num", "+=", "data", ".", "shape", "[", "1", "]", "with", "autograd", ".", "record", "(", ")", ":", "output", "=", "net", "(", "data", ",", "valid_length", ")", "L", "=", "loss", "(", "output", ",", "label", ")", ".", "mean", "(", ")", "L", ".", "backward", "(", ")", "# Clip gradient", "if", "args", ".", "clip", "is", "not", "None", ":", "grads", "=", "[", "p", ".", "grad", "(", "context", ")", "for", "p", "in", "net", ".", "collect_params", "(", ")", ".", "values", "(", ")", "]", "gluon", ".", "utils", ".", "clip_global_norm", "(", "grads", ",", "args", ".", "clip", ")", "# Update parameter", "trainer", ".", "step", "(", "1", ")", "log_interval_L", "+=", "L", ".", "asscalar", "(", ")", "epoch_L", "+=", "L", ".", "asscalar", "(", ")", "if", "(", "i", "+", "1", ")", "%", "args", ".", "log_interval", "==", "0", ":", "print", "(", "'[Epoch %d Batch %d/%d] avg loss %g, throughput %gK wps'", "%", "(", "epoch", ",", "i", "+", "1", ",", "len", "(", "train_dataloader", ")", ",", "log_interval_L", "/", "log_interval_sent_num", ",", "log_interval_wc", "/", "1000", "/", "(", "time", ".", "time", "(", ")", "-", "start_log_interval_time", ")", ")", ")", "# Clear log interval training stats", "start_log_interval_time", "=", "time", ".", "time", "(", ")", "log_interval_wc", "=", "0", "log_interval_sent_num", "=", "0", "log_interval_L", "=", "0", "end_epoch_time", "=", "time", ".", "time", "(", ")", "valid_avg_L", ",", "valid_acc", "=", "evaluate", "(", "valid_dataloader", ")", "test_avg_L", ",", "test_acc", "=", "evaluate", "(", "test_dataloader", ")", "print", "(", "'[Epoch %d] train avg loss %g, '", "'valid acc %.4f, valid avg loss %g, '", "'test acc %.4f, test avg loss %g, throughput %gK wps'", "%", "(", "epoch", ",", "epoch_L", "/", "epoch_sent_num", ",", "valid_acc", ",", "valid_avg_L", ",", "test_acc", ",", "test_avg_L", ",", "epoch_wc", "/", "1000", "/", "(", "end_epoch_time", "-", "start_epoch_time", ")", ")", ")", "if", "valid_acc", "<", "best_valid_acc", ":", "print", "(", "'No Improvement.'", ")", "stop_early", "+=", "1", "if", "stop_early", "==", "3", ":", "break", "else", ":", "# Reset stop_early if the validation loss finds a new low value", "print", "(", "'Observed Improvement.'", ")", "stop_early", "=", "0", "net", ".", "save_parameters", "(", "args", ".", "save_prefix", "+", "'_{:04d}.params'", ".", "format", "(", "epoch", ")", ")", "best_valid_acc", "=", "valid_acc", "net", ".", "load_parameters", "(", "glob", ".", "glob", "(", "args", ".", "save_prefix", "+", "'_*.params'", ")", "[", "-", "1", "]", ",", "context", ")", "valid_avg_L", ",", "valid_acc", "=", "evaluate", "(", "valid_dataloader", ")", "test_avg_L", ",", "test_acc", "=", "evaluate", "(", "test_dataloader", ")", "print", "(", "'Best validation loss %g, validation acc %.4f'", "%", "(", "valid_avg_L", ",", "valid_acc", ")", ")", "print", "(", "'Best test loss %g, test acc %.4f'", "%", "(", "test_avg_L", ",", "test_acc", ")", ")", "print", "(", "'Total time cost %.2fs'", "%", "(", "time", ".", "time", "(", ")", "-", "start_pipeline_time", ")", ")" ]
Training process
[ "Training", "process" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L263-L340
train
dmlc/gluon-nlp
scripts/sentiment_analysis/finetune_lm.py
AggregationLayer.hybrid_forward
def hybrid_forward(self, F, data, valid_length): # pylint: disable=arguments-differ """Forward logic""" # Data will have shape (T, N, C) if self._use_mean_pool: masked_encoded = F.SequenceMask(data, sequence_length=valid_length, use_sequence_length=True) agg_state = F.broadcast_div(F.sum(masked_encoded, axis=0), F.expand_dims(valid_length, axis=1)) else: agg_state = F.SequenceLast(data, sequence_length=valid_length, use_sequence_length=True) return agg_state
python
def hybrid_forward(self, F, data, valid_length): # pylint: disable=arguments-differ """Forward logic""" # Data will have shape (T, N, C) if self._use_mean_pool: masked_encoded = F.SequenceMask(data, sequence_length=valid_length, use_sequence_length=True) agg_state = F.broadcast_div(F.sum(masked_encoded, axis=0), F.expand_dims(valid_length, axis=1)) else: agg_state = F.SequenceLast(data, sequence_length=valid_length, use_sequence_length=True) return agg_state
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "data", ",", "valid_length", ")", ":", "# pylint: disable=arguments-differ", "# Data will have shape (T, N, C)", "if", "self", ".", "_use_mean_pool", ":", "masked_encoded", "=", "F", ".", "SequenceMask", "(", "data", ",", "sequence_length", "=", "valid_length", ",", "use_sequence_length", "=", "True", ")", "agg_state", "=", "F", ".", "broadcast_div", "(", "F", ".", "sum", "(", "masked_encoded", ",", "axis", "=", "0", ")", ",", "F", ".", "expand_dims", "(", "valid_length", ",", "axis", "=", "1", ")", ")", "else", ":", "agg_state", "=", "F", ".", "SequenceLast", "(", "data", ",", "sequence_length", "=", "valid_length", ",", "use_sequence_length", "=", "True", ")", "return", "agg_state" ]
Forward logic
[ "Forward", "logic" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L105-L118
train
dmlc/gluon-nlp
src/gluonnlp/model/lstmpcellwithclip.py
LSTMPCellWithClip.hybrid_forward
def hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias): r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input tensor with shape `(batch_size, input_size)`. states : a list of two initial recurrent state tensors, with shape `(batch_size, projection_size)` and `(batch_size, hidden_size)` respectively. Returns -------- out : output tensor with shape `(batch_size, num_hidden)`. next_states : a list of two output recurrent state tensors. Each has the same shape as `states`. """ prefix = 't%d_'%self._counter i2h = F.FullyConnected(data=inputs, weight=i2h_weight, bias=i2h_bias, num_hidden=self._hidden_size*4, name=prefix+'i2h') h2h = F.FullyConnected(data=states[0], weight=h2h_weight, bias=h2h_bias, num_hidden=self._hidden_size*4, name=prefix+'h2h') gates = i2h + h2h slice_gates = F.SliceChannel(gates, num_outputs=4, name=prefix+'slice') in_gate = F.Activation(slice_gates[0], act_type='sigmoid', name=prefix+'i') forget_gate = F.Activation(slice_gates[1], act_type='sigmoid', name=prefix+'f') in_transform = F.Activation(slice_gates[2], act_type='tanh', name=prefix+'c') out_gate = F.Activation(slice_gates[3], act_type='sigmoid', name=prefix+'o') next_c = F._internal._plus(forget_gate * states[1], in_gate * in_transform, name=prefix+'state') if self._cell_clip is not None: next_c = next_c.clip(-self._cell_clip, self._cell_clip) hidden = F._internal._mul(out_gate, F.Activation(next_c, act_type='tanh'), name=prefix+'hidden') next_r = F.FullyConnected(data=hidden, num_hidden=self._projection_size, weight=h2r_weight, no_bias=True, name=prefix+'out') if self._projection_clip is not None: next_r = next_r.clip(-self._projection_clip, self._projection_clip) return next_r, [next_r, next_c]
python
def hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias): r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input tensor with shape `(batch_size, input_size)`. states : a list of two initial recurrent state tensors, with shape `(batch_size, projection_size)` and `(batch_size, hidden_size)` respectively. Returns -------- out : output tensor with shape `(batch_size, num_hidden)`. next_states : a list of two output recurrent state tensors. Each has the same shape as `states`. """ prefix = 't%d_'%self._counter i2h = F.FullyConnected(data=inputs, weight=i2h_weight, bias=i2h_bias, num_hidden=self._hidden_size*4, name=prefix+'i2h') h2h = F.FullyConnected(data=states[0], weight=h2h_weight, bias=h2h_bias, num_hidden=self._hidden_size*4, name=prefix+'h2h') gates = i2h + h2h slice_gates = F.SliceChannel(gates, num_outputs=4, name=prefix+'slice') in_gate = F.Activation(slice_gates[0], act_type='sigmoid', name=prefix+'i') forget_gate = F.Activation(slice_gates[1], act_type='sigmoid', name=prefix+'f') in_transform = F.Activation(slice_gates[2], act_type='tanh', name=prefix+'c') out_gate = F.Activation(slice_gates[3], act_type='sigmoid', name=prefix+'o') next_c = F._internal._plus(forget_gate * states[1], in_gate * in_transform, name=prefix+'state') if self._cell_clip is not None: next_c = next_c.clip(-self._cell_clip, self._cell_clip) hidden = F._internal._mul(out_gate, F.Activation(next_c, act_type='tanh'), name=prefix+'hidden') next_r = F.FullyConnected(data=hidden, num_hidden=self._projection_size, weight=h2r_weight, no_bias=True, name=prefix+'out') if self._projection_clip is not None: next_r = next_r.clip(-self._projection_clip, self._projection_clip) return next_r, [next_r, next_c]
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", ",", "i2h_weight", ",", "h2h_weight", ",", "h2r_weight", ",", "i2h_bias", ",", "h2h_bias", ")", ":", "prefix", "=", "'t%d_'", "%", "self", ".", "_counter", "i2h", "=", "F", ".", "FullyConnected", "(", "data", "=", "inputs", ",", "weight", "=", "i2h_weight", ",", "bias", "=", "i2h_bias", ",", "num_hidden", "=", "self", ".", "_hidden_size", "*", "4", ",", "name", "=", "prefix", "+", "'i2h'", ")", "h2h", "=", "F", ".", "FullyConnected", "(", "data", "=", "states", "[", "0", "]", ",", "weight", "=", "h2h_weight", ",", "bias", "=", "h2h_bias", ",", "num_hidden", "=", "self", ".", "_hidden_size", "*", "4", ",", "name", "=", "prefix", "+", "'h2h'", ")", "gates", "=", "i2h", "+", "h2h", "slice_gates", "=", "F", ".", "SliceChannel", "(", "gates", ",", "num_outputs", "=", "4", ",", "name", "=", "prefix", "+", "'slice'", ")", "in_gate", "=", "F", ".", "Activation", "(", "slice_gates", "[", "0", "]", ",", "act_type", "=", "'sigmoid'", ",", "name", "=", "prefix", "+", "'i'", ")", "forget_gate", "=", "F", ".", "Activation", "(", "slice_gates", "[", "1", "]", ",", "act_type", "=", "'sigmoid'", ",", "name", "=", "prefix", "+", "'f'", ")", "in_transform", "=", "F", ".", "Activation", "(", "slice_gates", "[", "2", "]", ",", "act_type", "=", "'tanh'", ",", "name", "=", "prefix", "+", "'c'", ")", "out_gate", "=", "F", ".", "Activation", "(", "slice_gates", "[", "3", "]", ",", "act_type", "=", "'sigmoid'", ",", "name", "=", "prefix", "+", "'o'", ")", "next_c", "=", "F", ".", "_internal", ".", "_plus", "(", "forget_gate", "*", "states", "[", "1", "]", ",", "in_gate", "*", "in_transform", ",", "name", "=", "prefix", "+", "'state'", ")", "if", "self", ".", "_cell_clip", "is", "not", "None", ":", "next_c", "=", "next_c", ".", "clip", "(", "-", "self", ".", "_cell_clip", ",", "self", ".", "_cell_clip", ")", "hidden", "=", "F", ".", "_internal", ".", "_mul", "(", "out_gate", ",", "F", ".", "Activation", "(", "next_c", ",", "act_type", "=", "'tanh'", ")", ",", "name", "=", "prefix", "+", "'hidden'", ")", "next_r", "=", "F", ".", "FullyConnected", "(", "data", "=", "hidden", ",", "num_hidden", "=", "self", ".", "_projection_size", ",", "weight", "=", "h2r_weight", ",", "no_bias", "=", "True", ",", "name", "=", "prefix", "+", "'out'", ")", "if", "self", ".", "_projection_clip", "is", "not", "None", ":", "next_r", "=", "next_r", ".", "clip", "(", "-", "self", ".", "_projection_clip", ",", "self", ".", "_projection_clip", ")", "return", "next_r", ",", "[", "next_r", ",", "next_c", "]" ]
r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input tensor with shape `(batch_size, input_size)`. states : a list of two initial recurrent state tensors, with shape `(batch_size, projection_size)` and `(batch_size, hidden_size)` respectively. Returns -------- out : output tensor with shape `(batch_size, num_hidden)`. next_states : a list of two output recurrent state tensors. Each has the same shape as `states`.
[ "r", "Hybrid", "forward", "computation", "for", "Long", "-", "Short", "Term", "Memory", "Projected", "network", "cell", "with", "cell", "clip", "and", "projection", "clip", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/lstmpcellwithclip.py#L100-L139
train
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
clip_grad_global_norm
def clip_grad_global_norm(parameters, max_norm, check_isfinite=True): """Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients are summed first before calculating the 2-norm. .. note:: This function is only for use when `update_on_kvstore` is set to False in trainer. Example:: trainer = Trainer(net.collect_params(), update_on_kvstore=False, ...) for x, y in mx.gluon.utils.split_and_load(X, [mx.gpu(0), mx.gpu(1)]): with mx.autograd.record(): y = net(x) loss = loss_fn(y, label) loss.backward() trainer.allreduce_grads() nlp.utils.clip_grad_global_norm(net.collect_params().values(), max_norm) trainer.update(batch_size) ... Parameters ---------- parameters : list of Parameters max_norm : float check_isfinite : bool, default True If True, check that the total_norm is finite (not nan or inf). This requires a blocking .asscalar() call. Returns ------- NDArray or float Total norm. Return type is NDArray of shape (1,) if check_isfinite is False. Otherwise a float is returned. """ def _norm(array): if array.stype == 'default': x = array.reshape((-1)) return nd.dot(x, x) return array.norm().square() arrays = [] i = 0 for p in parameters: if p.grad_req != 'null': grad_list = p.list_grad() arrays.append(grad_list[i % len(grad_list)]) i += 1 assert len(arrays) > 0, 'No parameter found available for gradient norm clipping.' ctx, dtype = arrays[0].context, arrays[0].dtype total_norm = nd.add_n(*[_norm(arr).as_in_context(ctx) for arr in arrays]) total_norm = nd.sqrt(total_norm) if check_isfinite: total_norm = total_norm.asscalar() if not np.isfinite(total_norm): warnings.warn( UserWarning('nan or inf is detected. ' 'Clipping results will be undefined.'), stacklevel=2) scale = max_norm / (total_norm + 1e-8) if check_isfinite: scale = nd.array([scale], dtype=dtype, ctx=ctx) scale = nd.min(nd.concat(scale, nd.ones((1,), dtype=dtype, ctx=ctx), dim=0)) for p in parameters: if p.grad_req != 'null': for arr in p.list_grad(): arr *= scale.as_in_context(arr.context) return total_norm
python
def clip_grad_global_norm(parameters, max_norm, check_isfinite=True): """Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients are summed first before calculating the 2-norm. .. note:: This function is only for use when `update_on_kvstore` is set to False in trainer. Example:: trainer = Trainer(net.collect_params(), update_on_kvstore=False, ...) for x, y in mx.gluon.utils.split_and_load(X, [mx.gpu(0), mx.gpu(1)]): with mx.autograd.record(): y = net(x) loss = loss_fn(y, label) loss.backward() trainer.allreduce_grads() nlp.utils.clip_grad_global_norm(net.collect_params().values(), max_norm) trainer.update(batch_size) ... Parameters ---------- parameters : list of Parameters max_norm : float check_isfinite : bool, default True If True, check that the total_norm is finite (not nan or inf). This requires a blocking .asscalar() call. Returns ------- NDArray or float Total norm. Return type is NDArray of shape (1,) if check_isfinite is False. Otherwise a float is returned. """ def _norm(array): if array.stype == 'default': x = array.reshape((-1)) return nd.dot(x, x) return array.norm().square() arrays = [] i = 0 for p in parameters: if p.grad_req != 'null': grad_list = p.list_grad() arrays.append(grad_list[i % len(grad_list)]) i += 1 assert len(arrays) > 0, 'No parameter found available for gradient norm clipping.' ctx, dtype = arrays[0].context, arrays[0].dtype total_norm = nd.add_n(*[_norm(arr).as_in_context(ctx) for arr in arrays]) total_norm = nd.sqrt(total_norm) if check_isfinite: total_norm = total_norm.asscalar() if not np.isfinite(total_norm): warnings.warn( UserWarning('nan or inf is detected. ' 'Clipping results will be undefined.'), stacklevel=2) scale = max_norm / (total_norm + 1e-8) if check_isfinite: scale = nd.array([scale], dtype=dtype, ctx=ctx) scale = nd.min(nd.concat(scale, nd.ones((1,), dtype=dtype, ctx=ctx), dim=0)) for p in parameters: if p.grad_req != 'null': for arr in p.list_grad(): arr *= scale.as_in_context(arr.context) return total_norm
[ "def", "clip_grad_global_norm", "(", "parameters", ",", "max_norm", ",", "check_isfinite", "=", "True", ")", ":", "def", "_norm", "(", "array", ")", ":", "if", "array", ".", "stype", "==", "'default'", ":", "x", "=", "array", ".", "reshape", "(", "(", "-", "1", ")", ")", "return", "nd", ".", "dot", "(", "x", ",", "x", ")", "return", "array", ".", "norm", "(", ")", ".", "square", "(", ")", "arrays", "=", "[", "]", "i", "=", "0", "for", "p", "in", "parameters", ":", "if", "p", ".", "grad_req", "!=", "'null'", ":", "grad_list", "=", "p", ".", "list_grad", "(", ")", "arrays", ".", "append", "(", "grad_list", "[", "i", "%", "len", "(", "grad_list", ")", "]", ")", "i", "+=", "1", "assert", "len", "(", "arrays", ")", ">", "0", ",", "'No parameter found available for gradient norm clipping.'", "ctx", ",", "dtype", "=", "arrays", "[", "0", "]", ".", "context", ",", "arrays", "[", "0", "]", ".", "dtype", "total_norm", "=", "nd", ".", "add_n", "(", "*", "[", "_norm", "(", "arr", ")", ".", "as_in_context", "(", "ctx", ")", "for", "arr", "in", "arrays", "]", ")", "total_norm", "=", "nd", ".", "sqrt", "(", "total_norm", ")", "if", "check_isfinite", ":", "total_norm", "=", "total_norm", ".", "asscalar", "(", ")", "if", "not", "np", ".", "isfinite", "(", "total_norm", ")", ":", "warnings", ".", "warn", "(", "UserWarning", "(", "'nan or inf is detected. '", "'Clipping results will be undefined.'", ")", ",", "stacklevel", "=", "2", ")", "scale", "=", "max_norm", "/", "(", "total_norm", "+", "1e-8", ")", "if", "check_isfinite", ":", "scale", "=", "nd", ".", "array", "(", "[", "scale", "]", ",", "dtype", "=", "dtype", ",", "ctx", "=", "ctx", ")", "scale", "=", "nd", ".", "min", "(", "nd", ".", "concat", "(", "scale", ",", "nd", ".", "ones", "(", "(", "1", ",", ")", ",", "dtype", "=", "dtype", ",", "ctx", "=", "ctx", ")", ",", "dim", "=", "0", ")", ")", "for", "p", "in", "parameters", ":", "if", "p", ".", "grad_req", "!=", "'null'", ":", "for", "arr", "in", "p", ".", "list_grad", "(", ")", ":", "arr", "*=", "scale", ".", "as_in_context", "(", "arr", ".", "context", ")", "return", "total_norm" ]
Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients are summed first before calculating the 2-norm. .. note:: This function is only for use when `update_on_kvstore` is set to False in trainer. Example:: trainer = Trainer(net.collect_params(), update_on_kvstore=False, ...) for x, y in mx.gluon.utils.split_and_load(X, [mx.gpu(0), mx.gpu(1)]): with mx.autograd.record(): y = net(x) loss = loss_fn(y, label) loss.backward() trainer.allreduce_grads() nlp.utils.clip_grad_global_norm(net.collect_params().values(), max_norm) trainer.update(batch_size) ... Parameters ---------- parameters : list of Parameters max_norm : float check_isfinite : bool, default True If True, check that the total_norm is finite (not nan or inf). This requires a blocking .asscalar() call. Returns ------- NDArray or float Total norm. Return type is NDArray of shape (1,) if check_isfinite is False. Otherwise a float is returned.
[ "Rescales", "gradients", "of", "parameters", "so", "that", "the", "sum", "of", "their", "2", "-", "norm", "is", "smaller", "than", "max_norm", ".", "If", "gradients", "exist", "for", "more", "than", "one", "context", "for", "a", "parameter", "user", "needs", "to", "explicitly", "call", "trainer", ".", "allreduce_grads", "so", "that", "the", "gradients", "are", "summed", "first", "before", "calculating", "the", "2", "-", "norm", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/utils/parameter.py#L28-L97
train
dmlc/gluon-nlp
scripts/bert/run_pretraining.py
train
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx, store): """Training function.""" mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() lr = args.lr optim_params = {'learning_rate': lr, 'epsilon': 1e-6, 'wd': 0.01} if args.dtype == 'float16': optim_params['multi_precision'] = True trainer = mx.gluon.Trainer(model.collect_params(), 'bertadam', optim_params, update_on_kvstore=False, kvstore=store) dynamic_loss_scale = args.dtype == 'float16' fp16_trainer = FP16Trainer(trainer, dynamic_loss_scale=dynamic_loss_scale) if args.ckpt_dir and args.start_step: state_path = os.path.join(args.ckpt_dir, '%07d.states' % args.start_step) logging.info('Loading trainer state from %s', state_path) trainer.load_states(state_path) accumulate = args.accumulate num_train_steps = args.num_steps warmup_ratio = args.warmup_ratio num_warmup_steps = int(num_train_steps * warmup_ratio) params = [p for p in model.collect_params().values() if p.grad_req != 'null'] param_dict = model.collect_params() # Do not apply weight decay on LayerNorm and bias terms for _, v in model.collect_params('.*beta|.*gamma|.*bias').items(): v.wd_mult = 0.0 if accumulate > 1: for p in params: p.grad_req = 'add' train_begin_time = time.time() begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 batch_num = 0 step_num = args.start_step parallel_model = ParallelBERT(model, mlm_loss, nsp_loss, vocab_size, store.num_workers * accumulate, trainer=fp16_trainer) num_ctxes = len(ctx) parallel = nlp.utils.Parallel(num_ctxes if num_ctxes > 1 else 0, parallel_model) while step_num < num_train_steps: for _, dataloader in enumerate(data_train): if step_num >= num_train_steps: break # create dummy data loader if needed if args.dummy_data_len: target_shape = (args.batch_size*num_ctxes, args.dummy_data_len) dataloader = get_dummy_dataloader(dataloader, target_shape) for _, data_batch in enumerate(dataloader): if step_num >= num_train_steps: break if batch_num % accumulate == 0: step_num += 1 # if accumulate > 1, grad_req is set to 'add', and zero_grad is required if accumulate > 1: param_dict.zero_grad() # update learning rate if step_num <= num_warmup_steps: new_lr = lr * step_num / num_warmup_steps else: offset = lr * step_num / num_train_steps new_lr = lr - offset trainer.set_learning_rate(new_lr) if args.profile: profile(step_num, 10, 12, profile_name=args.profile) if args.use_avg_len: data_list = [[seq.as_in_context(context) for seq in shard] for context, shard in zip(ctx, data_batch)] else: if data_batch[0].shape[0] < len(ctx): continue data_list = split_and_load(data_batch, ctx) ns_label_list, ns_pred_list = [], [] mask_label_list, mask_pred_list, mask_weight_list = [], [], [] # parallel forward / backward for data in data_list: parallel.put(data) for _ in range(len(ctx)): (_, next_sentence_label, classified, masked_id, decoded, masked_weight, ls1, ls2, valid_length) = parallel.get() 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()) / num_ctxes running_nsp_loss += ls2.as_in_context(mx.cpu()) / num_ctxes running_num_tks += valid_length.sum().as_in_context(mx.cpu()) # update if (batch_num + 1) % accumulate == 0: fp16_trainer.step(1, max_norm=1) 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) % (args.log_interval) == 0 and (batch_num + 1) % accumulate == 0: log(begin_time, running_num_tks, running_mlm_loss / accumulate, running_nsp_loss / accumulate, step_num, mlm_metric, nsp_metric, trainer, args.log_interval) begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 mlm_metric.reset_local() nsp_metric.reset_local() # saving checkpoints if args.ckpt_dir and (step_num + 1) % (args.ckpt_interval) == 0 \ and (batch_num + 1) % accumulate == 0: save_params(step_num, model, trainer, args.ckpt_dir) batch_num += 1 save_params(step_num, model, trainer, args.ckpt_dir) mx.nd.waitall() train_end_time = time.time() logging.info('Train cost={:.1f}s'.format(train_end_time - train_begin_time))
python
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx, store): """Training function.""" mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() lr = args.lr optim_params = {'learning_rate': lr, 'epsilon': 1e-6, 'wd': 0.01} if args.dtype == 'float16': optim_params['multi_precision'] = True trainer = mx.gluon.Trainer(model.collect_params(), 'bertadam', optim_params, update_on_kvstore=False, kvstore=store) dynamic_loss_scale = args.dtype == 'float16' fp16_trainer = FP16Trainer(trainer, dynamic_loss_scale=dynamic_loss_scale) if args.ckpt_dir and args.start_step: state_path = os.path.join(args.ckpt_dir, '%07d.states' % args.start_step) logging.info('Loading trainer state from %s', state_path) trainer.load_states(state_path) accumulate = args.accumulate num_train_steps = args.num_steps warmup_ratio = args.warmup_ratio num_warmup_steps = int(num_train_steps * warmup_ratio) params = [p for p in model.collect_params().values() if p.grad_req != 'null'] param_dict = model.collect_params() # Do not apply weight decay on LayerNorm and bias terms for _, v in model.collect_params('.*beta|.*gamma|.*bias').items(): v.wd_mult = 0.0 if accumulate > 1: for p in params: p.grad_req = 'add' train_begin_time = time.time() begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 batch_num = 0 step_num = args.start_step parallel_model = ParallelBERT(model, mlm_loss, nsp_loss, vocab_size, store.num_workers * accumulate, trainer=fp16_trainer) num_ctxes = len(ctx) parallel = nlp.utils.Parallel(num_ctxes if num_ctxes > 1 else 0, parallel_model) while step_num < num_train_steps: for _, dataloader in enumerate(data_train): if step_num >= num_train_steps: break # create dummy data loader if needed if args.dummy_data_len: target_shape = (args.batch_size*num_ctxes, args.dummy_data_len) dataloader = get_dummy_dataloader(dataloader, target_shape) for _, data_batch in enumerate(dataloader): if step_num >= num_train_steps: break if batch_num % accumulate == 0: step_num += 1 # if accumulate > 1, grad_req is set to 'add', and zero_grad is required if accumulate > 1: param_dict.zero_grad() # update learning rate if step_num <= num_warmup_steps: new_lr = lr * step_num / num_warmup_steps else: offset = lr * step_num / num_train_steps new_lr = lr - offset trainer.set_learning_rate(new_lr) if args.profile: profile(step_num, 10, 12, profile_name=args.profile) if args.use_avg_len: data_list = [[seq.as_in_context(context) for seq in shard] for context, shard in zip(ctx, data_batch)] else: if data_batch[0].shape[0] < len(ctx): continue data_list = split_and_load(data_batch, ctx) ns_label_list, ns_pred_list = [], [] mask_label_list, mask_pred_list, mask_weight_list = [], [], [] # parallel forward / backward for data in data_list: parallel.put(data) for _ in range(len(ctx)): (_, next_sentence_label, classified, masked_id, decoded, masked_weight, ls1, ls2, valid_length) = parallel.get() 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()) / num_ctxes running_nsp_loss += ls2.as_in_context(mx.cpu()) / num_ctxes running_num_tks += valid_length.sum().as_in_context(mx.cpu()) # update if (batch_num + 1) % accumulate == 0: fp16_trainer.step(1, max_norm=1) 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) % (args.log_interval) == 0 and (batch_num + 1) % accumulate == 0: log(begin_time, running_num_tks, running_mlm_loss / accumulate, running_nsp_loss / accumulate, step_num, mlm_metric, nsp_metric, trainer, args.log_interval) begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 mlm_metric.reset_local() nsp_metric.reset_local() # saving checkpoints if args.ckpt_dir and (step_num + 1) % (args.ckpt_interval) == 0 \ and (batch_num + 1) % accumulate == 0: save_params(step_num, model, trainer, args.ckpt_dir) batch_num += 1 save_params(step_num, model, trainer, args.ckpt_dir) mx.nd.waitall() train_end_time = time.time() logging.info('Train cost={:.1f}s'.format(train_end_time - train_begin_time))
[ "def", "train", "(", "data_train", ",", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocab_size", ",", "ctx", ",", "store", ")", ":", "mlm_metric", "=", "nlp", ".", "metric", ".", "MaskedAccuracy", "(", ")", "nsp_metric", "=", "nlp", ".", "metric", ".", "MaskedAccuracy", "(", ")", "mlm_metric", ".", "reset", "(", ")", "nsp_metric", ".", "reset", "(", ")", "lr", "=", "args", ".", "lr", "optim_params", "=", "{", "'learning_rate'", ":", "lr", ",", "'epsilon'", ":", "1e-6", ",", "'wd'", ":", "0.01", "}", "if", "args", ".", "dtype", "==", "'float16'", ":", "optim_params", "[", "'multi_precision'", "]", "=", "True", "trainer", "=", "mx", ".", "gluon", ".", "Trainer", "(", "model", ".", "collect_params", "(", ")", ",", "'bertadam'", ",", "optim_params", ",", "update_on_kvstore", "=", "False", ",", "kvstore", "=", "store", ")", "dynamic_loss_scale", "=", "args", ".", "dtype", "==", "'float16'", "fp16_trainer", "=", "FP16Trainer", "(", "trainer", ",", "dynamic_loss_scale", "=", "dynamic_loss_scale", ")", "if", "args", ".", "ckpt_dir", "and", "args", ".", "start_step", ":", "state_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "ckpt_dir", ",", "'%07d.states'", "%", "args", ".", "start_step", ")", "logging", ".", "info", "(", "'Loading trainer state from %s'", ",", "state_path", ")", "trainer", ".", "load_states", "(", "state_path", ")", "accumulate", "=", "args", ".", "accumulate", "num_train_steps", "=", "args", ".", "num_steps", "warmup_ratio", "=", "args", ".", "warmup_ratio", "num_warmup_steps", "=", "int", "(", "num_train_steps", "*", "warmup_ratio", ")", "params", "=", "[", "p", "for", "p", "in", "model", ".", "collect_params", "(", ")", ".", "values", "(", ")", "if", "p", ".", "grad_req", "!=", "'null'", "]", "param_dict", "=", "model", ".", "collect_params", "(", ")", "# Do not apply weight decay on LayerNorm and bias terms", "for", "_", ",", "v", "in", "model", ".", "collect_params", "(", "'.*beta|.*gamma|.*bias'", ")", ".", "items", "(", ")", ":", "v", ".", "wd_mult", "=", "0.0", "if", "accumulate", ">", "1", ":", "for", "p", "in", "params", ":", "p", ".", "grad_req", "=", "'add'", "train_begin_time", "=", "time", ".", "time", "(", ")", "begin_time", "=", "time", ".", "time", "(", ")", "running_mlm_loss", "=", "running_nsp_loss", "=", "running_num_tks", "=", "0", "batch_num", "=", "0", "step_num", "=", "args", ".", "start_step", "parallel_model", "=", "ParallelBERT", "(", "model", ",", "mlm_loss", ",", "nsp_loss", ",", "vocab_size", ",", "store", ".", "num_workers", "*", "accumulate", ",", "trainer", "=", "fp16_trainer", ")", "num_ctxes", "=", "len", "(", "ctx", ")", "parallel", "=", "nlp", ".", "utils", ".", "Parallel", "(", "num_ctxes", "if", "num_ctxes", ">", "1", "else", "0", ",", "parallel_model", ")", "while", "step_num", "<", "num_train_steps", ":", "for", "_", ",", "dataloader", "in", "enumerate", "(", "data_train", ")", ":", "if", "step_num", ">=", "num_train_steps", ":", "break", "# create dummy data loader if needed", "if", "args", ".", "dummy_data_len", ":", "target_shape", "=", "(", "args", ".", "batch_size", "*", "num_ctxes", ",", "args", ".", "dummy_data_len", ")", "dataloader", "=", "get_dummy_dataloader", "(", "dataloader", ",", "target_shape", ")", "for", "_", ",", "data_batch", "in", "enumerate", "(", "dataloader", ")", ":", "if", "step_num", ">=", "num_train_steps", ":", "break", "if", "batch_num", "%", "accumulate", "==", "0", ":", "step_num", "+=", "1", "# if accumulate > 1, grad_req is set to 'add', and zero_grad is required", "if", "accumulate", ">", "1", ":", "param_dict", ".", "zero_grad", "(", ")", "# update learning rate", "if", "step_num", "<=", "num_warmup_steps", ":", "new_lr", "=", "lr", "*", "step_num", "/", "num_warmup_steps", "else", ":", "offset", "=", "lr", "*", "step_num", "/", "num_train_steps", "new_lr", "=", "lr", "-", "offset", "trainer", ".", "set_learning_rate", "(", "new_lr", ")", "if", "args", ".", "profile", ":", "profile", "(", "step_num", ",", "10", ",", "12", ",", "profile_name", "=", "args", ".", "profile", ")", "if", "args", ".", "use_avg_len", ":", "data_list", "=", "[", "[", "seq", ".", "as_in_context", "(", "context", ")", "for", "seq", "in", "shard", "]", "for", "context", ",", "shard", "in", "zip", "(", "ctx", ",", "data_batch", ")", "]", "else", ":", "if", "data_batch", "[", "0", "]", ".", "shape", "[", "0", "]", "<", "len", "(", "ctx", ")", ":", "continue", "data_list", "=", "split_and_load", "(", "data_batch", ",", "ctx", ")", "ns_label_list", ",", "ns_pred_list", "=", "[", "]", ",", "[", "]", "mask_label_list", ",", "mask_pred_list", ",", "mask_weight_list", "=", "[", "]", ",", "[", "]", ",", "[", "]", "# parallel forward / backward", "for", "data", "in", "data_list", ":", "parallel", ".", "put", "(", "data", ")", "for", "_", "in", "range", "(", "len", "(", "ctx", ")", ")", ":", "(", "_", ",", "next_sentence_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", "ls2", ",", "valid_length", ")", "=", "parallel", ".", "get", "(", ")", "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", "(", ")", ")", "/", "num_ctxes", "running_nsp_loss", "+=", "ls2", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "/", "num_ctxes", "running_num_tks", "+=", "valid_length", ".", "sum", "(", ")", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "# update", "if", "(", "batch_num", "+", "1", ")", "%", "accumulate", "==", "0", ":", "fp16_trainer", ".", "step", "(", "1", ",", "max_norm", "=", "1", ")", "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", ")", "%", "(", "args", ".", "log_interval", ")", "==", "0", "and", "(", "batch_num", "+", "1", ")", "%", "accumulate", "==", "0", ":", "log", "(", "begin_time", ",", "running_num_tks", ",", "running_mlm_loss", "/", "accumulate", ",", "running_nsp_loss", "/", "accumulate", ",", "step_num", ",", "mlm_metric", ",", "nsp_metric", ",", "trainer", ",", "args", ".", "log_interval", ")", "begin_time", "=", "time", ".", "time", "(", ")", "running_mlm_loss", "=", "running_nsp_loss", "=", "running_num_tks", "=", "0", "mlm_metric", ".", "reset_local", "(", ")", "nsp_metric", ".", "reset_local", "(", ")", "# saving checkpoints", "if", "args", ".", "ckpt_dir", "and", "(", "step_num", "+", "1", ")", "%", "(", "args", ".", "ckpt_interval", ")", "==", "0", "and", "(", "batch_num", "+", "1", ")", "%", "accumulate", "==", "0", ":", "save_params", "(", "step_num", ",", "model", ",", "trainer", ",", "args", ".", "ckpt_dir", ")", "batch_num", "+=", "1", "save_params", "(", "step_num", ",", "model", ",", "trainer", ",", "args", ".", "ckpt_dir", ")", "mx", ".", "nd", ".", "waitall", "(", ")", "train_end_time", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'Train cost={:.1f}s'", ".", "format", "(", "train_end_time", "-", "train_begin_time", ")", ")" ]
Training function.
[ "Training", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining.py#L92-L215
train
dmlc/gluon-nlp
scripts/bert/run_pretraining.py
ParallelBERT.forward_backward
def forward_backward(self, x): """forward backward implementation""" with mx.autograd.record(): (ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length) = forward(x, self._model, self._mlm_loss, self._nsp_loss, self._vocab_size, args.dtype) ls = ls / self._rescale_factor if args.dtype == 'float16': self._trainer.backward(ls) else: ls.backward() return ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length
python
def forward_backward(self, x): """forward backward implementation""" with mx.autograd.record(): (ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length) = forward(x, self._model, self._mlm_loss, self._nsp_loss, self._vocab_size, args.dtype) ls = ls / self._rescale_factor if args.dtype == 'float16': self._trainer.backward(ls) else: ls.backward() return ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length
[ "def", "forward_backward", "(", "self", ",", "x", ")", ":", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "(", "ls", ",", "next_sentence_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", "ls2", ",", "valid_length", ")", "=", "forward", "(", "x", ",", "self", ".", "_model", ",", "self", ".", "_mlm_loss", ",", "self", ".", "_nsp_loss", ",", "self", ".", "_vocab_size", ",", "args", ".", "dtype", ")", "ls", "=", "ls", "/", "self", ".", "_rescale_factor", "if", "args", ".", "dtype", "==", "'float16'", ":", "self", ".", "_trainer", ".", "backward", "(", "ls", ")", "else", ":", "ls", ".", "backward", "(", ")", "return", "ls", ",", "next_sentence_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", "ls2", ",", "valid_length" ]
forward backward implementation
[ "forward", "backward", "implementation" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining.py#L77-L90
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.log_info
def log_info(self, logger): """Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger() """ logger.info('#words in training set: %d' % self._words_in_train_data) logger.info("Vocab info: #words %d, #tags %d #rels %d" % (self.vocab_size, self.tag_size, self.rel_size))
python
def log_info(self, logger): """Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger() """ logger.info('#words in training set: %d' % self._words_in_train_data) logger.info("Vocab info: #words %d, #tags %d #rels %d" % (self.vocab_size, self.tag_size, self.rel_size))
[ "def", "log_info", "(", "self", ",", "logger", ")", ":", "logger", ".", "info", "(", "'#words in training set: %d'", "%", "self", ".", "_words_in_train_data", ")", "logger", ".", "info", "(", "\"Vocab info: #words %d, #tags %d #rels %d\"", "%", "(", "self", ".", "vocab_size", ",", "self", ".", "tag_size", ",", "self", ".", "rel_size", ")", ")" ]
Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger()
[ "Print", "statistical", "information", "via", "the", "provided", "logger" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L162-L171
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary._add_pret_words
def _add_pret_words(self, pret_embeddings): """Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) """ words_in_train_data = set(self._id2word) pret_embeddings = gluonnlp.embedding.create(pret_embeddings[0], source=pret_embeddings[1]) for idx, token in enumerate(pret_embeddings.idx_to_token): if token not in words_in_train_data: self._id2word.append(token)
python
def _add_pret_words(self, pret_embeddings): """Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) """ words_in_train_data = set(self._id2word) pret_embeddings = gluonnlp.embedding.create(pret_embeddings[0], source=pret_embeddings[1]) for idx, token in enumerate(pret_embeddings.idx_to_token): if token not in words_in_train_data: self._id2word.append(token)
[ "def", "_add_pret_words", "(", "self", ",", "pret_embeddings", ")", ":", "words_in_train_data", "=", "set", "(", "self", ".", "_id2word", ")", "pret_embeddings", "=", "gluonnlp", ".", "embedding", ".", "create", "(", "pret_embeddings", "[", "0", "]", ",", "source", "=", "pret_embeddings", "[", "1", "]", ")", "for", "idx", ",", "token", "in", "enumerate", "(", "pret_embeddings", ".", "idx_to_token", ")", ":", "if", "token", "not", "in", "words_in_train_data", ":", "self", ".", "_id2word", ".", "append", "(", "token", ")" ]
Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source)
[ "Read", "pre", "-", "trained", "embedding", "file", "for", "extending", "vocabulary" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L173-L186
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.get_pret_embs
def get_pret_embs(self, word_dims=None): """Read pre-trained embedding file Parameters ---------- word_dims : int or None vector size. Use `None` for auto-infer Returns ------- numpy.ndarray T x C numpy NDArray """ assert (self._pret_embeddings is not None), "No pretrained file provided." pret_embeddings = gluonnlp.embedding.create(self._pret_embeddings[0], source=self._pret_embeddings[1]) embs = [None] * len(self._id2word) for idx, vec in enumerate(pret_embeddings.idx_to_vec): embs[idx] = vec.asnumpy() if word_dims is None: word_dims = len(pret_embeddings.idx_to_vec[0]) for idx, emb in enumerate(embs): if emb is None: embs[idx] = np.zeros(word_dims) pret_embs = np.array(embs, dtype=np.float32) return pret_embs / np.std(pret_embs)
python
def get_pret_embs(self, word_dims=None): """Read pre-trained embedding file Parameters ---------- word_dims : int or None vector size. Use `None` for auto-infer Returns ------- numpy.ndarray T x C numpy NDArray """ assert (self._pret_embeddings is not None), "No pretrained file provided." pret_embeddings = gluonnlp.embedding.create(self._pret_embeddings[0], source=self._pret_embeddings[1]) embs = [None] * len(self._id2word) for idx, vec in enumerate(pret_embeddings.idx_to_vec): embs[idx] = vec.asnumpy() if word_dims is None: word_dims = len(pret_embeddings.idx_to_vec[0]) for idx, emb in enumerate(embs): if emb is None: embs[idx] = np.zeros(word_dims) pret_embs = np.array(embs, dtype=np.float32) return pret_embs / np.std(pret_embs)
[ "def", "get_pret_embs", "(", "self", ",", "word_dims", "=", "None", ")", ":", "assert", "(", "self", ".", "_pret_embeddings", "is", "not", "None", ")", ",", "\"No pretrained file provided.\"", "pret_embeddings", "=", "gluonnlp", ".", "embedding", ".", "create", "(", "self", ".", "_pret_embeddings", "[", "0", "]", ",", "source", "=", "self", ".", "_pret_embeddings", "[", "1", "]", ")", "embs", "=", "[", "None", "]", "*", "len", "(", "self", ".", "_id2word", ")", "for", "idx", ",", "vec", "in", "enumerate", "(", "pret_embeddings", ".", "idx_to_vec", ")", ":", "embs", "[", "idx", "]", "=", "vec", ".", "asnumpy", "(", ")", "if", "word_dims", "is", "None", ":", "word_dims", "=", "len", "(", "pret_embeddings", ".", "idx_to_vec", "[", "0", "]", ")", "for", "idx", ",", "emb", "in", "enumerate", "(", "embs", ")", ":", "if", "emb", "is", "None", ":", "embs", "[", "idx", "]", "=", "np", ".", "zeros", "(", "word_dims", ")", "pret_embs", "=", "np", ".", "array", "(", "embs", ",", "dtype", "=", "np", ".", "float32", ")", "return", "pret_embs", "/", "np", ".", "std", "(", "pret_embs", ")" ]
Read pre-trained embedding file Parameters ---------- word_dims : int or None vector size. Use `None` for auto-infer Returns ------- numpy.ndarray T x C numpy NDArray
[ "Read", "pre", "-", "trained", "embedding", "file" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L198-L221
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.get_word_embs
def get_word_embs(self, word_dims): """Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters ---------- word_dims : int word vector size Returns ------- numpy.ndarray T x C numpy NDArray """ if self._pret_embeddings is not None: return np.random.randn(self.words_in_train, word_dims).astype(np.float32) return np.zeros((self.words_in_train, word_dims), dtype=np.float32)
python
def get_word_embs(self, word_dims): """Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters ---------- word_dims : int word vector size Returns ------- numpy.ndarray T x C numpy NDArray """ if self._pret_embeddings is not None: return np.random.randn(self.words_in_train, word_dims).astype(np.float32) return np.zeros((self.words_in_train, word_dims), dtype=np.float32)
[ "def", "get_word_embs", "(", "self", ",", "word_dims", ")", ":", "if", "self", ".", "_pret_embeddings", "is", "not", "None", ":", "return", "np", ".", "random", ".", "randn", "(", "self", ".", "words_in_train", ",", "word_dims", ")", ".", "astype", "(", "np", ".", "float32", ")", "return", "np", ".", "zeros", "(", "(", "self", ".", "words_in_train", ",", "word_dims", ")", ",", "dtype", "=", "np", ".", "float32", ")" ]
Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters ---------- word_dims : int word vector size Returns ------- numpy.ndarray T x C numpy NDArray
[ "Get", "randomly", "initialized", "embeddings", "when", "pre", "-", "trained", "embeddings", "are", "used", "otherwise", "zero", "vectors" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L223-L237
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.get_tag_embs
def get_tag_embs(self, tag_dims): """Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings """ return np.random.randn(self.tag_size, tag_dims).astype(np.float32)
python
def get_tag_embs(self, tag_dims): """Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings """ return np.random.randn(self.tag_size, tag_dims).astype(np.float32)
[ "def", "get_tag_embs", "(", "self", ",", "tag_dims", ")", ":", "return", "np", ".", "random", ".", "randn", "(", "self", ".", "tag_size", ",", "tag_dims", ")", ".", "astype", "(", "np", ".", "float32", ")" ]
Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings
[ "Randomly", "initialize", "embeddings", "for", "tag" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L239-L252
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.word2id
def word2id(self, xs): """Map word(s) to its id(s) Parameters ---------- xs : str or list word or a list of words Returns ------- int or list id or a list of ids """ if isinstance(xs, list): return [self._word2id.get(x, self.UNK) for x in xs] return self._word2id.get(xs, self.UNK)
python
def word2id(self, xs): """Map word(s) to its id(s) Parameters ---------- xs : str or list word or a list of words Returns ------- int or list id or a list of ids """ if isinstance(xs, list): return [self._word2id.get(x, self.UNK) for x in xs] return self._word2id.get(xs, self.UNK)
[ "def", "word2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_word2id", ".", "get", "(", "x", ",", "self", ".", "UNK", ")", "for", "x", "in", "xs", "]", "return", "self", ".", "_word2id", ".", "get", "(", "xs", ",", "self", ".", "UNK", ")" ]
Map word(s) to its id(s) Parameters ---------- xs : str or list word or a list of words Returns ------- int or list id or a list of ids
[ "Map", "word", "(", "s", ")", "to", "its", "id", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L254-L269
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.id2word
def id2word(self, xs): """Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words """ if isinstance(xs, list): return [self._id2word[x] for x in xs] return self._id2word[xs]
python
def id2word(self, xs): """Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words """ if isinstance(xs, list): return [self._id2word[x] for x in xs] return self._id2word[xs]
[ "def", "id2word", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_id2word", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_id2word", "[", "xs", "]" ]
Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words
[ "Map", "id", "(", "s", ")", "to", "word", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L271-L286
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.rel2id
def rel2id(self, xs): """Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation """ if isinstance(xs, list): return [self._rel2id[x] for x in xs] return self._rel2id[xs]
python
def rel2id(self, xs): """Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation """ if isinstance(xs, list): return [self._rel2id[x] for x in xs] return self._rel2id[xs]
[ "def", "rel2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_rel2id", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_rel2id", "[", "xs", "]" ]
Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation
[ "Map", "relation", "(", "s", ")", "to", "id", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L288-L303
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.id2rel
def id2rel(self, xs): """Map id(s) to relation(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list relation or a list of relations """ if isinstance(xs, list): return [self._id2rel[x] for x in xs] return self._id2rel[xs]
python
def id2rel(self, xs): """Map id(s) to relation(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list relation or a list of relations """ if isinstance(xs, list): return [self._id2rel[x] for x in xs] return self._id2rel[xs]
[ "def", "id2rel", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_id2rel", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_id2rel", "[", "xs", "]" ]
Map id(s) to relation(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list relation or a list of relations
[ "Map", "id", "(", "s", ")", "to", "relation", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L305-L320
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.tag2id
def tag2id(self, xs): """Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s) """ if isinstance(xs, list): return [self._tag2id.get(x, self.UNK) for x in xs] return self._tag2id.get(xs, self.UNK)
python
def tag2id(self, xs): """Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s) """ if isinstance(xs, list): return [self._tag2id.get(x, self.UNK) for x in xs] return self._tag2id.get(xs, self.UNK)
[ "def", "tag2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_tag2id", ".", "get", "(", "x", ",", "self", ".", "UNK", ")", "for", "x", "in", "xs", "]", "return", "self", ".", "_tag2id", ".", "get", "(", "xs", ",", "self", ".", "UNK", ")" ]
Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s)
[ "Map", "tag", "(", "s", ")", "to", "id", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L322-L337
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
DataLoader.idx_sequence
def idx_sequence(self): """Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- list List of ids ranging from 0 to #sent -1 """ return [x[1] for x in sorted(zip(self._record, list(range(len(self._record)))))]
python
def idx_sequence(self): """Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- list List of ids ranging from 0 to #sent -1 """ return [x[1] for x in sorted(zip(self._record, list(range(len(self._record)))))]
[ "def", "idx_sequence", "(", "self", ")", ":", "return", "[", "x", "[", "1", "]", "for", "x", "in", "sorted", "(", "zip", "(", "self", ".", "_record", ",", "list", "(", "range", "(", "len", "(", "self", ".", "_record", ")", ")", ")", ")", ")", "]" ]
Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- list List of ids ranging from 0 to #sent -1
[ "Indices", "of", "sentences", "when", "enumerating", "data", "set", "from", "batches", ".", "Useful", "when", "retrieving", "the", "correct", "order", "of", "sentences" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L431-L440
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
DataLoader.get_batches
def get_batches(self, batch_size, shuffle=True): """Get batch iterator Parameters ---------- batch_size : int size of one batch shuffle : bool whether to shuffle batches. Don't set to True when evaluating on dev or test set. Returns ------- tuple word_inputs, tag_inputs, arc_targets, rel_targets """ batches = [] for bkt_idx, bucket in enumerate(self._buckets): bucket_size = bucket.shape[1] n_tokens = bucket_size * self._bucket_lengths[bkt_idx] n_splits = min(max(n_tokens // batch_size, 1), bucket_size) range_func = np.random.permutation if shuffle else np.arange for bkt_batch in np.array_split(range_func(bucket_size), n_splits): batches.append((bkt_idx, bkt_batch)) if shuffle: np.random.shuffle(batches) for bkt_idx, bkt_batch in batches: word_inputs = self._buckets[bkt_idx][:, bkt_batch, 0] # word_id x sent_id tag_inputs = self._buckets[bkt_idx][:, bkt_batch, 1] arc_targets = self._buckets[bkt_idx][:, bkt_batch, 2] rel_targets = self._buckets[bkt_idx][:, bkt_batch, 3] yield word_inputs, tag_inputs, arc_targets, rel_targets
python
def get_batches(self, batch_size, shuffle=True): """Get batch iterator Parameters ---------- batch_size : int size of one batch shuffle : bool whether to shuffle batches. Don't set to True when evaluating on dev or test set. Returns ------- tuple word_inputs, tag_inputs, arc_targets, rel_targets """ batches = [] for bkt_idx, bucket in enumerate(self._buckets): bucket_size = bucket.shape[1] n_tokens = bucket_size * self._bucket_lengths[bkt_idx] n_splits = min(max(n_tokens // batch_size, 1), bucket_size) range_func = np.random.permutation if shuffle else np.arange for bkt_batch in np.array_split(range_func(bucket_size), n_splits): batches.append((bkt_idx, bkt_batch)) if shuffle: np.random.shuffle(batches) for bkt_idx, bkt_batch in batches: word_inputs = self._buckets[bkt_idx][:, bkt_batch, 0] # word_id x sent_id tag_inputs = self._buckets[bkt_idx][:, bkt_batch, 1] arc_targets = self._buckets[bkt_idx][:, bkt_batch, 2] rel_targets = self._buckets[bkt_idx][:, bkt_batch, 3] yield word_inputs, tag_inputs, arc_targets, rel_targets
[ "def", "get_batches", "(", "self", ",", "batch_size", ",", "shuffle", "=", "True", ")", ":", "batches", "=", "[", "]", "for", "bkt_idx", ",", "bucket", "in", "enumerate", "(", "self", ".", "_buckets", ")", ":", "bucket_size", "=", "bucket", ".", "shape", "[", "1", "]", "n_tokens", "=", "bucket_size", "*", "self", ".", "_bucket_lengths", "[", "bkt_idx", "]", "n_splits", "=", "min", "(", "max", "(", "n_tokens", "//", "batch_size", ",", "1", ")", ",", "bucket_size", ")", "range_func", "=", "np", ".", "random", ".", "permutation", "if", "shuffle", "else", "np", ".", "arange", "for", "bkt_batch", "in", "np", ".", "array_split", "(", "range_func", "(", "bucket_size", ")", ",", "n_splits", ")", ":", "batches", ".", "append", "(", "(", "bkt_idx", ",", "bkt_batch", ")", ")", "if", "shuffle", ":", "np", ".", "random", ".", "shuffle", "(", "batches", ")", "for", "bkt_idx", ",", "bkt_batch", "in", "batches", ":", "word_inputs", "=", "self", ".", "_buckets", "[", "bkt_idx", "]", "[", ":", ",", "bkt_batch", ",", "0", "]", "# word_id x sent_id", "tag_inputs", "=", "self", ".", "_buckets", "[", "bkt_idx", "]", "[", ":", ",", "bkt_batch", ",", "1", "]", "arc_targets", "=", "self", ".", "_buckets", "[", "bkt_idx", "]", "[", ":", ",", "bkt_batch", ",", "2", "]", "rel_targets", "=", "self", ".", "_buckets", "[", "bkt_idx", "]", "[", ":", ",", "bkt_batch", ",", "3", "]", "yield", "word_inputs", ",", "tag_inputs", ",", "arc_targets", ",", "rel_targets" ]
Get batch iterator Parameters ---------- batch_size : int size of one batch shuffle : bool whether to shuffle batches. Don't set to True when evaluating on dev or test set. Returns ------- tuple word_inputs, tag_inputs, arc_targets, rel_targets
[ "Get", "batch", "iterator" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L442-L473
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
create_ngram_set
def create_ngram_set(input_list, ngram_value=2): """ Extract a set of n-grams from a list of integers. >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] """ return set(zip(*[input_list[i:] for i in range(ngram_value)]))
python
def create_ngram_set(input_list, ngram_value=2): """ Extract a set of n-grams from a list of integers. >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] """ return set(zip(*[input_list[i:] for i in range(ngram_value)]))
[ "def", "create_ngram_set", "(", "input_list", ",", "ngram_value", "=", "2", ")", ":", "return", "set", "(", "zip", "(", "*", "[", "input_list", "[", "i", ":", "]", "for", "i", "in", "range", "(", "ngram_value", ")", "]", ")", ")" ]
Extract a set of n-grams from a list of integers. >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)]
[ "Extract", "a", "set", "of", "n", "-", "grams", "from", "a", "list", "of", "integers", ".", ">>>", "create_ngram_set", "(", "[", "1", "4", "9", "4", "1", "4", "]", "ngram_value", "=", "2", ")", "{", "(", "4", "9", ")", "(", "4", "1", ")", "(", "1", "4", ")", "(", "9", "4", ")", "}", ">>>", "create_ngram_set", "(", "[", "1", "4", "9", "4", "1", "4", "]", "ngram_value", "=", "3", ")", "[", "(", "1", "4", "9", ")", "(", "4", "9", "4", ")", "(", "9", "4", "1", ")", "(", "4", "1", "4", ")", "]" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L96-L104
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
add_ngram
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_indice, ngram_range=2) [[1, 3, 4, 5, 1337, 2017], [1, 3, 7, 9, 2, 1337, 42]] Example: adding tri-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017, (7, 9, 2): 2018} >>> add_ngram(sequences, token_indice, ngram_range=3) [[1, 3, 4, 5, 1337], [1, 3, 7, 9, 2, 1337, 2018]] """ new_sequences = [] for input_list in sequences: new_list = input_list[:] for i in range(len(new_list) - ngram_range + 1): for ngram_value in range(2, ngram_range + 1): ngram = tuple(new_list[i:i + ngram_value]) if ngram in token_indice: new_list.append(token_indice[ngram]) new_sequences.append(new_list) return new_sequences
python
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_indice, ngram_range=2) [[1, 3, 4, 5, 1337, 2017], [1, 3, 7, 9, 2, 1337, 42]] Example: adding tri-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017, (7, 9, 2): 2018} >>> add_ngram(sequences, token_indice, ngram_range=3) [[1, 3, 4, 5, 1337], [1, 3, 7, 9, 2, 1337, 2018]] """ new_sequences = [] for input_list in sequences: new_list = input_list[:] for i in range(len(new_list) - ngram_range + 1): for ngram_value in range(2, ngram_range + 1): ngram = tuple(new_list[i:i + ngram_value]) if ngram in token_indice: new_list.append(token_indice[ngram]) new_sequences.append(new_list) return new_sequences
[ "def", "add_ngram", "(", "sequences", ",", "token_indice", ",", "ngram_range", "=", "2", ")", ":", "new_sequences", "=", "[", "]", "for", "input_list", "in", "sequences", ":", "new_list", "=", "input_list", "[", ":", "]", "for", "i", "in", "range", "(", "len", "(", "new_list", ")", "-", "ngram_range", "+", "1", ")", ":", "for", "ngram_value", "in", "range", "(", "2", ",", "ngram_range", "+", "1", ")", ":", "ngram", "=", "tuple", "(", "new_list", "[", "i", ":", "i", "+", "ngram_value", "]", ")", "if", "ngram", "in", "token_indice", ":", "new_list", ".", "append", "(", "token_indice", "[", "ngram", "]", ")", "new_sequences", ".", "append", "(", "new_list", ")", "return", "new_sequences" ]
Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_indice, ngram_range=2) [[1, 3, 4, 5, 1337, 2017], [1, 3, 7, 9, 2, 1337, 42]] Example: adding tri-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017, (7, 9, 2): 2018} >>> add_ngram(sequences, token_indice, ngram_range=3) [[1, 3, 4, 5, 1337], [1, 3, 7, 9, 2, 1337, 2018]]
[ "Augment", "the", "input", "list", "of", "list", "(", "sequences", ")", "by", "appending", "n", "-", "grams", "values", ".", "Example", ":", "adding", "bi", "-", "gram", ">>>", "sequences", "=", "[[", "1", "3", "4", "5", "]", "[", "1", "3", "7", "9", "2", "]]", ">>>", "token_indice", "=", "{", "(", "1", "3", ")", ":", "1337", "(", "9", "2", ")", ":", "42", "(", "4", "5", ")", ":", "2017", "}", ">>>", "add_ngram", "(", "sequences", "token_indice", "ngram_range", "=", "2", ")", "[[", "1", "3", "4", "5", "1337", "2017", "]", "[", "1", "3", "7", "9", "2", "1337", "42", "]]", "Example", ":", "adding", "tri", "-", "gram", ">>>", "sequences", "=", "[[", "1", "3", "4", "5", "]", "[", "1", "3", "7", "9", "2", "]]", ">>>", "token_indice", "=", "{", "(", "1", "3", ")", ":", "1337", "(", "9", "2", ")", ":", "42", "(", "4", "5", ")", ":", "2017", "(", "7", "9", "2", ")", ":", "2018", "}", ">>>", "add_ngram", "(", "sequences", "token_indice", "ngram_range", "=", "3", ")", "[[", "1", "3", "4", "5", "1337", "]", "[", "1", "3", "7", "9", "2", "1337", "2018", "]]" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L107-L131
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
evaluate_accuracy
def evaluate_accuracy(data_iterator, net, ctx, loss_fun, num_classes): """ This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too! """ acc = mx.metric.Accuracy() loss_avg = 0. for i, ((data, length), label) in enumerate(data_iterator): data = data.as_in_context(ctx) # .reshape((-1,784)) length = length.astype('float32').as_in_context(ctx) label = label.as_in_context(ctx) output = net(data, length) loss = loss_fun(output, label) preds = [] if num_classes == 2: preds = (nd.sign(output) + 1) / 2 preds = preds.reshape(-1) else: preds = nd.argmax(output, axis=1) acc.update(preds=preds, labels=label) loss_avg = loss_avg * i / (i + 1) + nd.mean(loss).asscalar() / (i + 1) return acc.get()[1], loss_avg
python
def evaluate_accuracy(data_iterator, net, ctx, loss_fun, num_classes): """ This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too! """ acc = mx.metric.Accuracy() loss_avg = 0. for i, ((data, length), label) in enumerate(data_iterator): data = data.as_in_context(ctx) # .reshape((-1,784)) length = length.astype('float32').as_in_context(ctx) label = label.as_in_context(ctx) output = net(data, length) loss = loss_fun(output, label) preds = [] if num_classes == 2: preds = (nd.sign(output) + 1) / 2 preds = preds.reshape(-1) else: preds = nd.argmax(output, axis=1) acc.update(preds=preds, labels=label) loss_avg = loss_avg * i / (i + 1) + nd.mean(loss).asscalar() / (i + 1) return acc.get()[1], loss_avg
[ "def", "evaluate_accuracy", "(", "data_iterator", ",", "net", ",", "ctx", ",", "loss_fun", ",", "num_classes", ")", ":", "acc", "=", "mx", ".", "metric", ".", "Accuracy", "(", ")", "loss_avg", "=", "0.", "for", "i", ",", "(", "(", "data", ",", "length", ")", ",", "label", ")", "in", "enumerate", "(", "data_iterator", ")", ":", "data", "=", "data", ".", "as_in_context", "(", "ctx", ")", "# .reshape((-1,784))", "length", "=", "length", ".", "astype", "(", "'float32'", ")", ".", "as_in_context", "(", "ctx", ")", "label", "=", "label", ".", "as_in_context", "(", "ctx", ")", "output", "=", "net", "(", "data", ",", "length", ")", "loss", "=", "loss_fun", "(", "output", ",", "label", ")", "preds", "=", "[", "]", "if", "num_classes", "==", "2", ":", "preds", "=", "(", "nd", ".", "sign", "(", "output", ")", "+", "1", ")", "/", "2", "preds", "=", "preds", ".", "reshape", "(", "-", "1", ")", "else", ":", "preds", "=", "nd", ".", "argmax", "(", "output", ",", "axis", "=", "1", ")", "acc", ".", "update", "(", "preds", "=", "preds", ",", "labels", "=", "label", ")", "loss_avg", "=", "loss_avg", "*", "i", "/", "(", "i", "+", "1", ")", "+", "nd", ".", "mean", "(", "loss", ")", ".", "asscalar", "(", ")", "/", "(", "i", "+", "1", ")", "return", "acc", ".", "get", "(", ")", "[", "1", "]", ",", "loss_avg" ]
This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too!
[ "This", "function", "is", "used", "for", "evaluating", "accuracy", "of", "a", "given", "data", "iterator", ".", "(", "Either", "Train", "/", "Test", "data", ")", "It", "takes", "in", "the", "loss", "function", "used", "too!" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L134-L156
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
read_input_data
def read_input_data(filename): """Helper function to get training data""" logging.info('Opening file %s for reading input', filename) input_file = open(filename, 'r') data = [] labels = [] for line in input_file: tokens = line.split(',', 1) labels.append(tokens[0].strip()) data.append(tokens[1].strip()) return labels, data
python
def read_input_data(filename): """Helper function to get training data""" logging.info('Opening file %s for reading input', filename) input_file = open(filename, 'r') data = [] labels = [] for line in input_file: tokens = line.split(',', 1) labels.append(tokens[0].strip()) data.append(tokens[1].strip()) return labels, data
[ "def", "read_input_data", "(", "filename", ")", ":", "logging", ".", "info", "(", "'Opening file %s for reading input'", ",", "filename", ")", "input_file", "=", "open", "(", "filename", ",", "'r'", ")", "data", "=", "[", "]", "labels", "=", "[", "]", "for", "line", "in", "input_file", ":", "tokens", "=", "line", ".", "split", "(", "','", ",", "1", ")", "labels", ".", "append", "(", "tokens", "[", "0", "]", ".", "strip", "(", ")", ")", "data", ".", "append", "(", "tokens", "[", "1", "]", ".", "strip", "(", ")", ")", "return", "labels", ",", "data" ]
Helper function to get training data
[ "Helper", "function", "to", "get", "training", "data" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L159-L169
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
parse_args
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='Text Classification with FastText', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Computation options group = parser.add_argument_group('Computation arguments') group.add_argument('--input', type=str, help='Input file location') group.add_argument( '--validation', type=str, help='Validation file Location ') group.add_argument( '--output', type=str, help='Location to save trained model') group.add_argument( '--ngrams', type=int, default=1, help='NGrams used for training') group.add_argument( '--batch_size', type=int, default=16, help='Batch size for training.') group.add_argument('--epochs', type=int, default=10, help='Epoch limit') group.add_argument( '--gpu', type=int, 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.') # Model group = parser.add_argument_group('Model arguments') group.add_argument( '--emsize', type=int, default=100, help='Size of embedding vectors.') # Optimization options group = parser.add_argument_group('Optimization arguments') group.add_argument('--optimizer', type=str, default='adam') group.add_argument('--lr', type=float, default=0.05) args = parser.parse_args() return args
python
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='Text Classification with FastText', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Computation options group = parser.add_argument_group('Computation arguments') group.add_argument('--input', type=str, help='Input file location') group.add_argument( '--validation', type=str, help='Validation file Location ') group.add_argument( '--output', type=str, help='Location to save trained model') group.add_argument( '--ngrams', type=int, default=1, help='NGrams used for training') group.add_argument( '--batch_size', type=int, default=16, help='Batch size for training.') group.add_argument('--epochs', type=int, default=10, help='Epoch limit') group.add_argument( '--gpu', type=int, 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.') # Model group = parser.add_argument_group('Model arguments') group.add_argument( '--emsize', type=int, default=100, help='Size of embedding vectors.') # Optimization options group = parser.add_argument_group('Optimization arguments') group.add_argument('--optimizer', type=str, default='adam') group.add_argument('--lr', type=float, default=0.05) args = parser.parse_args() return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Text Classification with FastText'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "# Computation options", "group", "=", "parser", ".", "add_argument_group", "(", "'Computation arguments'", ")", "group", ".", "add_argument", "(", "'--input'", ",", "type", "=", "str", ",", "help", "=", "'Input file location'", ")", "group", ".", "add_argument", "(", "'--validation'", ",", "type", "=", "str", ",", "help", "=", "'Validation file Location '", ")", "group", ".", "add_argument", "(", "'--output'", ",", "type", "=", "str", ",", "help", "=", "'Location to save trained model'", ")", "group", ".", "add_argument", "(", "'--ngrams'", ",", "type", "=", "int", ",", "default", "=", "1", ",", "help", "=", "'NGrams used for training'", ")", "group", ".", "add_argument", "(", "'--batch_size'", ",", "type", "=", "int", ",", "default", "=", "16", ",", "help", "=", "'Batch size for training.'", ")", "group", ".", "add_argument", "(", "'--epochs'", ",", "type", "=", "int", ",", "default", "=", "10", ",", "help", "=", "'Epoch limit'", ")", "group", ".", "add_argument", "(", "'--gpu'", ",", "type", "=", "int", ",", "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.'", ")", "# Model", "group", "=", "parser", ".", "add_argument_group", "(", "'Model arguments'", ")", "group", ".", "add_argument", "(", "'--emsize'", ",", "type", "=", "int", ",", "default", "=", "100", ",", "help", "=", "'Size of embedding vectors.'", ")", "# Optimization options", "group", "=", "parser", ".", "add_argument_group", "(", "'Optimization arguments'", ")", "group", ".", "add_argument", "(", "'--optimizer'", ",", "type", "=", "str", ",", "default", "=", "'adam'", ")", "group", ".", "add_argument", "(", "'--lr'", ",", "type", "=", "float", ",", "default", "=", "0.05", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "return", "args" ]
Parse command line arguments.
[ "Parse", "command", "line", "arguments", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L175-L214
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
get_label_mapping
def get_label_mapping(train_labels): """ Create the mapping from label to numeric label """ sorted_labels = np.sort(np.unique(train_labels)) label_mapping = {} for i, label in enumerate(sorted_labels): label_mapping[label] = i logging.info('Label mapping:%s', format(label_mapping)) return label_mapping
python
def get_label_mapping(train_labels): """ Create the mapping from label to numeric label """ sorted_labels = np.sort(np.unique(train_labels)) label_mapping = {} for i, label in enumerate(sorted_labels): label_mapping[label] = i logging.info('Label mapping:%s', format(label_mapping)) return label_mapping
[ "def", "get_label_mapping", "(", "train_labels", ")", ":", "sorted_labels", "=", "np", ".", "sort", "(", "np", ".", "unique", "(", "train_labels", ")", ")", "label_mapping", "=", "{", "}", "for", "i", ",", "label", "in", "enumerate", "(", "sorted_labels", ")", ":", "label_mapping", "[", "label", "]", "=", "i", "logging", ".", "info", "(", "'Label mapping:%s'", ",", "format", "(", "label_mapping", ")", ")", "return", "label_mapping" ]
Create the mapping from label to numeric label
[ "Create", "the", "mapping", "from", "label", "to", "numeric", "label" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L217-L226
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
convert_to_sequences
def convert_to_sequences(dataset, vocab): """This function takes a dataset and converts it into sequences via multiprocessing """ start = time.time() dataset_vocab = map(lambda x: (x, vocab), dataset) with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. output = pool.map(get_sequence, dataset_vocab) end = time.time() logging.info('Done! Sequence conversion Time={:.2f}s, #Sentences={}' .format(end - start, len(dataset))) return output
python
def convert_to_sequences(dataset, vocab): """This function takes a dataset and converts it into sequences via multiprocessing """ start = time.time() dataset_vocab = map(lambda x: (x, vocab), dataset) with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. output = pool.map(get_sequence, dataset_vocab) end = time.time() logging.info('Done! Sequence conversion Time={:.2f}s, #Sentences={}' .format(end - start, len(dataset))) return output
[ "def", "convert_to_sequences", "(", "dataset", ",", "vocab", ")", ":", "start", "=", "time", ".", "time", "(", ")", "dataset_vocab", "=", "map", "(", "lambda", "x", ":", "(", "x", ",", "vocab", ")", ",", "dataset", ")", "with", "mp", ".", "Pool", "(", ")", "as", "pool", ":", "# Each sample is processed in an asynchronous manner.", "output", "=", "pool", ".", "map", "(", "get_sequence", ",", "dataset_vocab", ")", "end", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'Done! Sequence conversion Time={:.2f}s, #Sentences={}'", ".", "format", "(", "end", "-", "start", ",", "len", "(", "dataset", ")", ")", ")", "return", "output" ]
This function takes a dataset and converts it into sequences via multiprocessing
[ "This", "function", "takes", "a", "dataset", "and", "converts", "it", "into", "sequences", "via", "multiprocessing" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L256-L268
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
preprocess_dataset
def preprocess_dataset(dataset, labels): """ Preprocess and prepare a dataset""" start = time.time() with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. dataset = gluon.data.SimpleDataset(list(zip(dataset, labels))) lengths = gluon.data.SimpleDataset(pool.map(get_length, dataset)) end = time.time() logging.info('Done! Preprocessing Time={:.2f}s, #Sentences={}' .format(end - start, len(dataset))) return dataset, lengths
python
def preprocess_dataset(dataset, labels): """ Preprocess and prepare a dataset""" start = time.time() with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. dataset = gluon.data.SimpleDataset(list(zip(dataset, labels))) lengths = gluon.data.SimpleDataset(pool.map(get_length, dataset)) end = time.time() logging.info('Done! Preprocessing Time={:.2f}s, #Sentences={}' .format(end - start, len(dataset))) return dataset, lengths
[ "def", "preprocess_dataset", "(", "dataset", ",", "labels", ")", ":", "start", "=", "time", ".", "time", "(", ")", "with", "mp", ".", "Pool", "(", ")", "as", "pool", ":", "# Each sample is processed in an asynchronous manner.", "dataset", "=", "gluon", ".", "data", ".", "SimpleDataset", "(", "list", "(", "zip", "(", "dataset", ",", "labels", ")", ")", ")", "lengths", "=", "gluon", ".", "data", ".", "SimpleDataset", "(", "pool", ".", "map", "(", "get_length", ",", "dataset", ")", ")", "end", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'Done! Preprocessing Time={:.2f}s, #Sentences={}'", ".", "format", "(", "end", "-", "start", ",", "len", "(", "dataset", ")", ")", ")", "return", "dataset", ",", "lengths" ]
Preprocess and prepare a dataset
[ "Preprocess", "and", "prepare", "a", "dataset" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L271-L281
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
get_dataloader
def get_dataloader(train_dataset, train_data_lengths, test_dataset, batch_size): """ Construct the DataLoader. Pad data, stack label and lengths""" bucket_num, bucket_ratio = 20, 0.2 batchify_fn = gluonnlp.data.batchify.Tuple( gluonnlp.data.batchify.Pad(axis=0, ret_length=True), gluonnlp.data.batchify.Stack(dtype='float32')) batch_sampler = gluonnlp.data.sampler.FixedBucketSampler( train_data_lengths, batch_size=batch_size, num_buckets=bucket_num, ratio=bucket_ratio, shuffle=True) train_dataloader = gluon.data.DataLoader( dataset=train_dataset, batch_sampler=batch_sampler, batchify_fn=batchify_fn) test_dataloader = gluon.data.DataLoader( dataset=test_dataset, batch_size=batch_size, shuffle=False, batchify_fn=batchify_fn) return train_dataloader, test_dataloader
python
def get_dataloader(train_dataset, train_data_lengths, test_dataset, batch_size): """ Construct the DataLoader. Pad data, stack label and lengths""" bucket_num, bucket_ratio = 20, 0.2 batchify_fn = gluonnlp.data.batchify.Tuple( gluonnlp.data.batchify.Pad(axis=0, ret_length=True), gluonnlp.data.batchify.Stack(dtype='float32')) batch_sampler = gluonnlp.data.sampler.FixedBucketSampler( train_data_lengths, batch_size=batch_size, num_buckets=bucket_num, ratio=bucket_ratio, shuffle=True) train_dataloader = gluon.data.DataLoader( dataset=train_dataset, batch_sampler=batch_sampler, batchify_fn=batchify_fn) test_dataloader = gluon.data.DataLoader( dataset=test_dataset, batch_size=batch_size, shuffle=False, batchify_fn=batchify_fn) return train_dataloader, test_dataloader
[ "def", "get_dataloader", "(", "train_dataset", ",", "train_data_lengths", ",", "test_dataset", ",", "batch_size", ")", ":", "bucket_num", ",", "bucket_ratio", "=", "20", ",", "0.2", "batchify_fn", "=", "gluonnlp", ".", "data", ".", "batchify", ".", "Tuple", "(", "gluonnlp", ".", "data", ".", "batchify", ".", "Pad", "(", "axis", "=", "0", ",", "ret_length", "=", "True", ")", ",", "gluonnlp", ".", "data", ".", "batchify", ".", "Stack", "(", "dtype", "=", "'float32'", ")", ")", "batch_sampler", "=", "gluonnlp", ".", "data", ".", "sampler", ".", "FixedBucketSampler", "(", "train_data_lengths", ",", "batch_size", "=", "batch_size", ",", "num_buckets", "=", "bucket_num", ",", "ratio", "=", "bucket_ratio", ",", "shuffle", "=", "True", ")", "train_dataloader", "=", "gluon", ".", "data", ".", "DataLoader", "(", "dataset", "=", "train_dataset", ",", "batch_sampler", "=", "batch_sampler", ",", "batchify_fn", "=", "batchify_fn", ")", "test_dataloader", "=", "gluon", ".", "data", ".", "DataLoader", "(", "dataset", "=", "test_dataset", ",", "batch_size", "=", "batch_size", ",", "shuffle", "=", "False", ",", "batchify_fn", "=", "batchify_fn", ")", "return", "train_dataloader", ",", "test_dataloader" ]
Construct the DataLoader. Pad data, stack label and lengths
[ "Construct", "the", "DataLoader", ".", "Pad", "data", "stack", "label", "and", "lengths" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L284-L306
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
train
def train(args): """Training function that orchestrates the Classification! """ train_file = args.input test_file = args.validation ngram_range = args.ngrams logging.info('Ngrams range for the training run : %s', ngram_range) logging.info('Loading Training data') train_labels, train_data = read_input_data(train_file) logging.info('Loading Test data') test_labels, test_data = read_input_data(test_file) tokens_list = [] for line in train_data: tokens_list.extend(line.split()) cntr = Counter(tokens_list) train_vocab = gluonnlp.Vocab(cntr) logging.info('Vocabulary size: %s', len(train_vocab)) logging.info('Training data converting to sequences...') embedding_matrix_len = len(train_vocab) # Preprocess the dataset train_sequences = convert_to_sequences(train_data, train_vocab) test_sequences = convert_to_sequences(test_data, train_vocab) if ngram_range >= 2: logging.info('Adding %s-gram features', ngram_range) # Create set of unique n-gram from the training set. ngram_set = set() for input_list in train_sequences: for i in range(2, ngram_range + 1): set_of_ngram = create_ngram_set(input_list, ngram_value=i) ngram_set.update(set_of_ngram) start_index = len(cntr) token_indices = {v: k + start_index for k, v in enumerate(ngram_set)} embedding_matrix_len = embedding_matrix_len + len(token_indices) train_sequences = add_ngram(train_sequences, token_indices, ngram_range) test_sequences = add_ngram(test_sequences, token_indices, ngram_range) logging.info('Added n-gram features to train and test datasets!! ') logging.info('Encoding labels') label_mapping = get_label_mapping(train_labels) y_train_final = list(map(lambda x: label_mapping[x], train_labels)) y_test_final = list(map(lambda x: label_mapping[x], test_labels)) train_sequences, train_data_lengths = preprocess_dataset( train_sequences, y_train_final) test_sequences, _ = preprocess_dataset( test_sequences, y_test_final) train_dataloader, test_dataloader = get_dataloader(train_sequences, train_data_lengths, test_sequences, args.batch_size) num_classes = len(np.unique(train_labels)) logging.info('Number of labels: %s', num_classes) logging.info('Initializing network') ctx = get_context(args) logging.info('Running Training on ctx:%s', ctx) embedding_dim = args.emsize logging.info('Embedding Matrix Length:%s', embedding_matrix_len) net = FastTextClassificationModel( embedding_matrix_len, embedding_dim, num_classes) net.hybridize() net.collect_params().initialize(mx.init.Xavier(), ctx=ctx) logging.info('Network initialized') softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss() sigmoid_loss_fn = gluon.loss.SigmoidBinaryCrossEntropyLoss() loss_function = softmax_cross_entropy if num_classes == 2: logging.info( 'Changing the loss function to sigmoid since its Binary Classification' ) loss_function = sigmoid_loss_fn logging.info('Loss function for training:%s', loss_function) num_epochs = args.epochs batch_size = args.batch_size logging.info('Starting Training!') learning_rate = args.lr trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': learning_rate}) num_batches = len(train_data) / batch_size display_batch_cadence = int(math.ceil(num_batches / 10)) logging.info('Training on %s samples and testing on %s samples', len(train_data), len(test_data)) logging.info('Number of batches for each epoch : %s, Display cadence: %s', num_batches, display_batch_cadence) for epoch in range(num_epochs): for batch, ((data, length), label) in enumerate(train_dataloader): data = data.as_in_context(ctx) label = label.as_in_context(ctx) length = length.astype('float32').as_in_context(ctx) with autograd.record(): output = net(data, length) loss = loss_function(output, label) loss.backward() trainer.step(data.shape[0]) if batch % display_batch_cadence == 0: logging.info('Epoch : %s, Batches complete :%s', epoch, batch) logging.info('Epoch complete :%s, Computing Accuracy', epoch) test_accuracy, test_loss = evaluate_accuracy( test_dataloader, net, ctx, loss_function, num_classes) logging.info('Epochs completed : %s Test Accuracy: %s, Test Loss: %s', epoch, test_accuracy, test_loss) learning_rate = learning_rate * 0.5 trainer.set_learning_rate(learning_rate) save_model(net, args.output)
python
def train(args): """Training function that orchestrates the Classification! """ train_file = args.input test_file = args.validation ngram_range = args.ngrams logging.info('Ngrams range for the training run : %s', ngram_range) logging.info('Loading Training data') train_labels, train_data = read_input_data(train_file) logging.info('Loading Test data') test_labels, test_data = read_input_data(test_file) tokens_list = [] for line in train_data: tokens_list.extend(line.split()) cntr = Counter(tokens_list) train_vocab = gluonnlp.Vocab(cntr) logging.info('Vocabulary size: %s', len(train_vocab)) logging.info('Training data converting to sequences...') embedding_matrix_len = len(train_vocab) # Preprocess the dataset train_sequences = convert_to_sequences(train_data, train_vocab) test_sequences = convert_to_sequences(test_data, train_vocab) if ngram_range >= 2: logging.info('Adding %s-gram features', ngram_range) # Create set of unique n-gram from the training set. ngram_set = set() for input_list in train_sequences: for i in range(2, ngram_range + 1): set_of_ngram = create_ngram_set(input_list, ngram_value=i) ngram_set.update(set_of_ngram) start_index = len(cntr) token_indices = {v: k + start_index for k, v in enumerate(ngram_set)} embedding_matrix_len = embedding_matrix_len + len(token_indices) train_sequences = add_ngram(train_sequences, token_indices, ngram_range) test_sequences = add_ngram(test_sequences, token_indices, ngram_range) logging.info('Added n-gram features to train and test datasets!! ') logging.info('Encoding labels') label_mapping = get_label_mapping(train_labels) y_train_final = list(map(lambda x: label_mapping[x], train_labels)) y_test_final = list(map(lambda x: label_mapping[x], test_labels)) train_sequences, train_data_lengths = preprocess_dataset( train_sequences, y_train_final) test_sequences, _ = preprocess_dataset( test_sequences, y_test_final) train_dataloader, test_dataloader = get_dataloader(train_sequences, train_data_lengths, test_sequences, args.batch_size) num_classes = len(np.unique(train_labels)) logging.info('Number of labels: %s', num_classes) logging.info('Initializing network') ctx = get_context(args) logging.info('Running Training on ctx:%s', ctx) embedding_dim = args.emsize logging.info('Embedding Matrix Length:%s', embedding_matrix_len) net = FastTextClassificationModel( embedding_matrix_len, embedding_dim, num_classes) net.hybridize() net.collect_params().initialize(mx.init.Xavier(), ctx=ctx) logging.info('Network initialized') softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss() sigmoid_loss_fn = gluon.loss.SigmoidBinaryCrossEntropyLoss() loss_function = softmax_cross_entropy if num_classes == 2: logging.info( 'Changing the loss function to sigmoid since its Binary Classification' ) loss_function = sigmoid_loss_fn logging.info('Loss function for training:%s', loss_function) num_epochs = args.epochs batch_size = args.batch_size logging.info('Starting Training!') learning_rate = args.lr trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': learning_rate}) num_batches = len(train_data) / batch_size display_batch_cadence = int(math.ceil(num_batches / 10)) logging.info('Training on %s samples and testing on %s samples', len(train_data), len(test_data)) logging.info('Number of batches for each epoch : %s, Display cadence: %s', num_batches, display_batch_cadence) for epoch in range(num_epochs): for batch, ((data, length), label) in enumerate(train_dataloader): data = data.as_in_context(ctx) label = label.as_in_context(ctx) length = length.astype('float32').as_in_context(ctx) with autograd.record(): output = net(data, length) loss = loss_function(output, label) loss.backward() trainer.step(data.shape[0]) if batch % display_batch_cadence == 0: logging.info('Epoch : %s, Batches complete :%s', epoch, batch) logging.info('Epoch complete :%s, Computing Accuracy', epoch) test_accuracy, test_loss = evaluate_accuracy( test_dataloader, net, ctx, loss_function, num_classes) logging.info('Epochs completed : %s Test Accuracy: %s, Test Loss: %s', epoch, test_accuracy, test_loss) learning_rate = learning_rate * 0.5 trainer.set_learning_rate(learning_rate) save_model(net, args.output)
[ "def", "train", "(", "args", ")", ":", "train_file", "=", "args", ".", "input", "test_file", "=", "args", ".", "validation", "ngram_range", "=", "args", ".", "ngrams", "logging", ".", "info", "(", "'Ngrams range for the training run : %s'", ",", "ngram_range", ")", "logging", ".", "info", "(", "'Loading Training data'", ")", "train_labels", ",", "train_data", "=", "read_input_data", "(", "train_file", ")", "logging", ".", "info", "(", "'Loading Test data'", ")", "test_labels", ",", "test_data", "=", "read_input_data", "(", "test_file", ")", "tokens_list", "=", "[", "]", "for", "line", "in", "train_data", ":", "tokens_list", ".", "extend", "(", "line", ".", "split", "(", ")", ")", "cntr", "=", "Counter", "(", "tokens_list", ")", "train_vocab", "=", "gluonnlp", ".", "Vocab", "(", "cntr", ")", "logging", ".", "info", "(", "'Vocabulary size: %s'", ",", "len", "(", "train_vocab", ")", ")", "logging", ".", "info", "(", "'Training data converting to sequences...'", ")", "embedding_matrix_len", "=", "len", "(", "train_vocab", ")", "# Preprocess the dataset", "train_sequences", "=", "convert_to_sequences", "(", "train_data", ",", "train_vocab", ")", "test_sequences", "=", "convert_to_sequences", "(", "test_data", ",", "train_vocab", ")", "if", "ngram_range", ">=", "2", ":", "logging", ".", "info", "(", "'Adding %s-gram features'", ",", "ngram_range", ")", "# Create set of unique n-gram from the training set.", "ngram_set", "=", "set", "(", ")", "for", "input_list", "in", "train_sequences", ":", "for", "i", "in", "range", "(", "2", ",", "ngram_range", "+", "1", ")", ":", "set_of_ngram", "=", "create_ngram_set", "(", "input_list", ",", "ngram_value", "=", "i", ")", "ngram_set", ".", "update", "(", "set_of_ngram", ")", "start_index", "=", "len", "(", "cntr", ")", "token_indices", "=", "{", "v", ":", "k", "+", "start_index", "for", "k", ",", "v", "in", "enumerate", "(", "ngram_set", ")", "}", "embedding_matrix_len", "=", "embedding_matrix_len", "+", "len", "(", "token_indices", ")", "train_sequences", "=", "add_ngram", "(", "train_sequences", ",", "token_indices", ",", "ngram_range", ")", "test_sequences", "=", "add_ngram", "(", "test_sequences", ",", "token_indices", ",", "ngram_range", ")", "logging", ".", "info", "(", "'Added n-gram features to train and test datasets!! '", ")", "logging", ".", "info", "(", "'Encoding labels'", ")", "label_mapping", "=", "get_label_mapping", "(", "train_labels", ")", "y_train_final", "=", "list", "(", "map", "(", "lambda", "x", ":", "label_mapping", "[", "x", "]", ",", "train_labels", ")", ")", "y_test_final", "=", "list", "(", "map", "(", "lambda", "x", ":", "label_mapping", "[", "x", "]", ",", "test_labels", ")", ")", "train_sequences", ",", "train_data_lengths", "=", "preprocess_dataset", "(", "train_sequences", ",", "y_train_final", ")", "test_sequences", ",", "_", "=", "preprocess_dataset", "(", "test_sequences", ",", "y_test_final", ")", "train_dataloader", ",", "test_dataloader", "=", "get_dataloader", "(", "train_sequences", ",", "train_data_lengths", ",", "test_sequences", ",", "args", ".", "batch_size", ")", "num_classes", "=", "len", "(", "np", ".", "unique", "(", "train_labels", ")", ")", "logging", ".", "info", "(", "'Number of labels: %s'", ",", "num_classes", ")", "logging", ".", "info", "(", "'Initializing network'", ")", "ctx", "=", "get_context", "(", "args", ")", "logging", ".", "info", "(", "'Running Training on ctx:%s'", ",", "ctx", ")", "embedding_dim", "=", "args", ".", "emsize", "logging", ".", "info", "(", "'Embedding Matrix Length:%s'", ",", "embedding_matrix_len", ")", "net", "=", "FastTextClassificationModel", "(", "embedding_matrix_len", ",", "embedding_dim", ",", "num_classes", ")", "net", ".", "hybridize", "(", ")", "net", ".", "collect_params", "(", ")", ".", "initialize", "(", "mx", ".", "init", ".", "Xavier", "(", ")", ",", "ctx", "=", "ctx", ")", "logging", ".", "info", "(", "'Network initialized'", ")", "softmax_cross_entropy", "=", "gluon", ".", "loss", ".", "SoftmaxCrossEntropyLoss", "(", ")", "sigmoid_loss_fn", "=", "gluon", ".", "loss", ".", "SigmoidBinaryCrossEntropyLoss", "(", ")", "loss_function", "=", "softmax_cross_entropy", "if", "num_classes", "==", "2", ":", "logging", ".", "info", "(", "'Changing the loss function to sigmoid since its Binary Classification'", ")", "loss_function", "=", "sigmoid_loss_fn", "logging", ".", "info", "(", "'Loss function for training:%s'", ",", "loss_function", ")", "num_epochs", "=", "args", ".", "epochs", "batch_size", "=", "args", ".", "batch_size", "logging", ".", "info", "(", "'Starting Training!'", ")", "learning_rate", "=", "args", ".", "lr", "trainer", "=", "gluon", ".", "Trainer", "(", "net", ".", "collect_params", "(", ")", ",", "'adam'", ",", "{", "'learning_rate'", ":", "learning_rate", "}", ")", "num_batches", "=", "len", "(", "train_data", ")", "/", "batch_size", "display_batch_cadence", "=", "int", "(", "math", ".", "ceil", "(", "num_batches", "/", "10", ")", ")", "logging", ".", "info", "(", "'Training on %s samples and testing on %s samples'", ",", "len", "(", "train_data", ")", ",", "len", "(", "test_data", ")", ")", "logging", ".", "info", "(", "'Number of batches for each epoch : %s, Display cadence: %s'", ",", "num_batches", ",", "display_batch_cadence", ")", "for", "epoch", "in", "range", "(", "num_epochs", ")", ":", "for", "batch", ",", "(", "(", "data", ",", "length", ")", ",", "label", ")", "in", "enumerate", "(", "train_dataloader", ")", ":", "data", "=", "data", ".", "as_in_context", "(", "ctx", ")", "label", "=", "label", ".", "as_in_context", "(", "ctx", ")", "length", "=", "length", ".", "astype", "(", "'float32'", ")", ".", "as_in_context", "(", "ctx", ")", "with", "autograd", ".", "record", "(", ")", ":", "output", "=", "net", "(", "data", ",", "length", ")", "loss", "=", "loss_function", "(", "output", ",", "label", ")", "loss", ".", "backward", "(", ")", "trainer", ".", "step", "(", "data", ".", "shape", "[", "0", "]", ")", "if", "batch", "%", "display_batch_cadence", "==", "0", ":", "logging", ".", "info", "(", "'Epoch : %s, Batches complete :%s'", ",", "epoch", ",", "batch", ")", "logging", ".", "info", "(", "'Epoch complete :%s, Computing Accuracy'", ",", "epoch", ")", "test_accuracy", ",", "test_loss", "=", "evaluate_accuracy", "(", "test_dataloader", ",", "net", ",", "ctx", ",", "loss_function", ",", "num_classes", ")", "logging", ".", "info", "(", "'Epochs completed : %s Test Accuracy: %s, Test Loss: %s'", ",", "epoch", ",", "test_accuracy", ",", "test_loss", ")", "learning_rate", "=", "learning_rate", "*", "0.5", "trainer", ".", "set_learning_rate", "(", "learning_rate", ")", "save_model", "(", "net", ",", "args", ".", "output", ")" ]
Training function that orchestrates the Classification!
[ "Training", "function", "that", "orchestrates", "the", "Classification!" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L311-L416
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert_qa_model.py
StaticBertForQA.hybrid_forward
def hybrid_forward(self, F, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """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 hybrid_forward(self, F, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """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", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "bert_output", "=", "self", ".", "bert", "(", "inputs", ",", "token_types", ",", "valid_length", ")", "output", "=", "self", ".", "span_classifier", "(", "bert_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/staticbert/static_bert_qa_model.py#L50-L72
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert_qa_model.py
BertForQALoss.hybrid_forward
def hybrid_forward(self, F, pred, label): # pylint: disable=arguments-differ """ Parameters ---------- pred : NDArray, shape (batch_size, seq_length, 2) BERTSquad forward output. label : list, length is 2, each shape is (batch_size,1) label[0] is the starting position of the answer, label[1] is the ending position of the answer. Returns ------- outputs : NDArray Shape (batch_size,) """ pred = F.split(pred, axis=2, num_outputs=2) start_pred = pred[0].reshape((0, -3)) start_label = label[0] end_pred = pred[1].reshape((0, -3)) end_label = label[1] return (self.loss(start_pred, start_label) + self.loss( end_pred, end_label)) / 2
python
def hybrid_forward(self, F, pred, label): # pylint: disable=arguments-differ """ Parameters ---------- pred : NDArray, shape (batch_size, seq_length, 2) BERTSquad forward output. label : list, length is 2, each shape is (batch_size,1) label[0] is the starting position of the answer, label[1] is the ending position of the answer. Returns ------- outputs : NDArray Shape (batch_size,) """ pred = F.split(pred, axis=2, num_outputs=2) start_pred = pred[0].reshape((0, -3)) start_label = label[0] end_pred = pred[1].reshape((0, -3)) end_label = label[1] return (self.loss(start_pred, start_label) + self.loss( end_pred, end_label)) / 2
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "pred", ",", "label", ")", ":", "# pylint: disable=arguments-differ", "pred", "=", "F", ".", "split", "(", "pred", ",", "axis", "=", "2", ",", "num_outputs", "=", "2", ")", "start_pred", "=", "pred", "[", "0", "]", ".", "reshape", "(", "(", "0", ",", "-", "3", ")", ")", "start_label", "=", "label", "[", "0", "]", "end_pred", "=", "pred", "[", "1", "]", ".", "reshape", "(", "(", "0", ",", "-", "3", ")", ")", "end_label", "=", "label", "[", "1", "]", "return", "(", "self", ".", "loss", "(", "start_pred", ",", "start_label", ")", "+", "self", ".", "loss", "(", "end_pred", ",", "end_label", ")", ")", "/", "2" ]
Parameters ---------- pred : NDArray, shape (batch_size, seq_length, 2) BERTSquad forward output. label : list, length is 2, each shape is (batch_size,1) label[0] is the starting position of the answer, label[1] is the ending position of the answer. Returns ------- outputs : NDArray Shape (batch_size,)
[ "Parameters", "----------", "pred", ":", "NDArray", "shape", "(", "batch_size", "seq_length", "2", ")", "BERTSquad", "forward", "output", ".", "label", ":", "list", "length", "is", "2", "each", "shape", "is", "(", "batch_size", "1", ")", "label", "[", "0", "]", "is", "the", "starting", "position", "of", "the", "answer", "label", "[", "1", "]", "is", "the", "ending", "position", "of", "the", "answer", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert_qa_model.py#L85-L106
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.encode
def encode(self, inputs, states=None, valid_length=None): """Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : list Outputs of the encoder. """ return self.encoder(self.src_embed(inputs), states, valid_length)
python
def encode(self, inputs, states=None, valid_length=None): """Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : list Outputs of the encoder. """ return self.encoder(self.src_embed(inputs), states, valid_length)
[ "def", "encode", "(", "self", ",", "inputs", ",", "states", "=", "None", ",", "valid_length", "=", "None", ")", ":", "return", "self", ".", "encoder", "(", "self", ".", "src_embed", "(", "inputs", ")", ",", "states", ",", "valid_length", ")" ]
Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : list Outputs of the encoder.
[ "Encode", "the", "input", "sequence", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L129-L143
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.decode_seq
def decode_seq(self, inputs, states, valid_length=None): """Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray The output of the decoder. Shape is (batch_size, length, tgt_word_num) states: list The new states of the decoder additional_outputs : list Additional outputs of the decoder, e.g, the attention weights """ outputs, states, additional_outputs =\ self.decoder.decode_seq(inputs=self.tgt_embed(inputs), states=states, valid_length=valid_length) outputs = self.tgt_proj(outputs) return outputs, states, additional_outputs
python
def decode_seq(self, inputs, states, valid_length=None): """Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray The output of the decoder. Shape is (batch_size, length, tgt_word_num) states: list The new states of the decoder additional_outputs : list Additional outputs of the decoder, e.g, the attention weights """ outputs, states, additional_outputs =\ self.decoder.decode_seq(inputs=self.tgt_embed(inputs), states=states, valid_length=valid_length) outputs = self.tgt_proj(outputs) return outputs, states, additional_outputs
[ "def", "decode_seq", "(", "self", ",", "inputs", ",", "states", ",", "valid_length", "=", "None", ")", ":", "outputs", ",", "states", ",", "additional_outputs", "=", "self", ".", "decoder", ".", "decode_seq", "(", "inputs", "=", "self", ".", "tgt_embed", "(", "inputs", ")", ",", "states", "=", "states", ",", "valid_length", "=", "valid_length", ")", "outputs", "=", "self", ".", "tgt_proj", "(", "outputs", ")", "return", "outputs", ",", "states", ",", "additional_outputs" ]
Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray The output of the decoder. Shape is (batch_size, length, tgt_word_num) states: list The new states of the decoder additional_outputs : list Additional outputs of the decoder, e.g, the attention weights
[ "Decode", "given", "the", "input", "sequence", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L145-L168
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.decode_step
def decode_step(self, step_input, states): """One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_size, C_out) states : list step_additional_outputs : list Additional outputs of the step, e.g, the attention weights """ step_output, states, step_additional_outputs =\ self.decoder(self.tgt_embed(step_input), states) step_output = self.tgt_proj(step_output) return step_output, states, step_additional_outputs
python
def decode_step(self, step_input, states): """One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_size, C_out) states : list step_additional_outputs : list Additional outputs of the step, e.g, the attention weights """ step_output, states, step_additional_outputs =\ self.decoder(self.tgt_embed(step_input), states) step_output = self.tgt_proj(step_output) return step_output, states, step_additional_outputs
[ "def", "decode_step", "(", "self", ",", "step_input", ",", "states", ")", ":", "step_output", ",", "states", ",", "step_additional_outputs", "=", "self", ".", "decoder", "(", "self", ".", "tgt_embed", "(", "step_input", ")", ",", "states", ")", "step_output", "=", "self", ".", "tgt_proj", "(", "step_output", ")", "return", "step_output", ",", "states", ",", "step_additional_outputs" ]
One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_size, C_out) states : list step_additional_outputs : list Additional outputs of the step, e.g, the attention weights
[ "One", "step", "decoding", "of", "the", "translation", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L170-L190
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.forward
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): #pylint: disable=arguments-differ """Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArray src_valid_length : NDArray or None tgt_valid_length : NDArray or None Returns ------- outputs : NDArray Shape (batch_size, tgt_length, tgt_word_num) additional_outputs : list of list Additional outputs of encoder and decoder, e.g, the attention weights """ additional_outputs = [] encoder_outputs, encoder_additional_outputs = self.encode(src_seq, valid_length=src_valid_length) decoder_states = self.decoder.init_state_from_encoder(encoder_outputs, encoder_valid_length=src_valid_length) outputs, _, decoder_additional_outputs =\ self.decode_seq(tgt_seq, decoder_states, tgt_valid_length) additional_outputs.append(encoder_additional_outputs) additional_outputs.append(decoder_additional_outputs) return outputs, additional_outputs
python
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): #pylint: disable=arguments-differ """Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArray src_valid_length : NDArray or None tgt_valid_length : NDArray or None Returns ------- outputs : NDArray Shape (batch_size, tgt_length, tgt_word_num) additional_outputs : list of list Additional outputs of encoder and decoder, e.g, the attention weights """ additional_outputs = [] encoder_outputs, encoder_additional_outputs = self.encode(src_seq, valid_length=src_valid_length) decoder_states = self.decoder.init_state_from_encoder(encoder_outputs, encoder_valid_length=src_valid_length) outputs, _, decoder_additional_outputs =\ self.decode_seq(tgt_seq, decoder_states, tgt_valid_length) additional_outputs.append(encoder_additional_outputs) additional_outputs.append(decoder_additional_outputs) return outputs, additional_outputs
[ "def", "forward", "(", "self", ",", "src_seq", ",", "tgt_seq", ",", "src_valid_length", "=", "None", ",", "tgt_valid_length", "=", "None", ")", ":", "#pylint: disable=arguments-differ", "additional_outputs", "=", "[", "]", "encoder_outputs", ",", "encoder_additional_outputs", "=", "self", ".", "encode", "(", "src_seq", ",", "valid_length", "=", "src_valid_length", ")", "decoder_states", "=", "self", ".", "decoder", ".", "init_state_from_encoder", "(", "encoder_outputs", ",", "encoder_valid_length", "=", "src_valid_length", ")", "outputs", ",", "_", ",", "decoder_additional_outputs", "=", "self", ".", "decode_seq", "(", "tgt_seq", ",", "decoder_states", ",", "tgt_valid_length", ")", "additional_outputs", ".", "append", "(", "encoder_additional_outputs", ")", "additional_outputs", ".", "append", "(", "decoder_additional_outputs", ")", "return", "outputs", ",", "additional_outputs" ]
Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArray src_valid_length : NDArray or None tgt_valid_length : NDArray or None Returns ------- outputs : NDArray Shape (batch_size, tgt_length, tgt_word_num) additional_outputs : list of list Additional outputs of encoder and decoder, e.g, the attention weights
[ "Generate", "the", "prediction", "given", "the", "src_seq", "and", "tgt_seq", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L213-L241
train
dmlc/gluon-nlp
src/gluonnlp/vocab/subwords.py
create_subword_function
def create_subword_function(subword_function_name, **kwargs): """Creates an instance of a subword function.""" create_ = registry.get_create_func(SubwordFunction, 'token embedding') return create_(subword_function_name, **kwargs)
python
def create_subword_function(subword_function_name, **kwargs): """Creates an instance of a subword function.""" create_ = registry.get_create_func(SubwordFunction, 'token embedding') return create_(subword_function_name, **kwargs)
[ "def", "create_subword_function", "(", "subword_function_name", ",", "*", "*", "kwargs", ")", ":", "create_", "=", "registry", ".", "get_create_func", "(", "SubwordFunction", ",", "'token embedding'", ")", "return", "create_", "(", "subword_function_name", ",", "*", "*", "kwargs", ")" ]
Creates an instance of a subword function.
[ "Creates", "an", "instance", "of", "a", "subword", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/subwords.py#L43-L47
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab._index_special_tokens
def _index_special_tokens(self, unknown_token, special_tokens): """Indexes unknown and reserved tokens.""" self._idx_to_token = [unknown_token] if unknown_token else [] if not special_tokens: self._reserved_tokens = None else: self._reserved_tokens = special_tokens[:] self._idx_to_token.extend(special_tokens) if unknown_token: self._token_to_idx = DefaultLookupDict(C.UNK_IDX) else: self._token_to_idx = {} self._token_to_idx.update((token, idx) for idx, token in enumerate(self._idx_to_token))
python
def _index_special_tokens(self, unknown_token, special_tokens): """Indexes unknown and reserved tokens.""" self._idx_to_token = [unknown_token] if unknown_token else [] if not special_tokens: self._reserved_tokens = None else: self._reserved_tokens = special_tokens[:] self._idx_to_token.extend(special_tokens) if unknown_token: self._token_to_idx = DefaultLookupDict(C.UNK_IDX) else: self._token_to_idx = {} self._token_to_idx.update((token, idx) for idx, token in enumerate(self._idx_to_token))
[ "def", "_index_special_tokens", "(", "self", ",", "unknown_token", ",", "special_tokens", ")", ":", "self", ".", "_idx_to_token", "=", "[", "unknown_token", "]", "if", "unknown_token", "else", "[", "]", "if", "not", "special_tokens", ":", "self", ".", "_reserved_tokens", "=", "None", "else", ":", "self", ".", "_reserved_tokens", "=", "special_tokens", "[", ":", "]", "self", ".", "_idx_to_token", ".", "extend", "(", "special_tokens", ")", "if", "unknown_token", ":", "self", ".", "_token_to_idx", "=", "DefaultLookupDict", "(", "C", ".", "UNK_IDX", ")", "else", ":", "self", ".", "_token_to_idx", "=", "{", "}", "self", ".", "_token_to_idx", ".", "update", "(", "(", "token", ",", "idx", ")", "for", "idx", ",", "token", "in", "enumerate", "(", "self", ".", "_idx_to_token", ")", ")" ]
Indexes unknown and reserved tokens.
[ "Indexes", "unknown", "and", "reserved", "tokens", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L163-L177
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab._index_counter_keys
def _index_counter_keys(self, counter, unknown_token, special_tokens, max_size, min_freq): """Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`. """ unknown_and_special_tokens = set(special_tokens) if special_tokens else set() if unknown_token: unknown_and_special_tokens.add(unknown_token) token_freqs = sorted(counter.items(), key=lambda x: x[0]) token_freqs.sort(key=lambda x: x[1], reverse=True) token_cap = len(unknown_and_special_tokens) + ( len(counter) if not max_size else max_size) for token, freq in token_freqs: if freq < min_freq or len(self._idx_to_token) == token_cap: break if token not in unknown_and_special_tokens: self._idx_to_token.append(token) self._token_to_idx[token] = len(self._idx_to_token) - 1
python
def _index_counter_keys(self, counter, unknown_token, special_tokens, max_size, min_freq): """Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`. """ unknown_and_special_tokens = set(special_tokens) if special_tokens else set() if unknown_token: unknown_and_special_tokens.add(unknown_token) token_freqs = sorted(counter.items(), key=lambda x: x[0]) token_freqs.sort(key=lambda x: x[1], reverse=True) token_cap = len(unknown_and_special_tokens) + ( len(counter) if not max_size else max_size) for token, freq in token_freqs: if freq < min_freq or len(self._idx_to_token) == token_cap: break if token not in unknown_and_special_tokens: self._idx_to_token.append(token) self._token_to_idx[token] = len(self._idx_to_token) - 1
[ "def", "_index_counter_keys", "(", "self", ",", "counter", ",", "unknown_token", ",", "special_tokens", ",", "max_size", ",", "min_freq", ")", ":", "unknown_and_special_tokens", "=", "set", "(", "special_tokens", ")", "if", "special_tokens", "else", "set", "(", ")", "if", "unknown_token", ":", "unknown_and_special_tokens", ".", "add", "(", "unknown_token", ")", "token_freqs", "=", "sorted", "(", "counter", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "token_freqs", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "token_cap", "=", "len", "(", "unknown_and_special_tokens", ")", "+", "(", "len", "(", "counter", ")", "if", "not", "max_size", "else", "max_size", ")", "for", "token", ",", "freq", "in", "token_freqs", ":", "if", "freq", "<", "min_freq", "or", "len", "(", "self", ".", "_idx_to_token", ")", "==", "token_cap", ":", "break", "if", "token", "not", "in", "unknown_and_special_tokens", ":", "self", ".", "_idx_to_token", ".", "append", "(", "token", ")", "self", ".", "_token_to_idx", "[", "token", "]", "=", "len", "(", "self", ".", "_idx_to_token", ")", "-", "1" ]
Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`.
[ "Indexes", "keys", "of", "counter", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L179-L204
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.set_embedding
def set_embedding(self, *embeddings): """Attaches one or more embeddings to the indexed text tokens. Parameters ---------- embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances The embedding to be attached to the indexed tokens. If a tuple of multiple embeddings are provided, their embedding vectors will be concatenated for the same token. """ if len(embeddings) == 1 and embeddings[0] is None: self._embedding = None return for embs in embeddings: assert isinstance(embs, emb.TokenEmbedding), \ 'The argument `embeddings` must be an instance or a list of instances of ' \ '`gluonnlp.embedding.TokenEmbedding`.' assert embs.idx_to_vec is not None, \ 'For all specified `embeddings`, `embeddings.idx_to_vec` must be initialized. ' \ 'Use eg. `emb[emb.unknown_token] = nd.zeros(emsize)` to initialize, ' \ 'where `emsize` is the desired embedding dimensionality.' assert all([embs.unknown_token for embs in embeddings]) or \ all([not embs.unknown_token for embs in embeddings]), \ 'Either all or none of the TokenEmbeddings must have an ' \ 'unknown_token set.' new_embedding = emb.TokenEmbedding(self.unknown_token, allow_extend=False) new_embedding._token_to_idx = self.token_to_idx new_embedding._idx_to_token = self.idx_to_token new_vec_len = sum(embs.idx_to_vec.shape[1] for embs in embeddings) new_idx_to_vec = nd.zeros(shape=(len(self), new_vec_len)) col_start = 0 # Concatenate all the embedding vectors in embedding. for embs in embeddings: if embs and embs.idx_to_vec is not None: col_end = col_start + embs.idx_to_vec.shape[1] # Cancatenate vectors of the unknown token. new_idx_to_vec[0, col_start:col_end] = embs.idx_to_vec[0] new_idx_to_vec[1:, col_start:col_end] = embs[self._idx_to_token[1:]] col_start = col_end new_embedding._idx_to_vec = new_idx_to_vec self._embedding = new_embedding
python
def set_embedding(self, *embeddings): """Attaches one or more embeddings to the indexed text tokens. Parameters ---------- embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances The embedding to be attached to the indexed tokens. If a tuple of multiple embeddings are provided, their embedding vectors will be concatenated for the same token. """ if len(embeddings) == 1 and embeddings[0] is None: self._embedding = None return for embs in embeddings: assert isinstance(embs, emb.TokenEmbedding), \ 'The argument `embeddings` must be an instance or a list of instances of ' \ '`gluonnlp.embedding.TokenEmbedding`.' assert embs.idx_to_vec is not None, \ 'For all specified `embeddings`, `embeddings.idx_to_vec` must be initialized. ' \ 'Use eg. `emb[emb.unknown_token] = nd.zeros(emsize)` to initialize, ' \ 'where `emsize` is the desired embedding dimensionality.' assert all([embs.unknown_token for embs in embeddings]) or \ all([not embs.unknown_token for embs in embeddings]), \ 'Either all or none of the TokenEmbeddings must have an ' \ 'unknown_token set.' new_embedding = emb.TokenEmbedding(self.unknown_token, allow_extend=False) new_embedding._token_to_idx = self.token_to_idx new_embedding._idx_to_token = self.idx_to_token new_vec_len = sum(embs.idx_to_vec.shape[1] for embs in embeddings) new_idx_to_vec = nd.zeros(shape=(len(self), new_vec_len)) col_start = 0 # Concatenate all the embedding vectors in embedding. for embs in embeddings: if embs and embs.idx_to_vec is not None: col_end = col_start + embs.idx_to_vec.shape[1] # Cancatenate vectors of the unknown token. new_idx_to_vec[0, col_start:col_end] = embs.idx_to_vec[0] new_idx_to_vec[1:, col_start:col_end] = embs[self._idx_to_token[1:]] col_start = col_end new_embedding._idx_to_vec = new_idx_to_vec self._embedding = new_embedding
[ "def", "set_embedding", "(", "self", ",", "*", "embeddings", ")", ":", "if", "len", "(", "embeddings", ")", "==", "1", "and", "embeddings", "[", "0", "]", "is", "None", ":", "self", ".", "_embedding", "=", "None", "return", "for", "embs", "in", "embeddings", ":", "assert", "isinstance", "(", "embs", ",", "emb", ".", "TokenEmbedding", ")", ",", "'The argument `embeddings` must be an instance or a list of instances of '", "'`gluonnlp.embedding.TokenEmbedding`.'", "assert", "embs", ".", "idx_to_vec", "is", "not", "None", ",", "'For all specified `embeddings`, `embeddings.idx_to_vec` must be initialized. '", "'Use eg. `emb[emb.unknown_token] = nd.zeros(emsize)` to initialize, '", "'where `emsize` is the desired embedding dimensionality.'", "assert", "all", "(", "[", "embs", ".", "unknown_token", "for", "embs", "in", "embeddings", "]", ")", "or", "all", "(", "[", "not", "embs", ".", "unknown_token", "for", "embs", "in", "embeddings", "]", ")", ",", "'Either all or none of the TokenEmbeddings must have an '", "'unknown_token set.'", "new_embedding", "=", "emb", ".", "TokenEmbedding", "(", "self", ".", "unknown_token", ",", "allow_extend", "=", "False", ")", "new_embedding", ".", "_token_to_idx", "=", "self", ".", "token_to_idx", "new_embedding", ".", "_idx_to_token", "=", "self", ".", "idx_to_token", "new_vec_len", "=", "sum", "(", "embs", ".", "idx_to_vec", ".", "shape", "[", "1", "]", "for", "embs", "in", "embeddings", ")", "new_idx_to_vec", "=", "nd", ".", "zeros", "(", "shape", "=", "(", "len", "(", "self", ")", ",", "new_vec_len", ")", ")", "col_start", "=", "0", "# Concatenate all the embedding vectors in embedding.", "for", "embs", "in", "embeddings", ":", "if", "embs", "and", "embs", ".", "idx_to_vec", "is", "not", "None", ":", "col_end", "=", "col_start", "+", "embs", ".", "idx_to_vec", ".", "shape", "[", "1", "]", "# Cancatenate vectors of the unknown token.", "new_idx_to_vec", "[", "0", ",", "col_start", ":", "col_end", "]", "=", "embs", ".", "idx_to_vec", "[", "0", "]", "new_idx_to_vec", "[", "1", ":", ",", "col_start", ":", "col_end", "]", "=", "embs", "[", "self", ".", "_idx_to_token", "[", "1", ":", "]", "]", "col_start", "=", "col_end", "new_embedding", ".", "_idx_to_vec", "=", "new_idx_to_vec", "self", ".", "_embedding", "=", "new_embedding" ]
Attaches one or more embeddings to the indexed text tokens. Parameters ---------- embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances The embedding to be attached to the indexed tokens. If a tuple of multiple embeddings are provided, their embedding vectors will be concatenated for the same token.
[ "Attaches", "one", "or", "more", "embeddings", "to", "the", "indexed", "text", "tokens", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L281-L328
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.to_tokens
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs A token or a list of tokens according to the vocabulary. """ to_reduce = False if not isinstance(indices, (list, tuple)): indices = [indices] to_reduce = True max_idx = len(self._idx_to_token) - 1 tokens = [] for idx in indices: if not isinstance(idx, int) or idx > max_idx: raise ValueError('Token index {} in the provided `indices` is invalid.'.format(idx)) else: tokens.append(self._idx_to_token[idx]) return tokens[0] if to_reduce else tokens
python
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs A token or a list of tokens according to the vocabulary. """ to_reduce = False if not isinstance(indices, (list, tuple)): indices = [indices] to_reduce = True max_idx = len(self._idx_to_token) - 1 tokens = [] for idx in indices: if not isinstance(idx, int) or idx > max_idx: raise ValueError('Token index {} in the provided `indices` is invalid.'.format(idx)) else: tokens.append(self._idx_to_token[idx]) return tokens[0] if to_reduce else tokens
[ "def", "to_tokens", "(", "self", ",", "indices", ")", ":", "to_reduce", "=", "False", "if", "not", "isinstance", "(", "indices", ",", "(", "list", ",", "tuple", ")", ")", ":", "indices", "=", "[", "indices", "]", "to_reduce", "=", "True", "max_idx", "=", "len", "(", "self", ".", "_idx_to_token", ")", "-", "1", "tokens", "=", "[", "]", "for", "idx", "in", "indices", ":", "if", "not", "isinstance", "(", "idx", ",", "int", ")", "or", "idx", ">", "max_idx", ":", "raise", "ValueError", "(", "'Token index {} in the provided `indices` is invalid.'", ".", "format", "(", "idx", ")", ")", "else", ":", "tokens", ".", "append", "(", "self", ".", "_idx_to_token", "[", "idx", "]", ")", "return", "tokens", "[", "0", "]", "if", "to_reduce", "else", "tokens" ]
Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs A token or a list of tokens according to the vocabulary.
[ "Converts", "token", "indices", "to", "tokens", "according", "to", "the", "vocabulary", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L330-L360
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.to_json
def to_json(self): """Serialize Vocab object to json string. This method does not serialize the underlying embedding. """ if self._embedding: warnings.warn('Serialization of attached embedding ' 'to json is not supported. ' 'You may serialize the embedding to a binary format ' 'separately using vocab.embedding.serialize') vocab_dict = {} vocab_dict['idx_to_token'] = self._idx_to_token vocab_dict['token_to_idx'] = dict(self._token_to_idx) vocab_dict['reserved_tokens'] = self._reserved_tokens vocab_dict['unknown_token'] = self._unknown_token vocab_dict['padding_token'] = self._padding_token vocab_dict['bos_token'] = self._bos_token vocab_dict['eos_token'] = self._eos_token return json.dumps(vocab_dict)
python
def to_json(self): """Serialize Vocab object to json string. This method does not serialize the underlying embedding. """ if self._embedding: warnings.warn('Serialization of attached embedding ' 'to json is not supported. ' 'You may serialize the embedding to a binary format ' 'separately using vocab.embedding.serialize') vocab_dict = {} vocab_dict['idx_to_token'] = self._idx_to_token vocab_dict['token_to_idx'] = dict(self._token_to_idx) vocab_dict['reserved_tokens'] = self._reserved_tokens vocab_dict['unknown_token'] = self._unknown_token vocab_dict['padding_token'] = self._padding_token vocab_dict['bos_token'] = self._bos_token vocab_dict['eos_token'] = self._eos_token return json.dumps(vocab_dict)
[ "def", "to_json", "(", "self", ")", ":", "if", "self", ".", "_embedding", ":", "warnings", ".", "warn", "(", "'Serialization of attached embedding '", "'to json is not supported. '", "'You may serialize the embedding to a binary format '", "'separately using vocab.embedding.serialize'", ")", "vocab_dict", "=", "{", "}", "vocab_dict", "[", "'idx_to_token'", "]", "=", "self", ".", "_idx_to_token", "vocab_dict", "[", "'token_to_idx'", "]", "=", "dict", "(", "self", ".", "_token_to_idx", ")", "vocab_dict", "[", "'reserved_tokens'", "]", "=", "self", ".", "_reserved_tokens", "vocab_dict", "[", "'unknown_token'", "]", "=", "self", ".", "_unknown_token", "vocab_dict", "[", "'padding_token'", "]", "=", "self", ".", "_padding_token", "vocab_dict", "[", "'bos_token'", "]", "=", "self", ".", "_bos_token", "vocab_dict", "[", "'eos_token'", "]", "=", "self", ".", "_eos_token", "return", "json", ".", "dumps", "(", "vocab_dict", ")" ]
Serialize Vocab object to json string. This method does not serialize the underlying embedding.
[ "Serialize", "Vocab", "object", "to", "json", "string", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L402-L420
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.from_json
def from_json(cls, json_str): """Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab """ vocab_dict = json.loads(json_str) unknown_token = vocab_dict.get('unknown_token') vocab = cls(unknown_token=unknown_token) vocab._idx_to_token = vocab_dict.get('idx_to_token') vocab._token_to_idx = vocab_dict.get('token_to_idx') if unknown_token: vocab._token_to_idx = DefaultLookupDict(vocab._token_to_idx[unknown_token], vocab._token_to_idx) vocab._reserved_tokens = vocab_dict.get('reserved_tokens') vocab._padding_token = vocab_dict.get('padding_token') vocab._bos_token = vocab_dict.get('bos_token') vocab._eos_token = vocab_dict.get('eos_token') return vocab
python
def from_json(cls, json_str): """Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab """ vocab_dict = json.loads(json_str) unknown_token = vocab_dict.get('unknown_token') vocab = cls(unknown_token=unknown_token) vocab._idx_to_token = vocab_dict.get('idx_to_token') vocab._token_to_idx = vocab_dict.get('token_to_idx') if unknown_token: vocab._token_to_idx = DefaultLookupDict(vocab._token_to_idx[unknown_token], vocab._token_to_idx) vocab._reserved_tokens = vocab_dict.get('reserved_tokens') vocab._padding_token = vocab_dict.get('padding_token') vocab._bos_token = vocab_dict.get('bos_token') vocab._eos_token = vocab_dict.get('eos_token') return vocab
[ "def", "from_json", "(", "cls", ",", "json_str", ")", ":", "vocab_dict", "=", "json", ".", "loads", "(", "json_str", ")", "unknown_token", "=", "vocab_dict", ".", "get", "(", "'unknown_token'", ")", "vocab", "=", "cls", "(", "unknown_token", "=", "unknown_token", ")", "vocab", ".", "_idx_to_token", "=", "vocab_dict", ".", "get", "(", "'idx_to_token'", ")", "vocab", ".", "_token_to_idx", "=", "vocab_dict", ".", "get", "(", "'token_to_idx'", ")", "if", "unknown_token", ":", "vocab", ".", "_token_to_idx", "=", "DefaultLookupDict", "(", "vocab", ".", "_token_to_idx", "[", "unknown_token", "]", ",", "vocab", ".", "_token_to_idx", ")", "vocab", ".", "_reserved_tokens", "=", "vocab_dict", ".", "get", "(", "'reserved_tokens'", ")", "vocab", ".", "_padding_token", "=", "vocab_dict", ".", "get", "(", "'padding_token'", ")", "vocab", ".", "_bos_token", "=", "vocab_dict", ".", "get", "(", "'bos_token'", ")", "vocab", ".", "_eos_token", "=", "vocab_dict", ".", "get", "(", "'eos_token'", ")", "return", "vocab" ]
Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab
[ "Deserialize", "Vocab", "object", "from", "json", "string", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L423-L449
train
dmlc/gluon-nlp
scripts/bert/run_pretraining_hvd.py
train
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx): """Training function.""" hvd.broadcast_parameters(model.collect_params(), root_rank=0) mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() logging.debug('Creating distributed trainer...') lr = args.lr optim_params = {'learning_rate': lr, 'epsilon': 1e-6, 'wd': 0.01} if args.dtype == 'float16': optim_params['multi_precision'] = True dynamic_loss_scale = args.dtype == 'float16' if dynamic_loss_scale: loss_scale_param = {'scale_window': 2000 / num_workers} else: loss_scale_param = None trainer = hvd.DistributedTrainer(model.collect_params(), 'bertadam', optim_params) fp16_trainer = FP16Trainer(trainer, dynamic_loss_scale=dynamic_loss_scale, loss_scaler_params=loss_scale_param) if args.ckpt_dir and args.start_step: trainer.load_states(os.path.join(args.ckpt_dir, '%07d.states'%args.start_step)) accumulate = args.accumulate num_train_steps = args.num_steps warmup_ratio = args.warmup_ratio num_warmup_steps = int(num_train_steps * warmup_ratio) params = [p for p in model.collect_params().values() if p.grad_req != 'null'] param_dict = model.collect_params() # Do not apply weight decay on LayerNorm and bias terms for _, v in model.collect_params('.*beta|.*gamma|.*bias').items(): v.wd_mult = 0.0 if accumulate > 1: for p in params: p.grad_req = 'add' train_begin_time = time.time() begin_time = time.time() running_mlm_loss, running_nsp_loss = 0, 0 running_num_tks = 0 batch_num = 0 step_num = args.start_step logging.debug('Training started') while step_num < num_train_steps: for _, dataloader in enumerate(data_train): if step_num >= num_train_steps: break # create dummy data loader if needed if args.dummy_data_len: target_shape = (args.batch_size, args.dummy_data_len) dataloader = get_dummy_dataloader(dataloader, target_shape) for _, data_batch in enumerate(dataloader): if step_num >= num_train_steps: break if batch_num % accumulate == 0: step_num += 1 # if accumulate > 1, grad_req is set to 'add', and zero_grad is required if accumulate > 1: param_dict.zero_grad() # update learning rate if step_num <= num_warmup_steps: new_lr = lr * step_num / num_warmup_steps else: offset = lr * step_num / num_train_steps new_lr = lr - offset trainer.set_learning_rate(new_lr) if args.profile: profile(step_num, 10, 14, profile_name=args.profile + str(rank)) # load data if args.use_avg_len: data_list = [[seq.as_in_context(context) for seq in shard] for context, shard in zip([ctx], data_batch)] else: data_list = list(split_and_load(data_batch, [ctx])) data = data_list[0] # forward with mx.autograd.record(): (ls, ns_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_len) = forward(data, model, mlm_loss, nsp_loss, vocab_size, args.dtype) ls = ls / accumulate # backward if args.dtype == 'float16': fp16_trainer.backward(ls) else: ls.backward() running_mlm_loss += ls1.as_in_context(mx.cpu()) running_nsp_loss += ls2.as_in_context(mx.cpu()) running_num_tks += valid_len.sum().as_in_context(mx.cpu()) # update if (batch_num + 1) % accumulate == 0: # step() performs 3 things: # 1. allreduce gradients from all workers # 2. checking the global_norm of gradients and clip them if necessary # 3. averaging the gradients and apply updates fp16_trainer.step(1, max_norm=1*num_workers) nsp_metric.update([ns_label], [classified]) mlm_metric.update([masked_id], [decoded], [masked_weight]) # logging if (step_num + 1) % (args.log_interval) == 0 and (batch_num + 1) % accumulate == 0: log(begin_time, running_num_tks, running_mlm_loss / accumulate, running_nsp_loss / accumulate, step_num, mlm_metric, nsp_metric, trainer, args.log_interval) begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 mlm_metric.reset_local() nsp_metric.reset_local() # saving checkpoints if args.ckpt_dir and (step_num + 1) % (args.ckpt_interval) == 0 \ and (batch_num + 1) % accumulate == 0 and local_rank == 0: save_params(step_num, model, trainer, args.ckpt_dir) batch_num += 1 if local_rank == 0: save_params(step_num, model, trainer, args.ckpt_dir) mx.nd.waitall() train_end_time = time.time() logging.info('Train cost={:.1f}s'.format(train_end_time - train_begin_time))
python
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx): """Training function.""" hvd.broadcast_parameters(model.collect_params(), root_rank=0) mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() logging.debug('Creating distributed trainer...') lr = args.lr optim_params = {'learning_rate': lr, 'epsilon': 1e-6, 'wd': 0.01} if args.dtype == 'float16': optim_params['multi_precision'] = True dynamic_loss_scale = args.dtype == 'float16' if dynamic_loss_scale: loss_scale_param = {'scale_window': 2000 / num_workers} else: loss_scale_param = None trainer = hvd.DistributedTrainer(model.collect_params(), 'bertadam', optim_params) fp16_trainer = FP16Trainer(trainer, dynamic_loss_scale=dynamic_loss_scale, loss_scaler_params=loss_scale_param) if args.ckpt_dir and args.start_step: trainer.load_states(os.path.join(args.ckpt_dir, '%07d.states'%args.start_step)) accumulate = args.accumulate num_train_steps = args.num_steps warmup_ratio = args.warmup_ratio num_warmup_steps = int(num_train_steps * warmup_ratio) params = [p for p in model.collect_params().values() if p.grad_req != 'null'] param_dict = model.collect_params() # Do not apply weight decay on LayerNorm and bias terms for _, v in model.collect_params('.*beta|.*gamma|.*bias').items(): v.wd_mult = 0.0 if accumulate > 1: for p in params: p.grad_req = 'add' train_begin_time = time.time() begin_time = time.time() running_mlm_loss, running_nsp_loss = 0, 0 running_num_tks = 0 batch_num = 0 step_num = args.start_step logging.debug('Training started') while step_num < num_train_steps: for _, dataloader in enumerate(data_train): if step_num >= num_train_steps: break # create dummy data loader if needed if args.dummy_data_len: target_shape = (args.batch_size, args.dummy_data_len) dataloader = get_dummy_dataloader(dataloader, target_shape) for _, data_batch in enumerate(dataloader): if step_num >= num_train_steps: break if batch_num % accumulate == 0: step_num += 1 # if accumulate > 1, grad_req is set to 'add', and zero_grad is required if accumulate > 1: param_dict.zero_grad() # update learning rate if step_num <= num_warmup_steps: new_lr = lr * step_num / num_warmup_steps else: offset = lr * step_num / num_train_steps new_lr = lr - offset trainer.set_learning_rate(new_lr) if args.profile: profile(step_num, 10, 14, profile_name=args.profile + str(rank)) # load data if args.use_avg_len: data_list = [[seq.as_in_context(context) for seq in shard] for context, shard in zip([ctx], data_batch)] else: data_list = list(split_and_load(data_batch, [ctx])) data = data_list[0] # forward with mx.autograd.record(): (ls, ns_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_len) = forward(data, model, mlm_loss, nsp_loss, vocab_size, args.dtype) ls = ls / accumulate # backward if args.dtype == 'float16': fp16_trainer.backward(ls) else: ls.backward() running_mlm_loss += ls1.as_in_context(mx.cpu()) running_nsp_loss += ls2.as_in_context(mx.cpu()) running_num_tks += valid_len.sum().as_in_context(mx.cpu()) # update if (batch_num + 1) % accumulate == 0: # step() performs 3 things: # 1. allreduce gradients from all workers # 2. checking the global_norm of gradients and clip them if necessary # 3. averaging the gradients and apply updates fp16_trainer.step(1, max_norm=1*num_workers) nsp_metric.update([ns_label], [classified]) mlm_metric.update([masked_id], [decoded], [masked_weight]) # logging if (step_num + 1) % (args.log_interval) == 0 and (batch_num + 1) % accumulate == 0: log(begin_time, running_num_tks, running_mlm_loss / accumulate, running_nsp_loss / accumulate, step_num, mlm_metric, nsp_metric, trainer, args.log_interval) begin_time = time.time() running_mlm_loss = running_nsp_loss = running_num_tks = 0 mlm_metric.reset_local() nsp_metric.reset_local() # saving checkpoints if args.ckpt_dir and (step_num + 1) % (args.ckpt_interval) == 0 \ and (batch_num + 1) % accumulate == 0 and local_rank == 0: save_params(step_num, model, trainer, args.ckpt_dir) batch_num += 1 if local_rank == 0: save_params(step_num, model, trainer, args.ckpt_dir) mx.nd.waitall() train_end_time = time.time() logging.info('Train cost={:.1f}s'.format(train_end_time - train_begin_time))
[ "def", "train", "(", "data_train", ",", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocab_size", ",", "ctx", ")", ":", "hvd", ".", "broadcast_parameters", "(", "model", ".", "collect_params", "(", ")", ",", "root_rank", "=", "0", ")", "mlm_metric", "=", "nlp", ".", "metric", ".", "MaskedAccuracy", "(", ")", "nsp_metric", "=", "nlp", ".", "metric", ".", "MaskedAccuracy", "(", ")", "mlm_metric", ".", "reset", "(", ")", "nsp_metric", ".", "reset", "(", ")", "logging", ".", "debug", "(", "'Creating distributed trainer...'", ")", "lr", "=", "args", ".", "lr", "optim_params", "=", "{", "'learning_rate'", ":", "lr", ",", "'epsilon'", ":", "1e-6", ",", "'wd'", ":", "0.01", "}", "if", "args", ".", "dtype", "==", "'float16'", ":", "optim_params", "[", "'multi_precision'", "]", "=", "True", "dynamic_loss_scale", "=", "args", ".", "dtype", "==", "'float16'", "if", "dynamic_loss_scale", ":", "loss_scale_param", "=", "{", "'scale_window'", ":", "2000", "/", "num_workers", "}", "else", ":", "loss_scale_param", "=", "None", "trainer", "=", "hvd", ".", "DistributedTrainer", "(", "model", ".", "collect_params", "(", ")", ",", "'bertadam'", ",", "optim_params", ")", "fp16_trainer", "=", "FP16Trainer", "(", "trainer", ",", "dynamic_loss_scale", "=", "dynamic_loss_scale", ",", "loss_scaler_params", "=", "loss_scale_param", ")", "if", "args", ".", "ckpt_dir", "and", "args", ".", "start_step", ":", "trainer", ".", "load_states", "(", "os", ".", "path", ".", "join", "(", "args", ".", "ckpt_dir", ",", "'%07d.states'", "%", "args", ".", "start_step", ")", ")", "accumulate", "=", "args", ".", "accumulate", "num_train_steps", "=", "args", ".", "num_steps", "warmup_ratio", "=", "args", ".", "warmup_ratio", "num_warmup_steps", "=", "int", "(", "num_train_steps", "*", "warmup_ratio", ")", "params", "=", "[", "p", "for", "p", "in", "model", ".", "collect_params", "(", ")", ".", "values", "(", ")", "if", "p", ".", "grad_req", "!=", "'null'", "]", "param_dict", "=", "model", ".", "collect_params", "(", ")", "# Do not apply weight decay on LayerNorm and bias terms", "for", "_", ",", "v", "in", "model", ".", "collect_params", "(", "'.*beta|.*gamma|.*bias'", ")", ".", "items", "(", ")", ":", "v", ".", "wd_mult", "=", "0.0", "if", "accumulate", ">", "1", ":", "for", "p", "in", "params", ":", "p", ".", "grad_req", "=", "'add'", "train_begin_time", "=", "time", ".", "time", "(", ")", "begin_time", "=", "time", ".", "time", "(", ")", "running_mlm_loss", ",", "running_nsp_loss", "=", "0", ",", "0", "running_num_tks", "=", "0", "batch_num", "=", "0", "step_num", "=", "args", ".", "start_step", "logging", ".", "debug", "(", "'Training started'", ")", "while", "step_num", "<", "num_train_steps", ":", "for", "_", ",", "dataloader", "in", "enumerate", "(", "data_train", ")", ":", "if", "step_num", ">=", "num_train_steps", ":", "break", "# create dummy data loader if needed", "if", "args", ".", "dummy_data_len", ":", "target_shape", "=", "(", "args", ".", "batch_size", ",", "args", ".", "dummy_data_len", ")", "dataloader", "=", "get_dummy_dataloader", "(", "dataloader", ",", "target_shape", ")", "for", "_", ",", "data_batch", "in", "enumerate", "(", "dataloader", ")", ":", "if", "step_num", ">=", "num_train_steps", ":", "break", "if", "batch_num", "%", "accumulate", "==", "0", ":", "step_num", "+=", "1", "# if accumulate > 1, grad_req is set to 'add', and zero_grad is required", "if", "accumulate", ">", "1", ":", "param_dict", ".", "zero_grad", "(", ")", "# update learning rate", "if", "step_num", "<=", "num_warmup_steps", ":", "new_lr", "=", "lr", "*", "step_num", "/", "num_warmup_steps", "else", ":", "offset", "=", "lr", "*", "step_num", "/", "num_train_steps", "new_lr", "=", "lr", "-", "offset", "trainer", ".", "set_learning_rate", "(", "new_lr", ")", "if", "args", ".", "profile", ":", "profile", "(", "step_num", ",", "10", ",", "14", ",", "profile_name", "=", "args", ".", "profile", "+", "str", "(", "rank", ")", ")", "# load data", "if", "args", ".", "use_avg_len", ":", "data_list", "=", "[", "[", "seq", ".", "as_in_context", "(", "context", ")", "for", "seq", "in", "shard", "]", "for", "context", ",", "shard", "in", "zip", "(", "[", "ctx", "]", ",", "data_batch", ")", "]", "else", ":", "data_list", "=", "list", "(", "split_and_load", "(", "data_batch", ",", "[", "ctx", "]", ")", ")", "data", "=", "data_list", "[", "0", "]", "# forward", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "(", "ls", ",", "ns_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", "ls2", ",", "valid_len", ")", "=", "forward", "(", "data", ",", "model", ",", "mlm_loss", ",", "nsp_loss", ",", "vocab_size", ",", "args", ".", "dtype", ")", "ls", "=", "ls", "/", "accumulate", "# backward", "if", "args", ".", "dtype", "==", "'float16'", ":", "fp16_trainer", ".", "backward", "(", "ls", ")", "else", ":", "ls", ".", "backward", "(", ")", "running_mlm_loss", "+=", "ls1", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "running_nsp_loss", "+=", "ls2", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "running_num_tks", "+=", "valid_len", ".", "sum", "(", ")", ".", "as_in_context", "(", "mx", ".", "cpu", "(", ")", ")", "# update", "if", "(", "batch_num", "+", "1", ")", "%", "accumulate", "==", "0", ":", "# step() performs 3 things:", "# 1. allreduce gradients from all workers", "# 2. checking the global_norm of gradients and clip them if necessary", "# 3. averaging the gradients and apply updates", "fp16_trainer", ".", "step", "(", "1", ",", "max_norm", "=", "1", "*", "num_workers", ")", "nsp_metric", ".", "update", "(", "[", "ns_label", "]", ",", "[", "classified", "]", ")", "mlm_metric", ".", "update", "(", "[", "masked_id", "]", ",", "[", "decoded", "]", ",", "[", "masked_weight", "]", ")", "# logging", "if", "(", "step_num", "+", "1", ")", "%", "(", "args", ".", "log_interval", ")", "==", "0", "and", "(", "batch_num", "+", "1", ")", "%", "accumulate", "==", "0", ":", "log", "(", "begin_time", ",", "running_num_tks", ",", "running_mlm_loss", "/", "accumulate", ",", "running_nsp_loss", "/", "accumulate", ",", "step_num", ",", "mlm_metric", ",", "nsp_metric", ",", "trainer", ",", "args", ".", "log_interval", ")", "begin_time", "=", "time", ".", "time", "(", ")", "running_mlm_loss", "=", "running_nsp_loss", "=", "running_num_tks", "=", "0", "mlm_metric", ".", "reset_local", "(", ")", "nsp_metric", ".", "reset_local", "(", ")", "# saving checkpoints", "if", "args", ".", "ckpt_dir", "and", "(", "step_num", "+", "1", ")", "%", "(", "args", ".", "ckpt_interval", ")", "==", "0", "and", "(", "batch_num", "+", "1", ")", "%", "accumulate", "==", "0", "and", "local_rank", "==", "0", ":", "save_params", "(", "step_num", ",", "model", ",", "trainer", ",", "args", ".", "ckpt_dir", ")", "batch_num", "+=", "1", "if", "local_rank", "==", "0", ":", "save_params", "(", "step_num", ",", "model", ",", "trainer", ",", "args", ".", "ckpt_dir", ")", "mx", ".", "nd", ".", "waitall", "(", ")", "train_end_time", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'Train cost={:.1f}s'", ".", "format", "(", "train_end_time", "-", "train_begin_time", ")", ")" ]
Training function.
[ "Training", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining_hvd.py#L71-L204
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_finetune_squad.py
train
def train(): """Training function.""" log.info('Loader Train data...') if version_2: train_data = SQuAD('train', version='2.0') else: train_data = SQuAD('train', version='1.1') log.info('Number of records in Train data:{}'.format(len(train_data))) train_data_transform, _ = preprocess_dataset( train_data, SQuADTransform( berttoken, max_seq_length=max_seq_length, doc_stride=doc_stride, max_query_length=max_query_length, is_pad=True, is_training=True)) log.info('The number of examples after preprocessing:{}'.format( len(train_data_transform))) train_dataloader = mx.gluon.data.DataLoader( train_data_transform, batchify_fn=batchify_fn, batch_size=batch_size, num_workers=4, shuffle=True) log.info('Start Training') optimizer_params = {'learning_rate': lr} try: trainer = gluon.Trainer(net.collect_params(), optimizer, optimizer_params, update_on_kvstore=False) except ValueError as e: print(e) warnings.warn('AdamW optimizer is not found. Please consider upgrading to ' 'mxnet>=1.5.0. Now the original Adam optimizer is used instead.') trainer = gluon.Trainer(net.collect_params(), 'adam', optimizer_params, update_on_kvstore=False) num_train_examples = len(train_data_transform) step_size = batch_size * accumulate if accumulate else batch_size num_train_steps = int(num_train_examples / step_size * epochs) num_warmup_steps = int(num_train_steps * warmup_ratio) step_num = 0 def set_new_lr(step_num, batch_id): """set new learning rate""" # set grad to zero for gradient accumulation if accumulate: if batch_id % accumulate == 0: net.collect_params().zero_grad() step_num += 1 else: step_num += 1 # learning rate schedule # Notice that this learning rate scheduler is adapted from traditional linear learning # rate scheduler where step_num >= num_warmup_steps, new_lr = 1 - step_num/num_train_steps if step_num < num_warmup_steps: new_lr = lr * step_num / num_warmup_steps else: offset = (step_num - num_warmup_steps) * lr / \ (num_train_steps - num_warmup_steps) new_lr = lr - offset trainer.set_learning_rate(new_lr) return step_num # Do not apply weight decay on LayerNorm and bias terms for _, v in net.collect_params('.*beta|.*gamma|.*bias').items(): v.wd_mult = 0.0 # Collect differentiable parameters params = [p for p in net.collect_params().values() if p.grad_req != 'null'] # Set grad_req if gradient accumulation is required if accumulate: for p in params: p.grad_req = 'add' epoch_tic = time.time() total_num = 0 log_num = 0 for epoch_id in range(epochs): step_loss = 0.0 tic = time.time() for batch_id, data in enumerate(train_dataloader): # set new lr step_num = set_new_lr(step_num, batch_id) # forward and backward with mx.autograd.record(): _, inputs, token_types, valid_length, start_label, end_label = data log_num += len(inputs) total_num += len(inputs) 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)) ls = loss_function(out, [ start_label.astype('float32').as_in_context(ctx), end_label.astype('float32').as_in_context(ctx)]).mean() if accumulate: ls = ls / accumulate ls.backward() # update if not accumulate or (batch_id + 1) % accumulate == 0: trainer.allreduce_grads() nlp.utils.clip_grad_global_norm(params, 1) trainer.update(1) step_loss += ls.asscalar() if (batch_id + 1) % log_interval == 0: toc = time.time() log.info( 'Epoch: {}, Batch: {}/{}, Loss={:.4f}, lr={:.7f} Time cost={:.1f} Thoughput={:.2f} samples/s' # pylint: disable=line-too-long .format(epoch_id, batch_id, len(train_dataloader), step_loss / log_interval, trainer.learning_rate, toc - tic, log_num / (toc - tic))) tic = time.time() step_loss = 0.0 log_num = 0 epoch_toc = time.time() log.info('Epoch: {}, Time cost={:.2f} s, Thoughput={:.2f} samples/s' .format(epoch_id, epoch_toc - epoch_tic, len(train_dataloader) / (epoch_toc - epoch_tic))) net.save_parameters(os.path.join(output_dir, 'net.params'))
python
def train(): """Training function.""" log.info('Loader Train data...') if version_2: train_data = SQuAD('train', version='2.0') else: train_data = SQuAD('train', version='1.1') log.info('Number of records in Train data:{}'.format(len(train_data))) train_data_transform, _ = preprocess_dataset( train_data, SQuADTransform( berttoken, max_seq_length=max_seq_length, doc_stride=doc_stride, max_query_length=max_query_length, is_pad=True, is_training=True)) log.info('The number of examples after preprocessing:{}'.format( len(train_data_transform))) train_dataloader = mx.gluon.data.DataLoader( train_data_transform, batchify_fn=batchify_fn, batch_size=batch_size, num_workers=4, shuffle=True) log.info('Start Training') optimizer_params = {'learning_rate': lr} try: trainer = gluon.Trainer(net.collect_params(), optimizer, optimizer_params, update_on_kvstore=False) except ValueError as e: print(e) warnings.warn('AdamW optimizer is not found. Please consider upgrading to ' 'mxnet>=1.5.0. Now the original Adam optimizer is used instead.') trainer = gluon.Trainer(net.collect_params(), 'adam', optimizer_params, update_on_kvstore=False) num_train_examples = len(train_data_transform) step_size = batch_size * accumulate if accumulate else batch_size num_train_steps = int(num_train_examples / step_size * epochs) num_warmup_steps = int(num_train_steps * warmup_ratio) step_num = 0 def set_new_lr(step_num, batch_id): """set new learning rate""" # set grad to zero for gradient accumulation if accumulate: if batch_id % accumulate == 0: net.collect_params().zero_grad() step_num += 1 else: step_num += 1 # learning rate schedule # Notice that this learning rate scheduler is adapted from traditional linear learning # rate scheduler where step_num >= num_warmup_steps, new_lr = 1 - step_num/num_train_steps if step_num < num_warmup_steps: new_lr = lr * step_num / num_warmup_steps else: offset = (step_num - num_warmup_steps) * lr / \ (num_train_steps - num_warmup_steps) new_lr = lr - offset trainer.set_learning_rate(new_lr) return step_num # Do not apply weight decay on LayerNorm and bias terms for _, v in net.collect_params('.*beta|.*gamma|.*bias').items(): v.wd_mult = 0.0 # Collect differentiable parameters params = [p for p in net.collect_params().values() if p.grad_req != 'null'] # Set grad_req if gradient accumulation is required if accumulate: for p in params: p.grad_req = 'add' epoch_tic = time.time() total_num = 0 log_num = 0 for epoch_id in range(epochs): step_loss = 0.0 tic = time.time() for batch_id, data in enumerate(train_dataloader): # set new lr step_num = set_new_lr(step_num, batch_id) # forward and backward with mx.autograd.record(): _, inputs, token_types, valid_length, start_label, end_label = data log_num += len(inputs) total_num += len(inputs) 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)) ls = loss_function(out, [ start_label.astype('float32').as_in_context(ctx), end_label.astype('float32').as_in_context(ctx)]).mean() if accumulate: ls = ls / accumulate ls.backward() # update if not accumulate or (batch_id + 1) % accumulate == 0: trainer.allreduce_grads() nlp.utils.clip_grad_global_norm(params, 1) trainer.update(1) step_loss += ls.asscalar() if (batch_id + 1) % log_interval == 0: toc = time.time() log.info( 'Epoch: {}, Batch: {}/{}, Loss={:.4f}, lr={:.7f} Time cost={:.1f} Thoughput={:.2f} samples/s' # pylint: disable=line-too-long .format(epoch_id, batch_id, len(train_dataloader), step_loss / log_interval, trainer.learning_rate, toc - tic, log_num / (toc - tic))) tic = time.time() step_loss = 0.0 log_num = 0 epoch_toc = time.time() log.info('Epoch: {}, Time cost={:.2f} s, Thoughput={:.2f} samples/s' .format(epoch_id, epoch_toc - epoch_tic, len(train_dataloader) / (epoch_toc - epoch_tic))) net.save_parameters(os.path.join(output_dir, 'net.params'))
[ "def", "train", "(", ")", ":", "log", ".", "info", "(", "'Loader Train data...'", ")", "if", "version_2", ":", "train_data", "=", "SQuAD", "(", "'train'", ",", "version", "=", "'2.0'", ")", "else", ":", "train_data", "=", "SQuAD", "(", "'train'", ",", "version", "=", "'1.1'", ")", "log", ".", "info", "(", "'Number of records in Train data:{}'", ".", "format", "(", "len", "(", "train_data", ")", ")", ")", "train_data_transform", ",", "_", "=", "preprocess_dataset", "(", "train_data", ",", "SQuADTransform", "(", "berttoken", ",", "max_seq_length", "=", "max_seq_length", ",", "doc_stride", "=", "doc_stride", ",", "max_query_length", "=", "max_query_length", ",", "is_pad", "=", "True", ",", "is_training", "=", "True", ")", ")", "log", ".", "info", "(", "'The number of examples after preprocessing:{}'", ".", "format", "(", "len", "(", "train_data_transform", ")", ")", ")", "train_dataloader", "=", "mx", ".", "gluon", ".", "data", ".", "DataLoader", "(", "train_data_transform", ",", "batchify_fn", "=", "batchify_fn", ",", "batch_size", "=", "batch_size", ",", "num_workers", "=", "4", ",", "shuffle", "=", "True", ")", "log", ".", "info", "(", "'Start Training'", ")", "optimizer_params", "=", "{", "'learning_rate'", ":", "lr", "}", "try", ":", "trainer", "=", "gluon", ".", "Trainer", "(", "net", ".", "collect_params", "(", ")", ",", "optimizer", ",", "optimizer_params", ",", "update_on_kvstore", "=", "False", ")", "except", "ValueError", "as", "e", ":", "print", "(", "e", ")", "warnings", ".", "warn", "(", "'AdamW optimizer is not found. Please consider upgrading to '", "'mxnet>=1.5.0. Now the original Adam optimizer is used instead.'", ")", "trainer", "=", "gluon", ".", "Trainer", "(", "net", ".", "collect_params", "(", ")", ",", "'adam'", ",", "optimizer_params", ",", "update_on_kvstore", "=", "False", ")", "num_train_examples", "=", "len", "(", "train_data_transform", ")", "step_size", "=", "batch_size", "*", "accumulate", "if", "accumulate", "else", "batch_size", "num_train_steps", "=", "int", "(", "num_train_examples", "/", "step_size", "*", "epochs", ")", "num_warmup_steps", "=", "int", "(", "num_train_steps", "*", "warmup_ratio", ")", "step_num", "=", "0", "def", "set_new_lr", "(", "step_num", ",", "batch_id", ")", ":", "\"\"\"set new learning rate\"\"\"", "# set grad to zero for gradient accumulation", "if", "accumulate", ":", "if", "batch_id", "%", "accumulate", "==", "0", ":", "net", ".", "collect_params", "(", ")", ".", "zero_grad", "(", ")", "step_num", "+=", "1", "else", ":", "step_num", "+=", "1", "# learning rate schedule", "# Notice that this learning rate scheduler is adapted from traditional linear learning", "# rate scheduler where step_num >= num_warmup_steps, new_lr = 1 - step_num/num_train_steps", "if", "step_num", "<", "num_warmup_steps", ":", "new_lr", "=", "lr", "*", "step_num", "/", "num_warmup_steps", "else", ":", "offset", "=", "(", "step_num", "-", "num_warmup_steps", ")", "*", "lr", "/", "(", "num_train_steps", "-", "num_warmup_steps", ")", "new_lr", "=", "lr", "-", "offset", "trainer", ".", "set_learning_rate", "(", "new_lr", ")", "return", "step_num", "# Do not apply weight decay on LayerNorm and bias terms", "for", "_", ",", "v", "in", "net", ".", "collect_params", "(", "'.*beta|.*gamma|.*bias'", ")", ".", "items", "(", ")", ":", "v", ".", "wd_mult", "=", "0.0", "# Collect differentiable parameters", "params", "=", "[", "p", "for", "p", "in", "net", ".", "collect_params", "(", ")", ".", "values", "(", ")", "if", "p", ".", "grad_req", "!=", "'null'", "]", "# Set grad_req if gradient accumulation is required", "if", "accumulate", ":", "for", "p", "in", "params", ":", "p", ".", "grad_req", "=", "'add'", "epoch_tic", "=", "time", ".", "time", "(", ")", "total_num", "=", "0", "log_num", "=", "0", "for", "epoch_id", "in", "range", "(", "epochs", ")", ":", "step_loss", "=", "0.0", "tic", "=", "time", ".", "time", "(", ")", "for", "batch_id", ",", "data", "in", "enumerate", "(", "train_dataloader", ")", ":", "# set new lr", "step_num", "=", "set_new_lr", "(", "step_num", ",", "batch_id", ")", "# forward and backward", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "_", ",", "inputs", ",", "token_types", ",", "valid_length", ",", "start_label", ",", "end_label", "=", "data", "log_num", "+=", "len", "(", "inputs", ")", "total_num", "+=", "len", "(", "inputs", ")", "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", ")", ")", "ls", "=", "loss_function", "(", "out", ",", "[", "start_label", ".", "astype", "(", "'float32'", ")", ".", "as_in_context", "(", "ctx", ")", ",", "end_label", ".", "astype", "(", "'float32'", ")", ".", "as_in_context", "(", "ctx", ")", "]", ")", ".", "mean", "(", ")", "if", "accumulate", ":", "ls", "=", "ls", "/", "accumulate", "ls", ".", "backward", "(", ")", "# update", "if", "not", "accumulate", "or", "(", "batch_id", "+", "1", ")", "%", "accumulate", "==", "0", ":", "trainer", ".", "allreduce_grads", "(", ")", "nlp", ".", "utils", ".", "clip_grad_global_norm", "(", "params", ",", "1", ")", "trainer", ".", "update", "(", "1", ")", "step_loss", "+=", "ls", ".", "asscalar", "(", ")", "if", "(", "batch_id", "+", "1", ")", "%", "log_interval", "==", "0", ":", "toc", "=", "time", ".", "time", "(", ")", "log", ".", "info", "(", "'Epoch: {}, Batch: {}/{}, Loss={:.4f}, lr={:.7f} Time cost={:.1f} Thoughput={:.2f} samples/s'", "# pylint: disable=line-too-long", ".", "format", "(", "epoch_id", ",", "batch_id", ",", "len", "(", "train_dataloader", ")", ",", "step_loss", "/", "log_interval", ",", "trainer", ".", "learning_rate", ",", "toc", "-", "tic", ",", "log_num", "/", "(", "toc", "-", "tic", ")", ")", ")", "tic", "=", "time", ".", "time", "(", ")", "step_loss", "=", "0.0", "log_num", "=", "0", "epoch_toc", "=", "time", ".", "time", "(", ")", "log", ".", "info", "(", "'Epoch: {}, Time cost={:.2f} s, Thoughput={:.2f} samples/s'", ".", "format", "(", "epoch_id", ",", "epoch_toc", "-", "epoch_tic", ",", "len", "(", "train_dataloader", ")", "/", "(", "epoch_toc", "-", "epoch_tic", ")", ")", ")", "net", ".", "save_parameters", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'net.params'", ")", ")" ]
Training function.
[ "Training", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_finetune_squad.py#L301-L426
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_finetune_squad.py
evaluate
def evaluate(): """Evaluate the model on validation dataset. """ log.info('Loader dev data...') if version_2: dev_data = SQuAD('dev', version='2.0') else: dev_data = SQuAD('dev', version='1.1') log.info('Number of records in Train data:{}'.format(len(dev_data))) dev_dataset = dev_data.transform( SQuADTransform( berttoken, max_seq_length=max_seq_length, doc_stride=doc_stride, max_query_length=max_query_length, is_pad=True, is_training=False)._transform) dev_data_transform, _ = preprocess_dataset( dev_data, SQuADTransform( berttoken, max_seq_length=max_seq_length, doc_stride=doc_stride, max_query_length=max_query_length, is_pad=True, is_training=False)) log.info('The number of examples after preprocessing:{}'.format( len(dev_data_transform))) dev_dataloader = mx.gluon.data.DataLoader( dev_data_transform, batchify_fn=batchify_fn, num_workers=4, batch_size=test_batch_size, shuffle=False, last_batch='keep') log.info('Start predict') _Result = collections.namedtuple( '_Result', ['example_id', 'start_logits', 'end_logits']) all_results = {} epoch_tic = time.time() total_num = 0 for data in dev_dataloader: example_ids, inputs, token_types, valid_length, _, _ = data total_num += len(inputs) 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)) output = nd.split(out, axis=2, num_outputs=2) start_logits = output[0].reshape((0, -3)).asnumpy() end_logits = output[1].reshape((0, -3)).asnumpy() for example_id, start, end in zip(example_ids, start_logits, end_logits): example_id = example_id.asscalar() if example_id not in all_results: all_results[example_id] = [] all_results[example_id].append( _Result(example_id, start.tolist(), end.tolist())) epoch_toc = time.time() log.info('Inference time cost={:.2f} s, Thoughput={:.2f} samples/s' .format(epoch_toc - epoch_tic, len(dev_dataloader) / (epoch_toc - epoch_tic))) log.info('Get prediction results...') all_predictions, all_nbest_json, scores_diff_json = predictions( dev_dataset=dev_dataset, all_results=all_results, tokenizer=nlp.data.BERTBasicTokenizer(lower=lower), max_answer_length=max_answer_length, null_score_diff_threshold=null_score_diff_threshold, n_best_size=n_best_size, version_2=version_2) with open(os.path.join(output_dir, 'predictions.json'), 'w', encoding='utf-8') as all_predictions_write: all_predictions_write.write(json.dumps(all_predictions)) with open(os.path.join(output_dir, 'nbest_predictions.json'), 'w', encoding='utf-8') as all_predictions_write: all_predictions_write.write(json.dumps(all_nbest_json)) if version_2: with open(os.path.join(output_dir, 'null_odds.json'), 'w', encoding='utf-8') as all_predictions_write: all_predictions_write.write(json.dumps(scores_diff_json)) else: log.info(get_F1_EM(dev_data, all_predictions))
python
def evaluate(): """Evaluate the model on validation dataset. """ log.info('Loader dev data...') if version_2: dev_data = SQuAD('dev', version='2.0') else: dev_data = SQuAD('dev', version='1.1') log.info('Number of records in Train data:{}'.format(len(dev_data))) dev_dataset = dev_data.transform( SQuADTransform( berttoken, max_seq_length=max_seq_length, doc_stride=doc_stride, max_query_length=max_query_length, is_pad=True, is_training=False)._transform) dev_data_transform, _ = preprocess_dataset( dev_data, SQuADTransform( berttoken, max_seq_length=max_seq_length, doc_stride=doc_stride, max_query_length=max_query_length, is_pad=True, is_training=False)) log.info('The number of examples after preprocessing:{}'.format( len(dev_data_transform))) dev_dataloader = mx.gluon.data.DataLoader( dev_data_transform, batchify_fn=batchify_fn, num_workers=4, batch_size=test_batch_size, shuffle=False, last_batch='keep') log.info('Start predict') _Result = collections.namedtuple( '_Result', ['example_id', 'start_logits', 'end_logits']) all_results = {} epoch_tic = time.time() total_num = 0 for data in dev_dataloader: example_ids, inputs, token_types, valid_length, _, _ = data total_num += len(inputs) 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)) output = nd.split(out, axis=2, num_outputs=2) start_logits = output[0].reshape((0, -3)).asnumpy() end_logits = output[1].reshape((0, -3)).asnumpy() for example_id, start, end in zip(example_ids, start_logits, end_logits): example_id = example_id.asscalar() if example_id not in all_results: all_results[example_id] = [] all_results[example_id].append( _Result(example_id, start.tolist(), end.tolist())) epoch_toc = time.time() log.info('Inference time cost={:.2f} s, Thoughput={:.2f} samples/s' .format(epoch_toc - epoch_tic, len(dev_dataloader) / (epoch_toc - epoch_tic))) log.info('Get prediction results...') all_predictions, all_nbest_json, scores_diff_json = predictions( dev_dataset=dev_dataset, all_results=all_results, tokenizer=nlp.data.BERTBasicTokenizer(lower=lower), max_answer_length=max_answer_length, null_score_diff_threshold=null_score_diff_threshold, n_best_size=n_best_size, version_2=version_2) with open(os.path.join(output_dir, 'predictions.json'), 'w', encoding='utf-8') as all_predictions_write: all_predictions_write.write(json.dumps(all_predictions)) with open(os.path.join(output_dir, 'nbest_predictions.json'), 'w', encoding='utf-8') as all_predictions_write: all_predictions_write.write(json.dumps(all_nbest_json)) if version_2: with open(os.path.join(output_dir, 'null_odds.json'), 'w', encoding='utf-8') as all_predictions_write: all_predictions_write.write(json.dumps(scores_diff_json)) else: log.info(get_F1_EM(dev_data, all_predictions))
[ "def", "evaluate", "(", ")", ":", "log", ".", "info", "(", "'Loader dev data...'", ")", "if", "version_2", ":", "dev_data", "=", "SQuAD", "(", "'dev'", ",", "version", "=", "'2.0'", ")", "else", ":", "dev_data", "=", "SQuAD", "(", "'dev'", ",", "version", "=", "'1.1'", ")", "log", ".", "info", "(", "'Number of records in Train data:{}'", ".", "format", "(", "len", "(", "dev_data", ")", ")", ")", "dev_dataset", "=", "dev_data", ".", "transform", "(", "SQuADTransform", "(", "berttoken", ",", "max_seq_length", "=", "max_seq_length", ",", "doc_stride", "=", "doc_stride", ",", "max_query_length", "=", "max_query_length", ",", "is_pad", "=", "True", ",", "is_training", "=", "False", ")", ".", "_transform", ")", "dev_data_transform", ",", "_", "=", "preprocess_dataset", "(", "dev_data", ",", "SQuADTransform", "(", "berttoken", ",", "max_seq_length", "=", "max_seq_length", ",", "doc_stride", "=", "doc_stride", ",", "max_query_length", "=", "max_query_length", ",", "is_pad", "=", "True", ",", "is_training", "=", "False", ")", ")", "log", ".", "info", "(", "'The number of examples after preprocessing:{}'", ".", "format", "(", "len", "(", "dev_data_transform", ")", ")", ")", "dev_dataloader", "=", "mx", ".", "gluon", ".", "data", ".", "DataLoader", "(", "dev_data_transform", ",", "batchify_fn", "=", "batchify_fn", ",", "num_workers", "=", "4", ",", "batch_size", "=", "test_batch_size", ",", "shuffle", "=", "False", ",", "last_batch", "=", "'keep'", ")", "log", ".", "info", "(", "'Start predict'", ")", "_Result", "=", "collections", ".", "namedtuple", "(", "'_Result'", ",", "[", "'example_id'", ",", "'start_logits'", ",", "'end_logits'", "]", ")", "all_results", "=", "{", "}", "epoch_tic", "=", "time", ".", "time", "(", ")", "total_num", "=", "0", "for", "data", "in", "dev_dataloader", ":", "example_ids", ",", "inputs", ",", "token_types", ",", "valid_length", ",", "_", ",", "_", "=", "data", "total_num", "+=", "len", "(", "inputs", ")", "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", ")", ")", "output", "=", "nd", ".", "split", "(", "out", ",", "axis", "=", "2", ",", "num_outputs", "=", "2", ")", "start_logits", "=", "output", "[", "0", "]", ".", "reshape", "(", "(", "0", ",", "-", "3", ")", ")", ".", "asnumpy", "(", ")", "end_logits", "=", "output", "[", "1", "]", ".", "reshape", "(", "(", "0", ",", "-", "3", ")", ")", ".", "asnumpy", "(", ")", "for", "example_id", ",", "start", ",", "end", "in", "zip", "(", "example_ids", ",", "start_logits", ",", "end_logits", ")", ":", "example_id", "=", "example_id", ".", "asscalar", "(", ")", "if", "example_id", "not", "in", "all_results", ":", "all_results", "[", "example_id", "]", "=", "[", "]", "all_results", "[", "example_id", "]", ".", "append", "(", "_Result", "(", "example_id", ",", "start", ".", "tolist", "(", ")", ",", "end", ".", "tolist", "(", ")", ")", ")", "epoch_toc", "=", "time", ".", "time", "(", ")", "log", ".", "info", "(", "'Inference time cost={:.2f} s, Thoughput={:.2f} samples/s'", ".", "format", "(", "epoch_toc", "-", "epoch_tic", ",", "len", "(", "dev_dataloader", ")", "/", "(", "epoch_toc", "-", "epoch_tic", ")", ")", ")", "log", ".", "info", "(", "'Get prediction results...'", ")", "all_predictions", ",", "all_nbest_json", ",", "scores_diff_json", "=", "predictions", "(", "dev_dataset", "=", "dev_dataset", ",", "all_results", "=", "all_results", ",", "tokenizer", "=", "nlp", ".", "data", ".", "BERTBasicTokenizer", "(", "lower", "=", "lower", ")", ",", "max_answer_length", "=", "max_answer_length", ",", "null_score_diff_threshold", "=", "null_score_diff_threshold", ",", "n_best_size", "=", "n_best_size", ",", "version_2", "=", "version_2", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'predictions.json'", ")", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "all_predictions_write", ":", "all_predictions_write", ".", "write", "(", "json", ".", "dumps", "(", "all_predictions", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'nbest_predictions.json'", ")", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "all_predictions_write", ":", "all_predictions_write", ".", "write", "(", "json", ".", "dumps", "(", "all_nbest_json", ")", ")", "if", "version_2", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'null_odds.json'", ")", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "all_predictions_write", ":", "all_predictions_write", ".", "write", "(", "json", ".", "dumps", "(", "scores_diff_json", ")", ")", "else", ":", "log", ".", "info", "(", "get_F1_EM", "(", "dev_data", ",", "all_predictions", ")", ")" ]
Evaluate the model on validation dataset.
[ "Evaluate", "the", "model", "on", "validation", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_finetune_squad.py#L429-L517
train
dmlc/gluon-nlp
src/gluonnlp/data/batchify/batchify.py
_pad_arrs_to_max_length
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : NDArray """ if isinstance(arrs[0], mx.nd.NDArray): dtype = arrs[0].dtype if dtype is None else dtype arrs = [arr.asnumpy() for arr in arrs] elif not isinstance(arrs[0], np.ndarray): arrs = [np.asarray(ele) for ele in arrs] else: dtype = arrs[0].dtype if dtype is None else dtype original_length = [ele.shape[pad_axis] for ele in arrs] max_size = max(original_length) ret_shape = list(arrs[0].shape) ret_shape[pad_axis] = max_size ret_shape = (len(arrs), ) + tuple(ret_shape) ret = np.full(shape=ret_shape, fill_value=pad_val, dtype=dtype) for i, arr in enumerate(arrs): if arr.shape[pad_axis] == max_size: ret[i] = arr else: slices = [slice(None) for _ in range(arr.ndim)] slices[pad_axis] = slice(0, arr.shape[pad_axis]) if slices[pad_axis].start != slices[pad_axis].stop: slices = [slice(i, i + 1)] + slices ret[tuple(slices)] = arr ctx = mx.Context('cpu_shared', 0) if use_shared_mem else mx.cpu() ret = mx.nd.array(ret, ctx=ctx, dtype=dtype) original_length = mx.nd.array(original_length, ctx=ctx, dtype=np.int32) return ret, original_length
python
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : NDArray """ if isinstance(arrs[0], mx.nd.NDArray): dtype = arrs[0].dtype if dtype is None else dtype arrs = [arr.asnumpy() for arr in arrs] elif not isinstance(arrs[0], np.ndarray): arrs = [np.asarray(ele) for ele in arrs] else: dtype = arrs[0].dtype if dtype is None else dtype original_length = [ele.shape[pad_axis] for ele in arrs] max_size = max(original_length) ret_shape = list(arrs[0].shape) ret_shape[pad_axis] = max_size ret_shape = (len(arrs), ) + tuple(ret_shape) ret = np.full(shape=ret_shape, fill_value=pad_val, dtype=dtype) for i, arr in enumerate(arrs): if arr.shape[pad_axis] == max_size: ret[i] = arr else: slices = [slice(None) for _ in range(arr.ndim)] slices[pad_axis] = slice(0, arr.shape[pad_axis]) if slices[pad_axis].start != slices[pad_axis].stop: slices = [slice(i, i + 1)] + slices ret[tuple(slices)] = arr ctx = mx.Context('cpu_shared', 0) if use_shared_mem else mx.cpu() ret = mx.nd.array(ret, ctx=ctx, dtype=dtype) original_length = mx.nd.array(original_length, ctx=ctx, dtype=np.int32) return ret, original_length
[ "def", "_pad_arrs_to_max_length", "(", "arrs", ",", "pad_axis", ",", "pad_val", ",", "use_shared_mem", ",", "dtype", ")", ":", "if", "isinstance", "(", "arrs", "[", "0", "]", ",", "mx", ".", "nd", ".", "NDArray", ")", ":", "dtype", "=", "arrs", "[", "0", "]", ".", "dtype", "if", "dtype", "is", "None", "else", "dtype", "arrs", "=", "[", "arr", ".", "asnumpy", "(", ")", "for", "arr", "in", "arrs", "]", "elif", "not", "isinstance", "(", "arrs", "[", "0", "]", ",", "np", ".", "ndarray", ")", ":", "arrs", "=", "[", "np", ".", "asarray", "(", "ele", ")", "for", "ele", "in", "arrs", "]", "else", ":", "dtype", "=", "arrs", "[", "0", "]", ".", "dtype", "if", "dtype", "is", "None", "else", "dtype", "original_length", "=", "[", "ele", ".", "shape", "[", "pad_axis", "]", "for", "ele", "in", "arrs", "]", "max_size", "=", "max", "(", "original_length", ")", "ret_shape", "=", "list", "(", "arrs", "[", "0", "]", ".", "shape", ")", "ret_shape", "[", "pad_axis", "]", "=", "max_size", "ret_shape", "=", "(", "len", "(", "arrs", ")", ",", ")", "+", "tuple", "(", "ret_shape", ")", "ret", "=", "np", ".", "full", "(", "shape", "=", "ret_shape", ",", "fill_value", "=", "pad_val", ",", "dtype", "=", "dtype", ")", "for", "i", ",", "arr", "in", "enumerate", "(", "arrs", ")", ":", "if", "arr", ".", "shape", "[", "pad_axis", "]", "==", "max_size", ":", "ret", "[", "i", "]", "=", "arr", "else", ":", "slices", "=", "[", "slice", "(", "None", ")", "for", "_", "in", "range", "(", "arr", ".", "ndim", ")", "]", "slices", "[", "pad_axis", "]", "=", "slice", "(", "0", ",", "arr", ".", "shape", "[", "pad_axis", "]", ")", "if", "slices", "[", "pad_axis", "]", ".", "start", "!=", "slices", "[", "pad_axis", "]", ".", "stop", ":", "slices", "=", "[", "slice", "(", "i", ",", "i", "+", "1", ")", "]", "+", "slices", "ret", "[", "tuple", "(", "slices", ")", "]", "=", "arr", "ctx", "=", "mx", ".", "Context", "(", "'cpu_shared'", ",", "0", ")", "if", "use_shared_mem", "else", "mx", ".", "cpu", "(", ")", "ret", "=", "mx", ".", "nd", ".", "array", "(", "ret", ",", "ctx", "=", "ctx", ",", "dtype", "=", "dtype", ")", "original_length", "=", "mx", ".", "nd", ".", "array", "(", "original_length", ",", "ctx", "=", "ctx", ",", "dtype", "=", "np", ".", "int32", ")", "return", "ret", ",", "original_length" ]
Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : NDArray
[ "Inner", "Implementation", "of", "the", "Pad", "batchify" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/batchify/batchify.py#L29-L75
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.train
def train(self, train_file, dev_file, test_file, save_dir, pretrained_embeddings=None, min_occur_count=2, lstm_layers=3, word_dims=100, tag_dims=100, dropout_emb=0.33, lstm_hiddens=400, dropout_lstm_input=0.33, dropout_lstm_hidden=0.33, mlp_arc_size=500, mlp_rel_size=100, dropout_mlp=0.33, learning_rate=2e-3, decay=.75, decay_steps=5000, beta_1=.9, beta_2=.9, epsilon=1e-12, num_buckets_train=40, num_buckets_valid=10, num_buckets_test=10, train_iters=50000, train_batch_size=5000, test_batch_size=5000, validate_every=100, save_after=5000, debug=False): """Train a deep biaffine dependency parser Parameters ---------- train_file : str path to training set dev_file : str path to dev set test_file : str path to test set save_dir : str a directory for saving model and related meta-data pretrained_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) min_occur_count : int threshold of rare words, which will be replaced with UNKs, lstm_layers : int layers of lstm word_dims : int dimension of word embedding tag_dims : int dimension of tag embedding dropout_emb : float word dropout lstm_hiddens : int size of lstm hidden states dropout_lstm_input : int dropout on x in variational RNN dropout_lstm_hidden : int dropout on h in variational RNN mlp_arc_size : int output size of MLP for arc feature extraction mlp_rel_size : int output size of MLP for rel feature extraction dropout_mlp : float dropout on the output of LSTM learning_rate : float learning rate decay : float see ExponentialScheduler decay_steps : int see ExponentialScheduler beta_1 : float see ExponentialScheduler beta_2 : float see ExponentialScheduler epsilon : float see ExponentialScheduler num_buckets_train : int number of buckets for training data set num_buckets_valid : int number of buckets for dev data set num_buckets_test : int number of buckets for testing data set train_iters : int training iterations train_batch_size : int training batch size test_batch_size : int test batch size validate_every : int validate on dev set every such number of batches save_after : int skip saving model in early epochs debug : bool debug mode Returns ------- DepParser parser itself """ logger = init_logger(save_dir) config = _Config(train_file, dev_file, test_file, save_dir, pretrained_embeddings, min_occur_count, lstm_layers, word_dims, tag_dims, dropout_emb, lstm_hiddens, dropout_lstm_input, dropout_lstm_hidden, mlp_arc_size, mlp_rel_size, dropout_mlp, learning_rate, decay, decay_steps, beta_1, beta_2, epsilon, num_buckets_train, num_buckets_valid, num_buckets_test, train_iters, train_batch_size, debug) config.save() self._vocab = vocab = ParserVocabulary(train_file, pretrained_embeddings, min_occur_count) vocab.save(config.save_vocab_path) vocab.log_info(logger) with mx.Context(mxnet_prefer_gpu()): self._parser = parser = BiaffineParser(vocab, word_dims, tag_dims, dropout_emb, lstm_layers, lstm_hiddens, dropout_lstm_input, dropout_lstm_hidden, mlp_arc_size, mlp_rel_size, dropout_mlp, debug) parser.initialize() scheduler = ExponentialScheduler(learning_rate, decay, decay_steps) optimizer = mx.optimizer.Adam(learning_rate, beta_1, beta_2, epsilon, lr_scheduler=scheduler) trainer = gluon.Trainer(parser.collect_params(), optimizer=optimizer) data_loader = DataLoader(train_file, num_buckets_train, vocab) global_step = 0 best_UAS = 0. batch_id = 0 epoch = 1 total_epoch = math.ceil(train_iters / validate_every) logger.info("Epoch {} out of {}".format(epoch, total_epoch)) bar = Progbar(target=min(validate_every, data_loader.samples)) while global_step < train_iters: for words, tags, arcs, rels in data_loader.get_batches(batch_size=train_batch_size, shuffle=True): with autograd.record(): arc_accuracy, rel_accuracy, overall_accuracy, loss = parser.forward(words, tags, arcs, rels) loss_value = loss.asscalar() loss.backward() trainer.step(train_batch_size) batch_id += 1 try: bar.update(batch_id, exact=[("UAS", arc_accuracy, 2), # ("LAS", rel_accuracy, 2), # ("ALL", overall_accuracy, 2), ("loss", loss_value)]) except OverflowError: pass # sometimes loss can be 0 or infinity, crashes the bar global_step += 1 if global_step % validate_every == 0: bar = Progbar(target=min(validate_every, train_iters - global_step)) batch_id = 0 UAS, LAS, speed = evaluate_official_script(parser, vocab, num_buckets_valid, test_batch_size, dev_file, os.path.join(save_dir, 'valid_tmp')) logger.info('Dev: UAS %.2f%% LAS %.2f%% %d sents/s' % (UAS, LAS, speed)) epoch += 1 if global_step < train_iters: logger.info("Epoch {} out of {}".format(epoch, total_epoch)) if global_step > save_after and UAS > best_UAS: logger.info('- new best score!') best_UAS = UAS parser.save(config.save_model_path) # When validate_every is too big if not os.path.isfile(config.save_model_path) or best_UAS != UAS: parser.save(config.save_model_path) return self
python
def train(self, train_file, dev_file, test_file, save_dir, pretrained_embeddings=None, min_occur_count=2, lstm_layers=3, word_dims=100, tag_dims=100, dropout_emb=0.33, lstm_hiddens=400, dropout_lstm_input=0.33, dropout_lstm_hidden=0.33, mlp_arc_size=500, mlp_rel_size=100, dropout_mlp=0.33, learning_rate=2e-3, decay=.75, decay_steps=5000, beta_1=.9, beta_2=.9, epsilon=1e-12, num_buckets_train=40, num_buckets_valid=10, num_buckets_test=10, train_iters=50000, train_batch_size=5000, test_batch_size=5000, validate_every=100, save_after=5000, debug=False): """Train a deep biaffine dependency parser Parameters ---------- train_file : str path to training set dev_file : str path to dev set test_file : str path to test set save_dir : str a directory for saving model and related meta-data pretrained_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) min_occur_count : int threshold of rare words, which will be replaced with UNKs, lstm_layers : int layers of lstm word_dims : int dimension of word embedding tag_dims : int dimension of tag embedding dropout_emb : float word dropout lstm_hiddens : int size of lstm hidden states dropout_lstm_input : int dropout on x in variational RNN dropout_lstm_hidden : int dropout on h in variational RNN mlp_arc_size : int output size of MLP for arc feature extraction mlp_rel_size : int output size of MLP for rel feature extraction dropout_mlp : float dropout on the output of LSTM learning_rate : float learning rate decay : float see ExponentialScheduler decay_steps : int see ExponentialScheduler beta_1 : float see ExponentialScheduler beta_2 : float see ExponentialScheduler epsilon : float see ExponentialScheduler num_buckets_train : int number of buckets for training data set num_buckets_valid : int number of buckets for dev data set num_buckets_test : int number of buckets for testing data set train_iters : int training iterations train_batch_size : int training batch size test_batch_size : int test batch size validate_every : int validate on dev set every such number of batches save_after : int skip saving model in early epochs debug : bool debug mode Returns ------- DepParser parser itself """ logger = init_logger(save_dir) config = _Config(train_file, dev_file, test_file, save_dir, pretrained_embeddings, min_occur_count, lstm_layers, word_dims, tag_dims, dropout_emb, lstm_hiddens, dropout_lstm_input, dropout_lstm_hidden, mlp_arc_size, mlp_rel_size, dropout_mlp, learning_rate, decay, decay_steps, beta_1, beta_2, epsilon, num_buckets_train, num_buckets_valid, num_buckets_test, train_iters, train_batch_size, debug) config.save() self._vocab = vocab = ParserVocabulary(train_file, pretrained_embeddings, min_occur_count) vocab.save(config.save_vocab_path) vocab.log_info(logger) with mx.Context(mxnet_prefer_gpu()): self._parser = parser = BiaffineParser(vocab, word_dims, tag_dims, dropout_emb, lstm_layers, lstm_hiddens, dropout_lstm_input, dropout_lstm_hidden, mlp_arc_size, mlp_rel_size, dropout_mlp, debug) parser.initialize() scheduler = ExponentialScheduler(learning_rate, decay, decay_steps) optimizer = mx.optimizer.Adam(learning_rate, beta_1, beta_2, epsilon, lr_scheduler=scheduler) trainer = gluon.Trainer(parser.collect_params(), optimizer=optimizer) data_loader = DataLoader(train_file, num_buckets_train, vocab) global_step = 0 best_UAS = 0. batch_id = 0 epoch = 1 total_epoch = math.ceil(train_iters / validate_every) logger.info("Epoch {} out of {}".format(epoch, total_epoch)) bar = Progbar(target=min(validate_every, data_loader.samples)) while global_step < train_iters: for words, tags, arcs, rels in data_loader.get_batches(batch_size=train_batch_size, shuffle=True): with autograd.record(): arc_accuracy, rel_accuracy, overall_accuracy, loss = parser.forward(words, tags, arcs, rels) loss_value = loss.asscalar() loss.backward() trainer.step(train_batch_size) batch_id += 1 try: bar.update(batch_id, exact=[("UAS", arc_accuracy, 2), # ("LAS", rel_accuracy, 2), # ("ALL", overall_accuracy, 2), ("loss", loss_value)]) except OverflowError: pass # sometimes loss can be 0 or infinity, crashes the bar global_step += 1 if global_step % validate_every == 0: bar = Progbar(target=min(validate_every, train_iters - global_step)) batch_id = 0 UAS, LAS, speed = evaluate_official_script(parser, vocab, num_buckets_valid, test_batch_size, dev_file, os.path.join(save_dir, 'valid_tmp')) logger.info('Dev: UAS %.2f%% LAS %.2f%% %d sents/s' % (UAS, LAS, speed)) epoch += 1 if global_step < train_iters: logger.info("Epoch {} out of {}".format(epoch, total_epoch)) if global_step > save_after and UAS > best_UAS: logger.info('- new best score!') best_UAS = UAS parser.save(config.save_model_path) # When validate_every is too big if not os.path.isfile(config.save_model_path) or best_UAS != UAS: parser.save(config.save_model_path) return self
[ "def", "train", "(", "self", ",", "train_file", ",", "dev_file", ",", "test_file", ",", "save_dir", ",", "pretrained_embeddings", "=", "None", ",", "min_occur_count", "=", "2", ",", "lstm_layers", "=", "3", ",", "word_dims", "=", "100", ",", "tag_dims", "=", "100", ",", "dropout_emb", "=", "0.33", ",", "lstm_hiddens", "=", "400", ",", "dropout_lstm_input", "=", "0.33", ",", "dropout_lstm_hidden", "=", "0.33", ",", "mlp_arc_size", "=", "500", ",", "mlp_rel_size", "=", "100", ",", "dropout_mlp", "=", "0.33", ",", "learning_rate", "=", "2e-3", ",", "decay", "=", ".75", ",", "decay_steps", "=", "5000", ",", "beta_1", "=", ".9", ",", "beta_2", "=", ".9", ",", "epsilon", "=", "1e-12", ",", "num_buckets_train", "=", "40", ",", "num_buckets_valid", "=", "10", ",", "num_buckets_test", "=", "10", ",", "train_iters", "=", "50000", ",", "train_batch_size", "=", "5000", ",", "test_batch_size", "=", "5000", ",", "validate_every", "=", "100", ",", "save_after", "=", "5000", ",", "debug", "=", "False", ")", ":", "logger", "=", "init_logger", "(", "save_dir", ")", "config", "=", "_Config", "(", "train_file", ",", "dev_file", ",", "test_file", ",", "save_dir", ",", "pretrained_embeddings", ",", "min_occur_count", ",", "lstm_layers", ",", "word_dims", ",", "tag_dims", ",", "dropout_emb", ",", "lstm_hiddens", ",", "dropout_lstm_input", ",", "dropout_lstm_hidden", ",", "mlp_arc_size", ",", "mlp_rel_size", ",", "dropout_mlp", ",", "learning_rate", ",", "decay", ",", "decay_steps", ",", "beta_1", ",", "beta_2", ",", "epsilon", ",", "num_buckets_train", ",", "num_buckets_valid", ",", "num_buckets_test", ",", "train_iters", ",", "train_batch_size", ",", "debug", ")", "config", ".", "save", "(", ")", "self", ".", "_vocab", "=", "vocab", "=", "ParserVocabulary", "(", "train_file", ",", "pretrained_embeddings", ",", "min_occur_count", ")", "vocab", ".", "save", "(", "config", ".", "save_vocab_path", ")", "vocab", ".", "log_info", "(", "logger", ")", "with", "mx", ".", "Context", "(", "mxnet_prefer_gpu", "(", ")", ")", ":", "self", ".", "_parser", "=", "parser", "=", "BiaffineParser", "(", "vocab", ",", "word_dims", ",", "tag_dims", ",", "dropout_emb", ",", "lstm_layers", ",", "lstm_hiddens", ",", "dropout_lstm_input", ",", "dropout_lstm_hidden", ",", "mlp_arc_size", ",", "mlp_rel_size", ",", "dropout_mlp", ",", "debug", ")", "parser", ".", "initialize", "(", ")", "scheduler", "=", "ExponentialScheduler", "(", "learning_rate", ",", "decay", ",", "decay_steps", ")", "optimizer", "=", "mx", ".", "optimizer", ".", "Adam", "(", "learning_rate", ",", "beta_1", ",", "beta_2", ",", "epsilon", ",", "lr_scheduler", "=", "scheduler", ")", "trainer", "=", "gluon", ".", "Trainer", "(", "parser", ".", "collect_params", "(", ")", ",", "optimizer", "=", "optimizer", ")", "data_loader", "=", "DataLoader", "(", "train_file", ",", "num_buckets_train", ",", "vocab", ")", "global_step", "=", "0", "best_UAS", "=", "0.", "batch_id", "=", "0", "epoch", "=", "1", "total_epoch", "=", "math", ".", "ceil", "(", "train_iters", "/", "validate_every", ")", "logger", ".", "info", "(", "\"Epoch {} out of {}\"", ".", "format", "(", "epoch", ",", "total_epoch", ")", ")", "bar", "=", "Progbar", "(", "target", "=", "min", "(", "validate_every", ",", "data_loader", ".", "samples", ")", ")", "while", "global_step", "<", "train_iters", ":", "for", "words", ",", "tags", ",", "arcs", ",", "rels", "in", "data_loader", ".", "get_batches", "(", "batch_size", "=", "train_batch_size", ",", "shuffle", "=", "True", ")", ":", "with", "autograd", ".", "record", "(", ")", ":", "arc_accuracy", ",", "rel_accuracy", ",", "overall_accuracy", ",", "loss", "=", "parser", ".", "forward", "(", "words", ",", "tags", ",", "arcs", ",", "rels", ")", "loss_value", "=", "loss", ".", "asscalar", "(", ")", "loss", ".", "backward", "(", ")", "trainer", ".", "step", "(", "train_batch_size", ")", "batch_id", "+=", "1", "try", ":", "bar", ".", "update", "(", "batch_id", ",", "exact", "=", "[", "(", "\"UAS\"", ",", "arc_accuracy", ",", "2", ")", ",", "# (\"LAS\", rel_accuracy, 2),", "# (\"ALL\", overall_accuracy, 2),", "(", "\"loss\"", ",", "loss_value", ")", "]", ")", "except", "OverflowError", ":", "pass", "# sometimes loss can be 0 or infinity, crashes the bar", "global_step", "+=", "1", "if", "global_step", "%", "validate_every", "==", "0", ":", "bar", "=", "Progbar", "(", "target", "=", "min", "(", "validate_every", ",", "train_iters", "-", "global_step", ")", ")", "batch_id", "=", "0", "UAS", ",", "LAS", ",", "speed", "=", "evaluate_official_script", "(", "parser", ",", "vocab", ",", "num_buckets_valid", ",", "test_batch_size", ",", "dev_file", ",", "os", ".", "path", ".", "join", "(", "save_dir", ",", "'valid_tmp'", ")", ")", "logger", ".", "info", "(", "'Dev: UAS %.2f%% LAS %.2f%% %d sents/s'", "%", "(", "UAS", ",", "LAS", ",", "speed", ")", ")", "epoch", "+=", "1", "if", "global_step", "<", "train_iters", ":", "logger", ".", "info", "(", "\"Epoch {} out of {}\"", ".", "format", "(", "epoch", ",", "total_epoch", ")", ")", "if", "global_step", ">", "save_after", "and", "UAS", ">", "best_UAS", ":", "logger", ".", "info", "(", "'- new best score!'", ")", "best_UAS", "=", "UAS", "parser", ".", "save", "(", "config", ".", "save_model_path", ")", "# When validate_every is too big", "if", "not", "os", ".", "path", ".", "isfile", "(", "config", ".", "save_model_path", ")", "or", "best_UAS", "!=", "UAS", ":", "parser", ".", "save", "(", "config", ".", "save_model_path", ")", "return", "self" ]
Train a deep biaffine dependency parser Parameters ---------- train_file : str path to training set dev_file : str path to dev set test_file : str path to test set save_dir : str a directory for saving model and related meta-data pretrained_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) min_occur_count : int threshold of rare words, which will be replaced with UNKs, lstm_layers : int layers of lstm word_dims : int dimension of word embedding tag_dims : int dimension of tag embedding dropout_emb : float word dropout lstm_hiddens : int size of lstm hidden states dropout_lstm_input : int dropout on x in variational RNN dropout_lstm_hidden : int dropout on h in variational RNN mlp_arc_size : int output size of MLP for arc feature extraction mlp_rel_size : int output size of MLP for rel feature extraction dropout_mlp : float dropout on the output of LSTM learning_rate : float learning rate decay : float see ExponentialScheduler decay_steps : int see ExponentialScheduler beta_1 : float see ExponentialScheduler beta_2 : float see ExponentialScheduler epsilon : float see ExponentialScheduler num_buckets_train : int number of buckets for training data set num_buckets_valid : int number of buckets for dev data set num_buckets_test : int number of buckets for testing data set train_iters : int training iterations train_batch_size : int training batch size test_batch_size : int test batch size validate_every : int validate on dev set every such number of batches save_after : int skip saving model in early epochs debug : bool debug mode Returns ------- DepParser parser itself
[ "Train", "a", "deep", "biaffine", "dependency", "parser" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L44-L199
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.load
def load(self, path): """Load from disk Parameters ---------- path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns ------- DepParser parser itself """ config = _Config.load(os.path.join(path, 'config.pkl')) config.save_dir = path # redirect root path to what user specified self._vocab = vocab = ParserVocabulary.load(config.save_vocab_path) with mx.Context(mxnet_prefer_gpu()): self._parser = BiaffineParser(vocab, config.word_dims, config.tag_dims, config.dropout_emb, config.lstm_layers, config.lstm_hiddens, config.dropout_lstm_input, config.dropout_lstm_hidden, config.mlp_arc_size, config.mlp_rel_size, config.dropout_mlp, config.debug) self._parser.load(config.save_model_path) return self
python
def load(self, path): """Load from disk Parameters ---------- path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns ------- DepParser parser itself """ config = _Config.load(os.path.join(path, 'config.pkl')) config.save_dir = path # redirect root path to what user specified self._vocab = vocab = ParserVocabulary.load(config.save_vocab_path) with mx.Context(mxnet_prefer_gpu()): self._parser = BiaffineParser(vocab, config.word_dims, config.tag_dims, config.dropout_emb, config.lstm_layers, config.lstm_hiddens, config.dropout_lstm_input, config.dropout_lstm_hidden, config.mlp_arc_size, config.mlp_rel_size, config.dropout_mlp, config.debug) self._parser.load(config.save_model_path) return self
[ "def", "load", "(", "self", ",", "path", ")", ":", "config", "=", "_Config", ".", "load", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'config.pkl'", ")", ")", "config", ".", "save_dir", "=", "path", "# redirect root path to what user specified", "self", ".", "_vocab", "=", "vocab", "=", "ParserVocabulary", ".", "load", "(", "config", ".", "save_vocab_path", ")", "with", "mx", ".", "Context", "(", "mxnet_prefer_gpu", "(", ")", ")", ":", "self", ".", "_parser", "=", "BiaffineParser", "(", "vocab", ",", "config", ".", "word_dims", ",", "config", ".", "tag_dims", ",", "config", ".", "dropout_emb", ",", "config", ".", "lstm_layers", ",", "config", ".", "lstm_hiddens", ",", "config", ".", "dropout_lstm_input", ",", "config", ".", "dropout_lstm_hidden", ",", "config", ".", "mlp_arc_size", ",", "config", ".", "mlp_rel_size", ",", "config", ".", "dropout_mlp", ",", "config", ".", "debug", ")", "self", ".", "_parser", ".", "load", "(", "config", ".", "save_model_path", ")", "return", "self" ]
Load from disk Parameters ---------- path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns ------- DepParser parser itself
[ "Load", "from", "disk" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L201-L224
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.evaluate
def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000): """Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log logger : logging.logger logger for printing results num_buckets_test : int number of clusters for sentences from test set test_batch_size : int batch size of test set Returns ------- tuple UAS, LAS """ parser = self._parser vocab = self._vocab with mx.Context(mxnet_prefer_gpu()): UAS, LAS, speed = evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, os.path.join(save_dir, 'valid_tmp')) if logger is None: logger = init_logger(save_dir, 'test.log') logger.info('Test: UAS %.2f%% LAS %.2f%% %d sents/s' % (UAS, LAS, speed)) return UAS, LAS
python
def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000): """Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log logger : logging.logger logger for printing results num_buckets_test : int number of clusters for sentences from test set test_batch_size : int batch size of test set Returns ------- tuple UAS, LAS """ parser = self._parser vocab = self._vocab with mx.Context(mxnet_prefer_gpu()): UAS, LAS, speed = evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, os.path.join(save_dir, 'valid_tmp')) if logger is None: logger = init_logger(save_dir, 'test.log') logger.info('Test: UAS %.2f%% LAS %.2f%% %d sents/s' % (UAS, LAS, speed)) return UAS, LAS
[ "def", "evaluate", "(", "self", ",", "test_file", ",", "save_dir", "=", "None", ",", "logger", "=", "None", ",", "num_buckets_test", "=", "10", ",", "test_batch_size", "=", "5000", ")", ":", "parser", "=", "self", ".", "_parser", "vocab", "=", "self", ".", "_vocab", "with", "mx", ".", "Context", "(", "mxnet_prefer_gpu", "(", ")", ")", ":", "UAS", ",", "LAS", ",", "speed", "=", "evaluate_official_script", "(", "parser", ",", "vocab", ",", "num_buckets_test", ",", "test_batch_size", ",", "test_file", ",", "os", ".", "path", ".", "join", "(", "save_dir", ",", "'valid_tmp'", ")", ")", "if", "logger", "is", "None", ":", "logger", "=", "init_logger", "(", "save_dir", ",", "'test.log'", ")", "logger", ".", "info", "(", "'Test: UAS %.2f%% LAS %.2f%% %d sents/s'", "%", "(", "UAS", ",", "LAS", ",", "speed", ")", ")", "return", "UAS", ",", "LAS" ]
Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log logger : logging.logger logger for printing results num_buckets_test : int number of clusters for sentences from test set test_batch_size : int batch size of test set Returns ------- tuple UAS, LAS
[ "Run", "evaluation", "on", "test", "set" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L226-L256
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.parse
def parse(self, sentence): """Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object """ words = np.zeros((len(sentence) + 1, 1), np.int32) tags = np.zeros((len(sentence) + 1, 1), np.int32) words[0, 0] = ParserVocabulary.ROOT tags[0, 0] = ParserVocabulary.ROOT vocab = self._vocab for i, (word, tag) in enumerate(sentence): words[i + 1, 0], tags[i + 1, 0] = vocab.word2id(word.lower()), vocab.tag2id(tag) with mx.Context(mxnet_prefer_gpu()): outputs = self._parser.forward(words, tags) words = [] for arc, rel, (word, tag) in zip(outputs[0][0], outputs[0][1], sentence): words.append(ConllWord(id=len(words) + 1, form=word, pos=tag, head=arc, relation=vocab.id2rel(rel))) return ConllSentence(words)
python
def parse(self, sentence): """Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object """ words = np.zeros((len(sentence) + 1, 1), np.int32) tags = np.zeros((len(sentence) + 1, 1), np.int32) words[0, 0] = ParserVocabulary.ROOT tags[0, 0] = ParserVocabulary.ROOT vocab = self._vocab for i, (word, tag) in enumerate(sentence): words[i + 1, 0], tags[i + 1, 0] = vocab.word2id(word.lower()), vocab.tag2id(tag) with mx.Context(mxnet_prefer_gpu()): outputs = self._parser.forward(words, tags) words = [] for arc, rel, (word, tag) in zip(outputs[0][0], outputs[0][1], sentence): words.append(ConllWord(id=len(words) + 1, form=word, pos=tag, head=arc, relation=vocab.id2rel(rel))) return ConllSentence(words)
[ "def", "parse", "(", "self", ",", "sentence", ")", ":", "words", "=", "np", ".", "zeros", "(", "(", "len", "(", "sentence", ")", "+", "1", ",", "1", ")", ",", "np", ".", "int32", ")", "tags", "=", "np", ".", "zeros", "(", "(", "len", "(", "sentence", ")", "+", "1", ",", "1", ")", ",", "np", ".", "int32", ")", "words", "[", "0", ",", "0", "]", "=", "ParserVocabulary", ".", "ROOT", "tags", "[", "0", ",", "0", "]", "=", "ParserVocabulary", ".", "ROOT", "vocab", "=", "self", ".", "_vocab", "for", "i", ",", "(", "word", ",", "tag", ")", "in", "enumerate", "(", "sentence", ")", ":", "words", "[", "i", "+", "1", ",", "0", "]", ",", "tags", "[", "i", "+", "1", ",", "0", "]", "=", "vocab", ".", "word2id", "(", "word", ".", "lower", "(", ")", ")", ",", "vocab", ".", "tag2id", "(", "tag", ")", "with", "mx", ".", "Context", "(", "mxnet_prefer_gpu", "(", ")", ")", ":", "outputs", "=", "self", ".", "_parser", ".", "forward", "(", "words", ",", "tags", ")", "words", "=", "[", "]", "for", "arc", ",", "rel", ",", "(", "word", ",", "tag", ")", "in", "zip", "(", "outputs", "[", "0", "]", "[", "0", "]", ",", "outputs", "[", "0", "]", "[", "1", "]", ",", "sentence", ")", ":", "words", ".", "append", "(", "ConllWord", "(", "id", "=", "len", "(", "words", ")", "+", "1", ",", "form", "=", "word", ",", "pos", "=", "tag", ",", "head", "=", "arc", ",", "relation", "=", "vocab", ".", "id2rel", "(", "rel", ")", ")", ")", "return", "ConllSentence", "(", "words", ")" ]
Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object
[ "Parse", "raw", "sentence", "into", "ConllSentence" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L258-L285
train
dmlc/gluon-nlp
src/gluonnlp/model/utils.py
apply_weight_drop
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_regex : str The regex for parameter names used in the self.params.get(), such as 'weight'. rate : float Fraction of the input units to drop. Must be a number between 0 and 1. axes : tuple of int, default () The axes on which dropout mask is shared. If empty, regular dropout is applied. weight_drop_mode : {'training', 'always'}, default 'training' Whether the weight dropout should be applied only at training time, or always be applied. Examples -------- >>> net = gluon.rnn.LSTM(10, num_layers=2, bidirectional=True) >>> gluonnlp.model.apply_weight_drop(net, r'.*h2h_weight', 0.5) >>> net.collect_params() lstm0_ ( Parameter lstm0_l0_i2h_weight (shape=(40, 0), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_l0_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_l0_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l0_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r0_i2h_weight (shape=(40, 0), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_r0_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_r0_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r0_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l1_i2h_weight (shape=(40, 20), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_l1_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_l1_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l1_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r1_i2h_weight (shape=(40, 20), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_r1_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_r1_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r1_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) ) >>> ones = mx.nd.ones((3, 4, 5)) >>> net.initialize() >>> with mx.autograd.train_mode(): ... net(ones).max().asscalar() != net(ones).max().asscalar() True """ if not rate: return existing_params = _find_params(block, local_param_regex) for (local_param_name, param), \ (ref_params_list, ref_reg_params_list) in existing_params.items(): dropped_param = WeightDropParameter(param, rate, weight_dropout_mode, axes) for ref_params in ref_params_list: ref_params[param.name] = dropped_param for ref_reg_params in ref_reg_params_list: ref_reg_params[local_param_name] = dropped_param if hasattr(block, local_param_name): local_attr = getattr(block, local_param_name) if local_attr == param: local_attr = dropped_param elif isinstance(local_attr, (list, tuple)): if isinstance(local_attr, tuple): local_attr = list(local_attr) for i, v in enumerate(local_attr): if v == param: local_attr[i] = dropped_param elif isinstance(local_attr, dict): for k, v in local_attr: if v == param: local_attr[k] = dropped_param else: continue if local_attr: super(Block, block).__setattr__(local_param_name, local_attr)
python
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_regex : str The regex for parameter names used in the self.params.get(), such as 'weight'. rate : float Fraction of the input units to drop. Must be a number between 0 and 1. axes : tuple of int, default () The axes on which dropout mask is shared. If empty, regular dropout is applied. weight_drop_mode : {'training', 'always'}, default 'training' Whether the weight dropout should be applied only at training time, or always be applied. Examples -------- >>> net = gluon.rnn.LSTM(10, num_layers=2, bidirectional=True) >>> gluonnlp.model.apply_weight_drop(net, r'.*h2h_weight', 0.5) >>> net.collect_params() lstm0_ ( Parameter lstm0_l0_i2h_weight (shape=(40, 0), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_l0_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_l0_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l0_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r0_i2h_weight (shape=(40, 0), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_r0_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_r0_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r0_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l1_i2h_weight (shape=(40, 20), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_l1_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_l1_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l1_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r1_i2h_weight (shape=(40, 20), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_r1_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_r1_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r1_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) ) >>> ones = mx.nd.ones((3, 4, 5)) >>> net.initialize() >>> with mx.autograd.train_mode(): ... net(ones).max().asscalar() != net(ones).max().asscalar() True """ if not rate: return existing_params = _find_params(block, local_param_regex) for (local_param_name, param), \ (ref_params_list, ref_reg_params_list) in existing_params.items(): dropped_param = WeightDropParameter(param, rate, weight_dropout_mode, axes) for ref_params in ref_params_list: ref_params[param.name] = dropped_param for ref_reg_params in ref_reg_params_list: ref_reg_params[local_param_name] = dropped_param if hasattr(block, local_param_name): local_attr = getattr(block, local_param_name) if local_attr == param: local_attr = dropped_param elif isinstance(local_attr, (list, tuple)): if isinstance(local_attr, tuple): local_attr = list(local_attr) for i, v in enumerate(local_attr): if v == param: local_attr[i] = dropped_param elif isinstance(local_attr, dict): for k, v in local_attr: if v == param: local_attr[k] = dropped_param else: continue if local_attr: super(Block, block).__setattr__(local_param_name, local_attr)
[ "def", "apply_weight_drop", "(", "block", ",", "local_param_regex", ",", "rate", ",", "axes", "=", "(", ")", ",", "weight_dropout_mode", "=", "'training'", ")", ":", "if", "not", "rate", ":", "return", "existing_params", "=", "_find_params", "(", "block", ",", "local_param_regex", ")", "for", "(", "local_param_name", ",", "param", ")", ",", "(", "ref_params_list", ",", "ref_reg_params_list", ")", "in", "existing_params", ".", "items", "(", ")", ":", "dropped_param", "=", "WeightDropParameter", "(", "param", ",", "rate", ",", "weight_dropout_mode", ",", "axes", ")", "for", "ref_params", "in", "ref_params_list", ":", "ref_params", "[", "param", ".", "name", "]", "=", "dropped_param", "for", "ref_reg_params", "in", "ref_reg_params_list", ":", "ref_reg_params", "[", "local_param_name", "]", "=", "dropped_param", "if", "hasattr", "(", "block", ",", "local_param_name", ")", ":", "local_attr", "=", "getattr", "(", "block", ",", "local_param_name", ")", "if", "local_attr", "==", "param", ":", "local_attr", "=", "dropped_param", "elif", "isinstance", "(", "local_attr", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "isinstance", "(", "local_attr", ",", "tuple", ")", ":", "local_attr", "=", "list", "(", "local_attr", ")", "for", "i", ",", "v", "in", "enumerate", "(", "local_attr", ")", ":", "if", "v", "==", "param", ":", "local_attr", "[", "i", "]", "=", "dropped_param", "elif", "isinstance", "(", "local_attr", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "local_attr", ":", "if", "v", "==", "param", ":", "local_attr", "[", "k", "]", "=", "dropped_param", "else", ":", "continue", "if", "local_attr", ":", "super", "(", "Block", ",", "block", ")", ".", "__setattr__", "(", "local_param_name", ",", "local_attr", ")" ]
Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_regex : str The regex for parameter names used in the self.params.get(), such as 'weight'. rate : float Fraction of the input units to drop. Must be a number between 0 and 1. axes : tuple of int, default () The axes on which dropout mask is shared. If empty, regular dropout is applied. weight_drop_mode : {'training', 'always'}, default 'training' Whether the weight dropout should be applied only at training time, or always be applied. Examples -------- >>> net = gluon.rnn.LSTM(10, num_layers=2, bidirectional=True) >>> gluonnlp.model.apply_weight_drop(net, r'.*h2h_weight', 0.5) >>> net.collect_params() lstm0_ ( Parameter lstm0_l0_i2h_weight (shape=(40, 0), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_l0_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_l0_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l0_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r0_i2h_weight (shape=(40, 0), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_r0_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_r0_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r0_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l1_i2h_weight (shape=(40, 20), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_l1_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_l1_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_l1_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r1_i2h_weight (shape=(40, 20), dtype=<class 'numpy.float32'>) WeightDropParameter lstm0_r1_h2h_weight (shape=(40, 10), dtype=<class 'numpy.float32'>, \ rate=0.5, mode=training) Parameter lstm0_r1_i2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) Parameter lstm0_r1_h2h_bias (shape=(40,), dtype=<class 'numpy.float32'>) ) >>> ones = mx.nd.ones((3, 4, 5)) >>> net.initialize() >>> with mx.autograd.train_mode(): ... net(ones).max().asscalar() != net(ones).max().asscalar() True
[ "Apply", "weight", "drop", "to", "the", "parameter", "of", "a", "block", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L36-L114
train
dmlc/gluon-nlp
src/gluonnlp/model/utils.py
_get_rnn_cell
def _get_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, cell_clip=None, proj_clip=None): """create rnn cell given specs Parameters ---------- mode : str The type of RNN cell to use. Options are 'lstmpc', 'rnn_tanh', 'rnn_relu', 'lstm', 'gru'. num_layers : int The number of RNN cells in the encoder. input_size : int The initial input size of in the RNN cell. hidden_size : int The hidden size of the RNN cell. dropout : float The dropout rate to use for encoder output. weight_dropout: float The dropout rate to the hidden to hidden connections. var_drop_in: float The variational dropout rate for inputs. Won’t apply dropout if it equals 0. var_drop_state: float The variational dropout rate for state inputs on the first state channel. Won’t apply dropout if it equals 0. var_drop_out: float The variational dropout rate for outputs. Won’t apply dropout if it equals 0. skip_connection : bool Whether to add skip connections (add RNN cell input to output) proj_size : int The projection size of each LSTMPCellWithClip cell. Only available when the mode=lstmpc. cell_clip : float Clip cell state between [-cellclip, cell_clip] in LSTMPCellWithClip cell. Only available when the mode=lstmpc. proj_clip : float Clip projection between [-projclip, projclip] in LSTMPCellWithClip cell Only available when the mode=lstmpc. """ assert mode == 'lstmpc' and proj_size is not None, \ 'proj_size takes effect only when mode is lstmpc' assert mode == 'lstmpc' and cell_clip is not None, \ 'cell_clip takes effect only when mode is lstmpc' assert mode == 'lstmpc' and proj_clip is not None, \ 'proj_clip takes effect only when mode is lstmpc' rnn_cell = rnn.HybridSequentialRNNCell() with rnn_cell.name_scope(): for i in range(num_layers): if mode == 'rnn_relu': cell = rnn.RNNCell(hidden_size, 'relu', input_size=input_size) elif mode == 'rnn_tanh': cell = rnn.RNNCell(hidden_size, 'tanh', input_size=input_size) elif mode == 'lstm': cell = rnn.LSTMCell(hidden_size, input_size=input_size) elif mode == 'gru': cell = rnn.GRUCell(hidden_size, input_size=input_size) elif mode == 'lstmpc': cell = LSTMPCellWithClip(hidden_size, proj_size, cell_clip=cell_clip, projection_clip=proj_clip, input_size=input_size) if var_drop_in + var_drop_state + var_drop_out != 0: cell = contrib.rnn.VariationalDropoutCell(cell, var_drop_in, var_drop_state, var_drop_out) if skip_connection: cell = rnn.ResidualCell(cell) rnn_cell.add(cell) if i != num_layers - 1 and dropout != 0: rnn_cell.add(rnn.DropoutCell(dropout)) if weight_dropout: apply_weight_drop(rnn_cell, 'h2h_weight', rate=weight_dropout) return rnn_cell
python
def _get_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, cell_clip=None, proj_clip=None): """create rnn cell given specs Parameters ---------- mode : str The type of RNN cell to use. Options are 'lstmpc', 'rnn_tanh', 'rnn_relu', 'lstm', 'gru'. num_layers : int The number of RNN cells in the encoder. input_size : int The initial input size of in the RNN cell. hidden_size : int The hidden size of the RNN cell. dropout : float The dropout rate to use for encoder output. weight_dropout: float The dropout rate to the hidden to hidden connections. var_drop_in: float The variational dropout rate for inputs. Won’t apply dropout if it equals 0. var_drop_state: float The variational dropout rate for state inputs on the first state channel. Won’t apply dropout if it equals 0. var_drop_out: float The variational dropout rate for outputs. Won’t apply dropout if it equals 0. skip_connection : bool Whether to add skip connections (add RNN cell input to output) proj_size : int The projection size of each LSTMPCellWithClip cell. Only available when the mode=lstmpc. cell_clip : float Clip cell state between [-cellclip, cell_clip] in LSTMPCellWithClip cell. Only available when the mode=lstmpc. proj_clip : float Clip projection between [-projclip, projclip] in LSTMPCellWithClip cell Only available when the mode=lstmpc. """ assert mode == 'lstmpc' and proj_size is not None, \ 'proj_size takes effect only when mode is lstmpc' assert mode == 'lstmpc' and cell_clip is not None, \ 'cell_clip takes effect only when mode is lstmpc' assert mode == 'lstmpc' and proj_clip is not None, \ 'proj_clip takes effect only when mode is lstmpc' rnn_cell = rnn.HybridSequentialRNNCell() with rnn_cell.name_scope(): for i in range(num_layers): if mode == 'rnn_relu': cell = rnn.RNNCell(hidden_size, 'relu', input_size=input_size) elif mode == 'rnn_tanh': cell = rnn.RNNCell(hidden_size, 'tanh', input_size=input_size) elif mode == 'lstm': cell = rnn.LSTMCell(hidden_size, input_size=input_size) elif mode == 'gru': cell = rnn.GRUCell(hidden_size, input_size=input_size) elif mode == 'lstmpc': cell = LSTMPCellWithClip(hidden_size, proj_size, cell_clip=cell_clip, projection_clip=proj_clip, input_size=input_size) if var_drop_in + var_drop_state + var_drop_out != 0: cell = contrib.rnn.VariationalDropoutCell(cell, var_drop_in, var_drop_state, var_drop_out) if skip_connection: cell = rnn.ResidualCell(cell) rnn_cell.add(cell) if i != num_layers - 1 and dropout != 0: rnn_cell.add(rnn.DropoutCell(dropout)) if weight_dropout: apply_weight_drop(rnn_cell, 'h2h_weight', rate=weight_dropout) return rnn_cell
[ "def", "_get_rnn_cell", "(", "mode", ",", "num_layers", ",", "input_size", ",", "hidden_size", ",", "dropout", ",", "weight_dropout", ",", "var_drop_in", ",", "var_drop_state", ",", "var_drop_out", ",", "skip_connection", ",", "proj_size", "=", "None", ",", "cell_clip", "=", "None", ",", "proj_clip", "=", "None", ")", ":", "assert", "mode", "==", "'lstmpc'", "and", "proj_size", "is", "not", "None", ",", "'proj_size takes effect only when mode is lstmpc'", "assert", "mode", "==", "'lstmpc'", "and", "cell_clip", "is", "not", "None", ",", "'cell_clip takes effect only when mode is lstmpc'", "assert", "mode", "==", "'lstmpc'", "and", "proj_clip", "is", "not", "None", ",", "'proj_clip takes effect only when mode is lstmpc'", "rnn_cell", "=", "rnn", ".", "HybridSequentialRNNCell", "(", ")", "with", "rnn_cell", ".", "name_scope", "(", ")", ":", "for", "i", "in", "range", "(", "num_layers", ")", ":", "if", "mode", "==", "'rnn_relu'", ":", "cell", "=", "rnn", ".", "RNNCell", "(", "hidden_size", ",", "'relu'", ",", "input_size", "=", "input_size", ")", "elif", "mode", "==", "'rnn_tanh'", ":", "cell", "=", "rnn", ".", "RNNCell", "(", "hidden_size", ",", "'tanh'", ",", "input_size", "=", "input_size", ")", "elif", "mode", "==", "'lstm'", ":", "cell", "=", "rnn", ".", "LSTMCell", "(", "hidden_size", ",", "input_size", "=", "input_size", ")", "elif", "mode", "==", "'gru'", ":", "cell", "=", "rnn", ".", "GRUCell", "(", "hidden_size", ",", "input_size", "=", "input_size", ")", "elif", "mode", "==", "'lstmpc'", ":", "cell", "=", "LSTMPCellWithClip", "(", "hidden_size", ",", "proj_size", ",", "cell_clip", "=", "cell_clip", ",", "projection_clip", "=", "proj_clip", ",", "input_size", "=", "input_size", ")", "if", "var_drop_in", "+", "var_drop_state", "+", "var_drop_out", "!=", "0", ":", "cell", "=", "contrib", ".", "rnn", ".", "VariationalDropoutCell", "(", "cell", ",", "var_drop_in", ",", "var_drop_state", ",", "var_drop_out", ")", "if", "skip_connection", ":", "cell", "=", "rnn", ".", "ResidualCell", "(", "cell", ")", "rnn_cell", ".", "add", "(", "cell", ")", "if", "i", "!=", "num_layers", "-", "1", "and", "dropout", "!=", "0", ":", "rnn_cell", ".", "add", "(", "rnn", ".", "DropoutCell", "(", "dropout", ")", ")", "if", "weight_dropout", ":", "apply_weight_drop", "(", "rnn_cell", ",", "'h2h_weight'", ",", "rate", "=", "weight_dropout", ")", "return", "rnn_cell" ]
create rnn cell given specs Parameters ---------- mode : str The type of RNN cell to use. Options are 'lstmpc', 'rnn_tanh', 'rnn_relu', 'lstm', 'gru'. num_layers : int The number of RNN cells in the encoder. input_size : int The initial input size of in the RNN cell. hidden_size : int The hidden size of the RNN cell. dropout : float The dropout rate to use for encoder output. weight_dropout: float The dropout rate to the hidden to hidden connections. var_drop_in: float The variational dropout rate for inputs. Won’t apply dropout if it equals 0. var_drop_state: float The variational dropout rate for state inputs on the first state channel. Won’t apply dropout if it equals 0. var_drop_out: float The variational dropout rate for outputs. Won’t apply dropout if it equals 0. skip_connection : bool Whether to add skip connections (add RNN cell input to output) proj_size : int The projection size of each LSTMPCellWithClip cell. Only available when the mode=lstmpc. cell_clip : float Clip cell state between [-cellclip, cell_clip] in LSTMPCellWithClip cell. Only available when the mode=lstmpc. proj_clip : float Clip projection between [-projclip, projclip] in LSTMPCellWithClip cell Only available when the mode=lstmpc.
[ "create", "rnn", "cell", "given", "specs" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L162-L242
train
dmlc/gluon-nlp
src/gluonnlp/model/utils.py
_get_rnn_layer
def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout): """create rnn layer given specs""" if mode == 'rnn_relu': rnn_block = functools.partial(rnn.RNN, activation='relu') elif mode == 'rnn_tanh': rnn_block = functools.partial(rnn.RNN, activation='tanh') elif mode == 'lstm': rnn_block = rnn.LSTM elif mode == 'gru': rnn_block = rnn.GRU block = rnn_block(hidden_size, num_layers, dropout=dropout, input_size=input_size) if weight_dropout: apply_weight_drop(block, '.*h2h_weight', rate=weight_dropout) return block
python
def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout): """create rnn layer given specs""" if mode == 'rnn_relu': rnn_block = functools.partial(rnn.RNN, activation='relu') elif mode == 'rnn_tanh': rnn_block = functools.partial(rnn.RNN, activation='tanh') elif mode == 'lstm': rnn_block = rnn.LSTM elif mode == 'gru': rnn_block = rnn.GRU block = rnn_block(hidden_size, num_layers, dropout=dropout, input_size=input_size) if weight_dropout: apply_weight_drop(block, '.*h2h_weight', rate=weight_dropout) return block
[ "def", "_get_rnn_layer", "(", "mode", ",", "num_layers", ",", "input_size", ",", "hidden_size", ",", "dropout", ",", "weight_dropout", ")", ":", "if", "mode", "==", "'rnn_relu'", ":", "rnn_block", "=", "functools", ".", "partial", "(", "rnn", ".", "RNN", ",", "activation", "=", "'relu'", ")", "elif", "mode", "==", "'rnn_tanh'", ":", "rnn_block", "=", "functools", ".", "partial", "(", "rnn", ".", "RNN", ",", "activation", "=", "'tanh'", ")", "elif", "mode", "==", "'lstm'", ":", "rnn_block", "=", "rnn", ".", "LSTM", "elif", "mode", "==", "'gru'", ":", "rnn_block", "=", "rnn", ".", "GRU", "block", "=", "rnn_block", "(", "hidden_size", ",", "num_layers", ",", "dropout", "=", "dropout", ",", "input_size", "=", "input_size", ")", "if", "weight_dropout", ":", "apply_weight_drop", "(", "block", ",", "'.*h2h_weight'", ",", "rate", "=", "weight_dropout", ")", "return", "block" ]
create rnn layer given specs
[ "create", "rnn", "layer", "given", "specs" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L245-L262
train
dmlc/gluon-nlp
src/gluonnlp/model/sampled_block.py
_SampledDenseHelper.hybrid_forward
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = w_all.slice(begin=(self._num_sampled, 0), end=(None, None)) b_sampled = b_all.slice(begin=(0,), end=(self._num_sampled,)) b_true = b_all.slice(begin=(self._num_sampled,), end=(None,)) # true pred # (batch_size, 1) x = x.reshape((-1, self._in_unit)) pred_true = (w_true * x).sum(axis=1) + b_true # samples pred # (batch_size, num_sampled) b_sampled = F.reshape(b_sampled, (-1,)) pred_sampled = F.FullyConnected(x, weight=w_sampled, bias=b_sampled, num_hidden=self._num_sampled) # remove accidental hits if self._remove_accidental_hits: label_vec = F.reshape(label, (-1, 1)) sample_vec = F.reshape(sampled_candidates, (1, -1)) mask = F.broadcast_equal(label_vec, sample_vec) * -1e37 pred_sampled = pred_sampled + mask # subtract log(q) expected_count_sampled = F.reshape(expected_count_sampled, shape=(1, self._num_sampled)) expected_count_true = expected_count_true.reshape((-1,)) pred_true = pred_true - F.log(expected_count_true) pred_true = pred_true.reshape((-1, 1)) pred_sampled = F.broadcast_sub(pred_sampled, F.log(expected_count_sampled)) # pred and new_labels # (batch_size, 1+num_sampled) pred = F.concat(pred_true, pred_sampled, dim=1) if self._sparse_label: new_label = F.zeros_like(label) else: label_vec = F.reshape(label, (-1, 1)) new_label_true = F.ones_like(label_vec) new_label_sampled = F.zeros_like(pred_sampled) new_label = F.Concat(new_label_true, new_label_sampled, dim=1) return pred, new_label
python
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = w_all.slice(begin=(self._num_sampled, 0), end=(None, None)) b_sampled = b_all.slice(begin=(0,), end=(self._num_sampled,)) b_true = b_all.slice(begin=(self._num_sampled,), end=(None,)) # true pred # (batch_size, 1) x = x.reshape((-1, self._in_unit)) pred_true = (w_true * x).sum(axis=1) + b_true # samples pred # (batch_size, num_sampled) b_sampled = F.reshape(b_sampled, (-1,)) pred_sampled = F.FullyConnected(x, weight=w_sampled, bias=b_sampled, num_hidden=self._num_sampled) # remove accidental hits if self._remove_accidental_hits: label_vec = F.reshape(label, (-1, 1)) sample_vec = F.reshape(sampled_candidates, (1, -1)) mask = F.broadcast_equal(label_vec, sample_vec) * -1e37 pred_sampled = pred_sampled + mask # subtract log(q) expected_count_sampled = F.reshape(expected_count_sampled, shape=(1, self._num_sampled)) expected_count_true = expected_count_true.reshape((-1,)) pred_true = pred_true - F.log(expected_count_true) pred_true = pred_true.reshape((-1, 1)) pred_sampled = F.broadcast_sub(pred_sampled, F.log(expected_count_sampled)) # pred and new_labels # (batch_size, 1+num_sampled) pred = F.concat(pred_true, pred_sampled, dim=1) if self._sparse_label: new_label = F.zeros_like(label) else: label_vec = F.reshape(label, (-1, 1)) new_label_true = F.ones_like(label_vec) new_label_sampled = F.zeros_like(pred_sampled) new_label = F.Concat(new_label_true, new_label_sampled, dim=1) return pred, new_label
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "x", ",", "sampled_values", ",", "label", ",", "w_all", ",", "b_all", ")", ":", "sampled_candidates", ",", "expected_count_sampled", ",", "expected_count_true", "=", "sampled_values", "# (num_sampled, in_unit)", "w_sampled", "=", "w_all", ".", "slice", "(", "begin", "=", "(", "0", ",", "0", ")", ",", "end", "=", "(", "self", ".", "_num_sampled", ",", "None", ")", ")", "w_true", "=", "w_all", ".", "slice", "(", "begin", "=", "(", "self", ".", "_num_sampled", ",", "0", ")", ",", "end", "=", "(", "None", ",", "None", ")", ")", "b_sampled", "=", "b_all", ".", "slice", "(", "begin", "=", "(", "0", ",", ")", ",", "end", "=", "(", "self", ".", "_num_sampled", ",", ")", ")", "b_true", "=", "b_all", ".", "slice", "(", "begin", "=", "(", "self", ".", "_num_sampled", ",", ")", ",", "end", "=", "(", "None", ",", ")", ")", "# true pred", "# (batch_size, 1)", "x", "=", "x", ".", "reshape", "(", "(", "-", "1", ",", "self", ".", "_in_unit", ")", ")", "pred_true", "=", "(", "w_true", "*", "x", ")", ".", "sum", "(", "axis", "=", "1", ")", "+", "b_true", "# samples pred", "# (batch_size, num_sampled)", "b_sampled", "=", "F", ".", "reshape", "(", "b_sampled", ",", "(", "-", "1", ",", ")", ")", "pred_sampled", "=", "F", ".", "FullyConnected", "(", "x", ",", "weight", "=", "w_sampled", ",", "bias", "=", "b_sampled", ",", "num_hidden", "=", "self", ".", "_num_sampled", ")", "# remove accidental hits", "if", "self", ".", "_remove_accidental_hits", ":", "label_vec", "=", "F", ".", "reshape", "(", "label", ",", "(", "-", "1", ",", "1", ")", ")", "sample_vec", "=", "F", ".", "reshape", "(", "sampled_candidates", ",", "(", "1", ",", "-", "1", ")", ")", "mask", "=", "F", ".", "broadcast_equal", "(", "label_vec", ",", "sample_vec", ")", "*", "-", "1e37", "pred_sampled", "=", "pred_sampled", "+", "mask", "# subtract log(q)", "expected_count_sampled", "=", "F", ".", "reshape", "(", "expected_count_sampled", ",", "shape", "=", "(", "1", ",", "self", ".", "_num_sampled", ")", ")", "expected_count_true", "=", "expected_count_true", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "pred_true", "=", "pred_true", "-", "F", ".", "log", "(", "expected_count_true", ")", "pred_true", "=", "pred_true", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "pred_sampled", "=", "F", ".", "broadcast_sub", "(", "pred_sampled", ",", "F", ".", "log", "(", "expected_count_sampled", ")", ")", "# pred and new_labels", "# (batch_size, 1+num_sampled)", "pred", "=", "F", ".", "concat", "(", "pred_true", ",", "pred_sampled", ",", "dim", "=", "1", ")", "if", "self", ".", "_sparse_label", ":", "new_label", "=", "F", ".", "zeros_like", "(", "label", ")", "else", ":", "label_vec", "=", "F", ".", "reshape", "(", "label", ",", "(", "-", "1", ",", "1", ")", ")", "new_label_true", "=", "F", ".", "ones_like", "(", "label_vec", ")", "new_label_sampled", "=", "F", ".", "zeros_like", "(", "pred_sampled", ")", "new_label", "=", "F", ".", "Concat", "(", "new_label_true", ",", "new_label_sampled", ",", "dim", "=", "1", ")", "return", "pred", ",", "new_label" ]
Forward computation.
[ "Forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L52-L95
train
dmlc/gluon-nlp
src/gluonnlp/model/sampled_block.py
_SampledDense.hybrid_forward
def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shape=(-1,)) # (num_sampled+batch_size,) ids = F.concat(sampled_candidates, label, dim=0) # lookup weights and biases # (num_sampled+batch_size, dim) w_all = F.Embedding(data=ids, weight=weight, input_dim=self._num_classes, output_dim=self._in_unit, sparse_grad=self._sparse_grad) # (num_sampled+batch_size, 1) b_all = F.take(bias, indices=ids) return self._dense(x, sampled_values, label, w_all, b_all)
python
def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shape=(-1,)) # (num_sampled+batch_size,) ids = F.concat(sampled_candidates, label, dim=0) # lookup weights and biases # (num_sampled+batch_size, dim) w_all = F.Embedding(data=ids, weight=weight, input_dim=self._num_classes, output_dim=self._in_unit, sparse_grad=self._sparse_grad) # (num_sampled+batch_size, 1) b_all = F.take(bias, indices=ids) return self._dense(x, sampled_values, label, w_all, b_all)
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "x", ",", "sampled_values", ",", "label", ",", "weight", ",", "bias", ")", ":", "sampled_candidates", ",", "_", ",", "_", "=", "sampled_values", "# (batch_size,)", "label", "=", "F", ".", "reshape", "(", "label", ",", "shape", "=", "(", "-", "1", ",", ")", ")", "# (num_sampled+batch_size,)", "ids", "=", "F", ".", "concat", "(", "sampled_candidates", ",", "label", ",", "dim", "=", "0", ")", "# lookup weights and biases", "# (num_sampled+batch_size, dim)", "w_all", "=", "F", ".", "Embedding", "(", "data", "=", "ids", ",", "weight", "=", "weight", ",", "input_dim", "=", "self", ".", "_num_classes", ",", "output_dim", "=", "self", ".", "_in_unit", ",", "sparse_grad", "=", "self", ".", "_sparse_grad", ")", "# (num_sampled+batch_size, 1)", "b_all", "=", "F", ".", "take", "(", "bias", ",", "indices", "=", "ids", ")", "return", "self", ".", "_dense", "(", "x", ",", "sampled_values", ",", "label", ",", "w_all", ",", "b_all", ")" ]
Forward computation.
[ "Forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L169-L183
train
dmlc/gluon-nlp
src/gluonnlp/model/sampled_block.py
_SparseSampledDense.forward
def forward(self, x, sampled_values, label): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = label.reshape(shape=(-1,)) # (num_sampled+batch_size,) ids = nd.concat(sampled_candidates, label, dim=0) # lookup weights and biases weight = self.weight.row_sparse_data(ids) bias = self.bias.data(ids.context) # (num_sampled+batch_size, dim) w_all = nd.Embedding(data=ids, weight=weight, **self._kwargs) # (num_sampled+batch_size,) b_all = nd.take(bias, indices=ids) out, new_targets = self._dense(x, sampled_values, label, w_all, b_all) return out, new_targets
python
def forward(self, x, sampled_values, label): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = label.reshape(shape=(-1,)) # (num_sampled+batch_size,) ids = nd.concat(sampled_candidates, label, dim=0) # lookup weights and biases weight = self.weight.row_sparse_data(ids) bias = self.bias.data(ids.context) # (num_sampled+batch_size, dim) w_all = nd.Embedding(data=ids, weight=weight, **self._kwargs) # (num_sampled+batch_size,) b_all = nd.take(bias, indices=ids) out, new_targets = self._dense(x, sampled_values, label, w_all, b_all) return out, new_targets
[ "def", "forward", "(", "self", ",", "x", ",", "sampled_values", ",", "label", ")", ":", "sampled_candidates", ",", "_", ",", "_", "=", "sampled_values", "# (batch_size,)", "label", "=", "label", ".", "reshape", "(", "shape", "=", "(", "-", "1", ",", ")", ")", "# (num_sampled+batch_size,)", "ids", "=", "nd", ".", "concat", "(", "sampled_candidates", ",", "label", ",", "dim", "=", "0", ")", "# lookup weights and biases", "weight", "=", "self", ".", "weight", ".", "row_sparse_data", "(", "ids", ")", "bias", "=", "self", ".", "bias", ".", "data", "(", "ids", ".", "context", ")", "# (num_sampled+batch_size, dim)", "w_all", "=", "nd", ".", "Embedding", "(", "data", "=", "ids", ",", "weight", "=", "weight", ",", "*", "*", "self", ".", "_kwargs", ")", "# (num_sampled+batch_size,)", "b_all", "=", "nd", ".", "take", "(", "bias", ",", "indices", "=", "ids", ")", "out", ",", "new_targets", "=", "self", ".", "_dense", "(", "x", ",", "sampled_values", ",", "label", ",", "w_all", ",", "b_all", ")", "return", "out", ",", "new_targets" ]
Forward computation.
[ "Forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L472-L487
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_extract_and_flatten_nested_structure
def _extract_and_flatten_nested_structure(data, flattened=None): """Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None The container thats holds flattened result. Returns ------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : (optional) list The container thats holds flattened result. It is returned only when the input argument `flattened` is not given. """ if flattened is None: flattened = [] structure = _extract_and_flatten_nested_structure(data, flattened) return structure, flattened if isinstance(data, list): return list(_extract_and_flatten_nested_structure(x, flattened) for x in data) elif isinstance(data, tuple): return tuple(_extract_and_flatten_nested_structure(x, flattened) for x in data) elif isinstance(data, dict): return {k: _extract_and_flatten_nested_structure(v) for k, v in data.items()} elif isinstance(data, (mx.sym.Symbol, mx.nd.NDArray)): flattened.append(data) return len(flattened) - 1 else: raise NotImplementedError
python
def _extract_and_flatten_nested_structure(data, flattened=None): """Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None The container thats holds flattened result. Returns ------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : (optional) list The container thats holds flattened result. It is returned only when the input argument `flattened` is not given. """ if flattened is None: flattened = [] structure = _extract_and_flatten_nested_structure(data, flattened) return structure, flattened if isinstance(data, list): return list(_extract_and_flatten_nested_structure(x, flattened) for x in data) elif isinstance(data, tuple): return tuple(_extract_and_flatten_nested_structure(x, flattened) for x in data) elif isinstance(data, dict): return {k: _extract_and_flatten_nested_structure(v) for k, v in data.items()} elif isinstance(data, (mx.sym.Symbol, mx.nd.NDArray)): flattened.append(data) return len(flattened) - 1 else: raise NotImplementedError
[ "def", "_extract_and_flatten_nested_structure", "(", "data", ",", "flattened", "=", "None", ")", ":", "if", "flattened", "is", "None", ":", "flattened", "=", "[", "]", "structure", "=", "_extract_and_flatten_nested_structure", "(", "data", ",", "flattened", ")", "return", "structure", ",", "flattened", "if", "isinstance", "(", "data", ",", "list", ")", ":", "return", "list", "(", "_extract_and_flatten_nested_structure", "(", "x", ",", "flattened", ")", "for", "x", "in", "data", ")", "elif", "isinstance", "(", "data", ",", "tuple", ")", ":", "return", "tuple", "(", "_extract_and_flatten_nested_structure", "(", "x", ",", "flattened", ")", "for", "x", "in", "data", ")", "elif", "isinstance", "(", "data", ",", "dict", ")", ":", "return", "{", "k", ":", "_extract_and_flatten_nested_structure", "(", "v", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", "}", "elif", "isinstance", "(", "data", ",", "(", "mx", ".", "sym", ".", "Symbol", ",", "mx", ".", "nd", ".", "NDArray", ")", ")", ":", "flattened", ".", "append", "(", "data", ")", "return", "len", "(", "flattened", ")", "-", "1", "else", ":", "raise", "NotImplementedError" ]
Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None The container thats holds flattened result. Returns ------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : (optional) list The container thats holds flattened result. It is returned only when the input argument `flattened` is not given.
[ "Flatten", "the", "structure", "of", "a", "nested", "container", "to", "a", "list", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L88-L119
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_reconstruct_flattened_structure
def _reconstruct_flattened_structure(structure, flattened): """Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None The container thats holds flattened result. Returns ------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container that was flattened. """ if isinstance(structure, list): return list(_reconstruct_flattened_structure(x, flattened) for x in structure) elif isinstance(structure, tuple): return tuple(_reconstruct_flattened_structure(x, flattened) for x in structure) elif isinstance(structure, dict): return {k: _reconstruct_flattened_structure(v, flattened) for k, v in structure.items()} elif isinstance(structure, int): return flattened[structure] else: raise NotImplementedError
python
def _reconstruct_flattened_structure(structure, flattened): """Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None The container thats holds flattened result. Returns ------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container that was flattened. """ if isinstance(structure, list): return list(_reconstruct_flattened_structure(x, flattened) for x in structure) elif isinstance(structure, tuple): return tuple(_reconstruct_flattened_structure(x, flattened) for x in structure) elif isinstance(structure, dict): return {k: _reconstruct_flattened_structure(v, flattened) for k, v in structure.items()} elif isinstance(structure, int): return flattened[structure] else: raise NotImplementedError
[ "def", "_reconstruct_flattened_structure", "(", "structure", ",", "flattened", ")", ":", "if", "isinstance", "(", "structure", ",", "list", ")", ":", "return", "list", "(", "_reconstruct_flattened_structure", "(", "x", ",", "flattened", ")", "for", "x", "in", "structure", ")", "elif", "isinstance", "(", "structure", ",", "tuple", ")", ":", "return", "tuple", "(", "_reconstruct_flattened_structure", "(", "x", ",", "flattened", ")", "for", "x", "in", "structure", ")", "elif", "isinstance", "(", "structure", ",", "dict", ")", ":", "return", "{", "k", ":", "_reconstruct_flattened_structure", "(", "v", ",", "flattened", ")", "for", "k", ",", "v", "in", "structure", ".", "items", "(", ")", "}", "elif", "isinstance", "(", "structure", ",", "int", ")", ":", "return", "flattened", "[", "structure", "]", "else", ":", "raise", "NotImplementedError" ]
Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None The container thats holds flattened result. Returns ------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container that was flattened.
[ "Reconstruct", "the", "flattened", "list", "back", "to", "(", "possibly", ")", "nested", "structure", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L122-L145
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_expand_to_beam_size
def _expand_to_beam_size(data, beam_size, batch_size, state_info=None): """Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when state_info is None, or same as the layout in state_info when it's not None. beam_size : int Beam size batch_size : int Batch size state_info : Nested structure of dictionary, default None. Descriptors for states, usually from decoder's ``state_info()``. When None, this method assumes that the batch axis is the first dimension. Returns ------- new_states : Object that contains NDArrays/Symbols Each NDArray/Symbol should have shape batch_size * beam_size on the batch axis. """ assert not state_info or isinstance(state_info, (type(data), dict)), \ 'data and state_info doesn\'t match, ' \ 'got: {} vs {}.'.format(type(state_info), type(data)) if isinstance(data, list): if not state_info: state_info = [None] * len(data) return [_expand_to_beam_size(d, beam_size, batch_size, s) for d, s in zip(data, state_info)] elif isinstance(data, tuple): if not state_info: state_info = [None] * len(data) state_info = tuple(state_info) return tuple(_expand_to_beam_size(d, beam_size, batch_size, s) for d, s in zip(data, state_info)) elif isinstance(data, dict): if not state_info: state_info = {k: None for k in data.keys()} return {k: _expand_to_beam_size(v, beam_size, batch_size, state_info[k]) for k, v in data.items()} elif isinstance(data, mx.nd.NDArray): if not state_info: batch_axis = 0 else: batch_axis = state_info['__layout__'].find('N') if data.shape[batch_axis] != batch_size: raise ValueError('The batch dimension of all the inner elements in states must be ' '{}, Found shape={}'.format(batch_size, data.shape)) new_shape = list(data.shape) new_shape[batch_axis] = batch_size * beam_size new_shape = tuple(new_shape) return data.expand_dims(batch_axis+1)\ .broadcast_axes(axis=batch_axis+1, size=beam_size)\ .reshape(new_shape) elif isinstance(data, mx.sym.Symbol): if not state_info: batch_axis = 0 else: batch_axis = state_info['__layout__'].find('N') new_shape = (0, ) * batch_axis + (-3, -2) return data.expand_dims(batch_axis+1)\ .broadcast_axes(axis=batch_axis+1, size=beam_size)\ .reshape(new_shape) else: raise NotImplementedError
python
def _expand_to_beam_size(data, beam_size, batch_size, state_info=None): """Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when state_info is None, or same as the layout in state_info when it's not None. beam_size : int Beam size batch_size : int Batch size state_info : Nested structure of dictionary, default None. Descriptors for states, usually from decoder's ``state_info()``. When None, this method assumes that the batch axis is the first dimension. Returns ------- new_states : Object that contains NDArrays/Symbols Each NDArray/Symbol should have shape batch_size * beam_size on the batch axis. """ assert not state_info or isinstance(state_info, (type(data), dict)), \ 'data and state_info doesn\'t match, ' \ 'got: {} vs {}.'.format(type(state_info), type(data)) if isinstance(data, list): if not state_info: state_info = [None] * len(data) return [_expand_to_beam_size(d, beam_size, batch_size, s) for d, s in zip(data, state_info)] elif isinstance(data, tuple): if not state_info: state_info = [None] * len(data) state_info = tuple(state_info) return tuple(_expand_to_beam_size(d, beam_size, batch_size, s) for d, s in zip(data, state_info)) elif isinstance(data, dict): if not state_info: state_info = {k: None for k in data.keys()} return {k: _expand_to_beam_size(v, beam_size, batch_size, state_info[k]) for k, v in data.items()} elif isinstance(data, mx.nd.NDArray): if not state_info: batch_axis = 0 else: batch_axis = state_info['__layout__'].find('N') if data.shape[batch_axis] != batch_size: raise ValueError('The batch dimension of all the inner elements in states must be ' '{}, Found shape={}'.format(batch_size, data.shape)) new_shape = list(data.shape) new_shape[batch_axis] = batch_size * beam_size new_shape = tuple(new_shape) return data.expand_dims(batch_axis+1)\ .broadcast_axes(axis=batch_axis+1, size=beam_size)\ .reshape(new_shape) elif isinstance(data, mx.sym.Symbol): if not state_info: batch_axis = 0 else: batch_axis = state_info['__layout__'].find('N') new_shape = (0, ) * batch_axis + (-3, -2) return data.expand_dims(batch_axis+1)\ .broadcast_axes(axis=batch_axis+1, size=beam_size)\ .reshape(new_shape) else: raise NotImplementedError
[ "def", "_expand_to_beam_size", "(", "data", ",", "beam_size", ",", "batch_size", ",", "state_info", "=", "None", ")", ":", "assert", "not", "state_info", "or", "isinstance", "(", "state_info", ",", "(", "type", "(", "data", ")", ",", "dict", ")", ")", ",", "'data and state_info doesn\\'t match, '", "'got: {} vs {}.'", ".", "format", "(", "type", "(", "state_info", ")", ",", "type", "(", "data", ")", ")", "if", "isinstance", "(", "data", ",", "list", ")", ":", "if", "not", "state_info", ":", "state_info", "=", "[", "None", "]", "*", "len", "(", "data", ")", "return", "[", "_expand_to_beam_size", "(", "d", ",", "beam_size", ",", "batch_size", ",", "s", ")", "for", "d", ",", "s", "in", "zip", "(", "data", ",", "state_info", ")", "]", "elif", "isinstance", "(", "data", ",", "tuple", ")", ":", "if", "not", "state_info", ":", "state_info", "=", "[", "None", "]", "*", "len", "(", "data", ")", "state_info", "=", "tuple", "(", "state_info", ")", "return", "tuple", "(", "_expand_to_beam_size", "(", "d", ",", "beam_size", ",", "batch_size", ",", "s", ")", "for", "d", ",", "s", "in", "zip", "(", "data", ",", "state_info", ")", ")", "elif", "isinstance", "(", "data", ",", "dict", ")", ":", "if", "not", "state_info", ":", "state_info", "=", "{", "k", ":", "None", "for", "k", "in", "data", ".", "keys", "(", ")", "}", "return", "{", "k", ":", "_expand_to_beam_size", "(", "v", ",", "beam_size", ",", "batch_size", ",", "state_info", "[", "k", "]", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", "}", "elif", "isinstance", "(", "data", ",", "mx", ".", "nd", ".", "NDArray", ")", ":", "if", "not", "state_info", ":", "batch_axis", "=", "0", "else", ":", "batch_axis", "=", "state_info", "[", "'__layout__'", "]", ".", "find", "(", "'N'", ")", "if", "data", ".", "shape", "[", "batch_axis", "]", "!=", "batch_size", ":", "raise", "ValueError", "(", "'The batch dimension of all the inner elements in states must be '", "'{}, Found shape={}'", ".", "format", "(", "batch_size", ",", "data", ".", "shape", ")", ")", "new_shape", "=", "list", "(", "data", ".", "shape", ")", "new_shape", "[", "batch_axis", "]", "=", "batch_size", "*", "beam_size", "new_shape", "=", "tuple", "(", "new_shape", ")", "return", "data", ".", "expand_dims", "(", "batch_axis", "+", "1", ")", ".", "broadcast_axes", "(", "axis", "=", "batch_axis", "+", "1", ",", "size", "=", "beam_size", ")", ".", "reshape", "(", "new_shape", ")", "elif", "isinstance", "(", "data", ",", "mx", ".", "sym", ".", "Symbol", ")", ":", "if", "not", "state_info", ":", "batch_axis", "=", "0", "else", ":", "batch_axis", "=", "state_info", "[", "'__layout__'", "]", ".", "find", "(", "'N'", ")", "new_shape", "=", "(", "0", ",", ")", "*", "batch_axis", "+", "(", "-", "3", ",", "-", "2", ")", "return", "data", ".", "expand_dims", "(", "batch_axis", "+", "1", ")", ".", "broadcast_axes", "(", "axis", "=", "batch_axis", "+", "1", ",", "size", "=", "beam_size", ")", ".", "reshape", "(", "new_shape", ")", "else", ":", "raise", "NotImplementedError" ]
Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when state_info is None, or same as the layout in state_info when it's not None. beam_size : int Beam size batch_size : int Batch size state_info : Nested structure of dictionary, default None. Descriptors for states, usually from decoder's ``state_info()``. When None, this method assumes that the batch axis is the first dimension. Returns ------- new_states : Object that contains NDArrays/Symbols Each NDArray/Symbol should have shape batch_size * beam_size on the batch axis.
[ "Tile", "all", "the", "states", "to", "have", "batch_size", "*", "beam_size", "on", "the", "batch", "axis", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L148-L211
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_SamplingStepUpdate.hybrid_forward
def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states): """ Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbol The current valid lengths of the samples outputs: NDArray or Symbol Decoder output (unnormalized) scores of the current step. Shape (batch_size * beam_size, V) scores : NDArray or Symbol The previous scores. Shape (batch_size, beam_size) beam_alive_mask : NDArray or Symbol Shape (batch_size, beam_size) states : nested structure of NDArrays/Symbols Inner NDArrays have shape (batch_size * beam_size, ...) Returns ------- new_samples : NDArray or Symbol The updated samples. Shape (batch_size, beam_size, L + 1) new_valid_length : NDArray or Symbol Valid lengths of the samples. Shape (batch_size, beam_size) new_scores : NDArray or Symbol Shape (batch_size, beam_size) chosen_word_ids : NDArray or Symbol The chosen word ids of the step. Shape (batch_size, beam_size). If it's negative, no word will be appended to the beam. beam_alive_mask : NDArray or Symbol Shape (batch_size, beam_size) new_states : nested structure of NDArrays/Symbols Inner NDArrays have shape (batch_size * beam_size, ...) """ beam_size = self._beam_size # outputs: (batch_size, beam_size, vocab_size) outputs = outputs.reshape(shape=(-4, -1, beam_size, 0)) smoothed_probs = (outputs / self._temperature).softmax(axis=2) log_probs = F.log_softmax(outputs, axis=2).reshape(-3, -1) # (batch_size, beam_size) chosen_word_ids = F.sample_multinomial(smoothed_probs, dtype=np.int32) chosen_word_ids = F.where(beam_alive_mask, chosen_word_ids, -1*F.ones_like(beam_alive_mask)) chosen_word_log_probs = log_probs[mx.nd.arange(log_probs.shape[0]), chosen_word_ids.reshape(-1)].reshape(-4, -1, beam_size) # Don't update for finished beams new_scores = scores + F.where(beam_alive_mask, chosen_word_log_probs, F.zeros_like(chosen_word_log_probs)) new_valid_length = valid_length + beam_alive_mask # Update the samples and vaild_length new_samples = F.concat(samples, chosen_word_ids.expand_dims(2), dim=2) # Update the states new_states = states # Update the alive mask. beam_alive_mask = beam_alive_mask * (chosen_word_ids != self._eos_id) return new_samples, new_valid_length, new_scores,\ chosen_word_ids, beam_alive_mask, new_states
python
def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states): """ Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbol The current valid lengths of the samples outputs: NDArray or Symbol Decoder output (unnormalized) scores of the current step. Shape (batch_size * beam_size, V) scores : NDArray or Symbol The previous scores. Shape (batch_size, beam_size) beam_alive_mask : NDArray or Symbol Shape (batch_size, beam_size) states : nested structure of NDArrays/Symbols Inner NDArrays have shape (batch_size * beam_size, ...) Returns ------- new_samples : NDArray or Symbol The updated samples. Shape (batch_size, beam_size, L + 1) new_valid_length : NDArray or Symbol Valid lengths of the samples. Shape (batch_size, beam_size) new_scores : NDArray or Symbol Shape (batch_size, beam_size) chosen_word_ids : NDArray or Symbol The chosen word ids of the step. Shape (batch_size, beam_size). If it's negative, no word will be appended to the beam. beam_alive_mask : NDArray or Symbol Shape (batch_size, beam_size) new_states : nested structure of NDArrays/Symbols Inner NDArrays have shape (batch_size * beam_size, ...) """ beam_size = self._beam_size # outputs: (batch_size, beam_size, vocab_size) outputs = outputs.reshape(shape=(-4, -1, beam_size, 0)) smoothed_probs = (outputs / self._temperature).softmax(axis=2) log_probs = F.log_softmax(outputs, axis=2).reshape(-3, -1) # (batch_size, beam_size) chosen_word_ids = F.sample_multinomial(smoothed_probs, dtype=np.int32) chosen_word_ids = F.where(beam_alive_mask, chosen_word_ids, -1*F.ones_like(beam_alive_mask)) chosen_word_log_probs = log_probs[mx.nd.arange(log_probs.shape[0]), chosen_word_ids.reshape(-1)].reshape(-4, -1, beam_size) # Don't update for finished beams new_scores = scores + F.where(beam_alive_mask, chosen_word_log_probs, F.zeros_like(chosen_word_log_probs)) new_valid_length = valid_length + beam_alive_mask # Update the samples and vaild_length new_samples = F.concat(samples, chosen_word_ids.expand_dims(2), dim=2) # Update the states new_states = states # Update the alive mask. beam_alive_mask = beam_alive_mask * (chosen_word_ids != self._eos_id) return new_samples, new_valid_length, new_scores,\ chosen_word_ids, beam_alive_mask, new_states
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "samples", ",", "valid_length", ",", "outputs", ",", "scores", ",", "beam_alive_mask", ",", "states", ")", ":", "beam_size", "=", "self", ".", "_beam_size", "# outputs: (batch_size, beam_size, vocab_size)", "outputs", "=", "outputs", ".", "reshape", "(", "shape", "=", "(", "-", "4", ",", "-", "1", ",", "beam_size", ",", "0", ")", ")", "smoothed_probs", "=", "(", "outputs", "/", "self", ".", "_temperature", ")", ".", "softmax", "(", "axis", "=", "2", ")", "log_probs", "=", "F", ".", "log_softmax", "(", "outputs", ",", "axis", "=", "2", ")", ".", "reshape", "(", "-", "3", ",", "-", "1", ")", "# (batch_size, beam_size)", "chosen_word_ids", "=", "F", ".", "sample_multinomial", "(", "smoothed_probs", ",", "dtype", "=", "np", ".", "int32", ")", "chosen_word_ids", "=", "F", ".", "where", "(", "beam_alive_mask", ",", "chosen_word_ids", ",", "-", "1", "*", "F", ".", "ones_like", "(", "beam_alive_mask", ")", ")", "chosen_word_log_probs", "=", "log_probs", "[", "mx", ".", "nd", ".", "arange", "(", "log_probs", ".", "shape", "[", "0", "]", ")", ",", "chosen_word_ids", ".", "reshape", "(", "-", "1", ")", "]", ".", "reshape", "(", "-", "4", ",", "-", "1", ",", "beam_size", ")", "# Don't update for finished beams", "new_scores", "=", "scores", "+", "F", ".", "where", "(", "beam_alive_mask", ",", "chosen_word_log_probs", ",", "F", ".", "zeros_like", "(", "chosen_word_log_probs", ")", ")", "new_valid_length", "=", "valid_length", "+", "beam_alive_mask", "# Update the samples and vaild_length", "new_samples", "=", "F", ".", "concat", "(", "samples", ",", "chosen_word_ids", ".", "expand_dims", "(", "2", ")", ",", "dim", "=", "2", ")", "# Update the states", "new_states", "=", "states", "# Update the alive mask.", "beam_alive_mask", "=", "beam_alive_mask", "*", "(", "chosen_word_ids", "!=", "self", ".", "_eos_id", ")", "return", "new_samples", ",", "new_valid_length", ",", "new_scores", ",", "chosen_word_ids", ",", "beam_alive_mask", ",", "new_states" ]
Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbol The current valid lengths of the samples outputs: NDArray or Symbol Decoder output (unnormalized) scores of the current step. Shape (batch_size * beam_size, V) scores : NDArray or Symbol The previous scores. Shape (batch_size, beam_size) beam_alive_mask : NDArray or Symbol Shape (batch_size, beam_size) states : nested structure of NDArrays/Symbols Inner NDArrays have shape (batch_size * beam_size, ...) Returns ------- new_samples : NDArray or Symbol The updated samples. Shape (batch_size, beam_size, L + 1) new_valid_length : NDArray or Symbol Valid lengths of the samples. Shape (batch_size, beam_size) new_scores : NDArray or Symbol Shape (batch_size, beam_size) chosen_word_ids : NDArray or Symbol The chosen word ids of the step. Shape (batch_size, beam_size). If it's negative, no word will be appended to the beam. beam_alive_mask : NDArray or Symbol Shape (batch_size, beam_size) new_states : nested structure of NDArrays/Symbols Inner NDArrays have shape (batch_size * beam_size, ...)
[ "Parameters", "----------", "F", "samples", ":", "NDArray", "or", "Symbol", "The", "current", "samples", "generated", "by", "beam", "search", ".", "Shape", "(", "batch_size", "beam_size", "L", ")", "valid_length", ":", "NDArray", "or", "Symbol", "The", "current", "valid", "lengths", "of", "the", "samples", "outputs", ":", "NDArray", "or", "Symbol", "Decoder", "output", "(", "unnormalized", ")", "scores", "of", "the", "current", "step", ".", "Shape", "(", "batch_size", "*", "beam_size", "V", ")", "scores", ":", "NDArray", "or", "Symbol", "The", "previous", "scores", ".", "Shape", "(", "batch_size", "beam_size", ")", "beam_alive_mask", ":", "NDArray", "or", "Symbol", "Shape", "(", "batch_size", "beam_size", ")", "states", ":", "nested", "structure", "of", "NDArrays", "/", "Symbols", "Inner", "NDArrays", "have", "shape", "(", "batch_size", "*", "beam_size", "...", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L377-L442
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
HybridBeamSearchSampler.hybrid_forward
def hybrid_forward(self, F, inputs, states): # pylint: disable=arguments-differ """Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or Symbols The initial states of the decoder. Returns ------- samples : NDArray or Symbol Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32. scores : NDArray or Symbol Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are in descending order. valid_length : NDArray or Symbol The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32. """ batch_size = self._batch_size beam_size = self._beam_size vocab_size = self._vocab_size # Tile the states and inputs to have shape (batch_size * beam_size, ...) state_info = self._state_info_func(batch_size) step_input = _expand_to_beam_size(inputs, beam_size=beam_size, batch_size=batch_size).astype(np.int32) states = _expand_to_beam_size(states, beam_size=beam_size, batch_size=batch_size, state_info=state_info) state_structure, states = _extract_and_flatten_nested_structure(states) if beam_size == 1: init_scores = F.zeros(shape=(batch_size, 1)) else: init_scores = F.concat( F.zeros(shape=(batch_size, 1)), F.full(shape=(batch_size, beam_size - 1), val=LARGE_NEGATIVE_FLOAT), dim=1) vocab_size = F.full(shape=(1,), val=vocab_size, dtype=np.int32) batch_shift = F.arange(0, batch_size * beam_size, beam_size, dtype=np.int32) def _loop_cond(_i, _samples, _indices, _step_input, _valid_length, _scores, \ beam_alive_mask, *_states): return F.sum(beam_alive_mask) > 0 def _loop_func(i, samples, indices, step_input, valid_length, scores, \ beam_alive_mask, *states): outputs, new_states = self._decoder( step_input, _reconstruct_flattened_structure(state_structure, states)) step = i + 1 new_samples, new_valid_length, new_scores, \ chosen_word_ids, new_beam_alive_mask, new_new_states = \ self._updater(samples, valid_length, outputs, scores, step.astype(np.float32), beam_alive_mask, _extract_and_flatten_nested_structure(new_states)[-1], vocab_size, batch_shift) new_step_input = F.relu(chosen_word_ids).reshape((-1,)) # We are doing `new_indices = indices[1 : ] + indices[ : 1]` new_indices = F.concat( indices.slice_axis(axis=0, begin=1, end=None), indices.slice_axis(axis=0, begin=0, end=1), dim=0) return [], (step, new_samples, new_indices, new_step_input, new_valid_length, \ new_scores, new_beam_alive_mask) + tuple(new_new_states) _, pad_samples, indices, _, new_valid_length, new_scores, new_beam_alive_mask = \ F.contrib.while_loop( cond=_loop_cond, func=_loop_func, max_iterations=self._max_length, loop_vars=( F.zeros(shape=(1,), dtype=np.int32), # i F.zeros(shape=(batch_size, beam_size, self._max_length), dtype=np.int32), # samples F.arange(start=0, stop=self._max_length, dtype=np.int32), # indices step_input, # step_input F.ones(shape=(batch_size, beam_size), dtype=np.int32), # valid_length init_scores, # scores F.ones(shape=(batch_size, beam_size), dtype=np.int32), # beam_alive_mask ) + tuple(states) )[1][:7] # I hate Python 2 samples = pad_samples.take(indices, axis=2) def _then_func(): new_samples = F.concat( step_input.reshape((batch_size, beam_size, 1)), samples, F.full(shape=(batch_size, beam_size, 1), val=-1, dtype=np.int32), dim=2, name='concat3') new_new_valid_length = new_valid_length return new_samples, new_new_valid_length def _else_func(): final_word = F.where(new_beam_alive_mask, F.full(shape=(batch_size, beam_size), val=self._eos_id, dtype=np.int32), F.full(shape=(batch_size, beam_size), val=-1, dtype=np.int32)) new_samples = F.concat( step_input.reshape((batch_size, beam_size, 1)), samples, final_word.reshape((0, 0, 1)), dim=2) new_new_valid_length = new_valid_length + new_beam_alive_mask return new_samples, new_new_valid_length new_samples, new_new_valid_length = \ F.contrib.cond(F.sum(new_beam_alive_mask) == 0, _then_func, _else_func) return new_samples, new_scores, new_new_valid_length
python
def hybrid_forward(self, F, inputs, states): # pylint: disable=arguments-differ """Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or Symbols The initial states of the decoder. Returns ------- samples : NDArray or Symbol Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32. scores : NDArray or Symbol Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are in descending order. valid_length : NDArray or Symbol The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32. """ batch_size = self._batch_size beam_size = self._beam_size vocab_size = self._vocab_size # Tile the states and inputs to have shape (batch_size * beam_size, ...) state_info = self._state_info_func(batch_size) step_input = _expand_to_beam_size(inputs, beam_size=beam_size, batch_size=batch_size).astype(np.int32) states = _expand_to_beam_size(states, beam_size=beam_size, batch_size=batch_size, state_info=state_info) state_structure, states = _extract_and_flatten_nested_structure(states) if beam_size == 1: init_scores = F.zeros(shape=(batch_size, 1)) else: init_scores = F.concat( F.zeros(shape=(batch_size, 1)), F.full(shape=(batch_size, beam_size - 1), val=LARGE_NEGATIVE_FLOAT), dim=1) vocab_size = F.full(shape=(1,), val=vocab_size, dtype=np.int32) batch_shift = F.arange(0, batch_size * beam_size, beam_size, dtype=np.int32) def _loop_cond(_i, _samples, _indices, _step_input, _valid_length, _scores, \ beam_alive_mask, *_states): return F.sum(beam_alive_mask) > 0 def _loop_func(i, samples, indices, step_input, valid_length, scores, \ beam_alive_mask, *states): outputs, new_states = self._decoder( step_input, _reconstruct_flattened_structure(state_structure, states)) step = i + 1 new_samples, new_valid_length, new_scores, \ chosen_word_ids, new_beam_alive_mask, new_new_states = \ self._updater(samples, valid_length, outputs, scores, step.astype(np.float32), beam_alive_mask, _extract_and_flatten_nested_structure(new_states)[-1], vocab_size, batch_shift) new_step_input = F.relu(chosen_word_ids).reshape((-1,)) # We are doing `new_indices = indices[1 : ] + indices[ : 1]` new_indices = F.concat( indices.slice_axis(axis=0, begin=1, end=None), indices.slice_axis(axis=0, begin=0, end=1), dim=0) return [], (step, new_samples, new_indices, new_step_input, new_valid_length, \ new_scores, new_beam_alive_mask) + tuple(new_new_states) _, pad_samples, indices, _, new_valid_length, new_scores, new_beam_alive_mask = \ F.contrib.while_loop( cond=_loop_cond, func=_loop_func, max_iterations=self._max_length, loop_vars=( F.zeros(shape=(1,), dtype=np.int32), # i F.zeros(shape=(batch_size, beam_size, self._max_length), dtype=np.int32), # samples F.arange(start=0, stop=self._max_length, dtype=np.int32), # indices step_input, # step_input F.ones(shape=(batch_size, beam_size), dtype=np.int32), # valid_length init_scores, # scores F.ones(shape=(batch_size, beam_size), dtype=np.int32), # beam_alive_mask ) + tuple(states) )[1][:7] # I hate Python 2 samples = pad_samples.take(indices, axis=2) def _then_func(): new_samples = F.concat( step_input.reshape((batch_size, beam_size, 1)), samples, F.full(shape=(batch_size, beam_size, 1), val=-1, dtype=np.int32), dim=2, name='concat3') new_new_valid_length = new_valid_length return new_samples, new_new_valid_length def _else_func(): final_word = F.where(new_beam_alive_mask, F.full(shape=(batch_size, beam_size), val=self._eos_id, dtype=np.int32), F.full(shape=(batch_size, beam_size), val=-1, dtype=np.int32)) new_samples = F.concat( step_input.reshape((batch_size, beam_size, 1)), samples, final_word.reshape((0, 0, 1)), dim=2) new_new_valid_length = new_valid_length + new_beam_alive_mask return new_samples, new_new_valid_length new_samples, new_new_valid_length = \ F.contrib.cond(F.sum(new_beam_alive_mask) == 0, _then_func, _else_func) return new_samples, new_scores, new_new_valid_length
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", ")", ":", "# pylint: disable=arguments-differ", "batch_size", "=", "self", ".", "_batch_size", "beam_size", "=", "self", ".", "_beam_size", "vocab_size", "=", "self", ".", "_vocab_size", "# Tile the states and inputs to have shape (batch_size * beam_size, ...)", "state_info", "=", "self", ".", "_state_info_func", "(", "batch_size", ")", "step_input", "=", "_expand_to_beam_size", "(", "inputs", ",", "beam_size", "=", "beam_size", ",", "batch_size", "=", "batch_size", ")", ".", "astype", "(", "np", ".", "int32", ")", "states", "=", "_expand_to_beam_size", "(", "states", ",", "beam_size", "=", "beam_size", ",", "batch_size", "=", "batch_size", ",", "state_info", "=", "state_info", ")", "state_structure", ",", "states", "=", "_extract_and_flatten_nested_structure", "(", "states", ")", "if", "beam_size", "==", "1", ":", "init_scores", "=", "F", ".", "zeros", "(", "shape", "=", "(", "batch_size", ",", "1", ")", ")", "else", ":", "init_scores", "=", "F", ".", "concat", "(", "F", ".", "zeros", "(", "shape", "=", "(", "batch_size", ",", "1", ")", ")", ",", "F", ".", "full", "(", "shape", "=", "(", "batch_size", ",", "beam_size", "-", "1", ")", ",", "val", "=", "LARGE_NEGATIVE_FLOAT", ")", ",", "dim", "=", "1", ")", "vocab_size", "=", "F", ".", "full", "(", "shape", "=", "(", "1", ",", ")", ",", "val", "=", "vocab_size", ",", "dtype", "=", "np", ".", "int32", ")", "batch_shift", "=", "F", ".", "arange", "(", "0", ",", "batch_size", "*", "beam_size", ",", "beam_size", ",", "dtype", "=", "np", ".", "int32", ")", "def", "_loop_cond", "(", "_i", ",", "_samples", ",", "_indices", ",", "_step_input", ",", "_valid_length", ",", "_scores", ",", "beam_alive_mask", ",", "*", "_states", ")", ":", "return", "F", ".", "sum", "(", "beam_alive_mask", ")", ">", "0", "def", "_loop_func", "(", "i", ",", "samples", ",", "indices", ",", "step_input", ",", "valid_length", ",", "scores", ",", "beam_alive_mask", ",", "*", "states", ")", ":", "outputs", ",", "new_states", "=", "self", ".", "_decoder", "(", "step_input", ",", "_reconstruct_flattened_structure", "(", "state_structure", ",", "states", ")", ")", "step", "=", "i", "+", "1", "new_samples", ",", "new_valid_length", ",", "new_scores", ",", "chosen_word_ids", ",", "new_beam_alive_mask", ",", "new_new_states", "=", "self", ".", "_updater", "(", "samples", ",", "valid_length", ",", "outputs", ",", "scores", ",", "step", ".", "astype", "(", "np", ".", "float32", ")", ",", "beam_alive_mask", ",", "_extract_and_flatten_nested_structure", "(", "new_states", ")", "[", "-", "1", "]", ",", "vocab_size", ",", "batch_shift", ")", "new_step_input", "=", "F", ".", "relu", "(", "chosen_word_ids", ")", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "# We are doing `new_indices = indices[1 : ] + indices[ : 1]`", "new_indices", "=", "F", ".", "concat", "(", "indices", ".", "slice_axis", "(", "axis", "=", "0", ",", "begin", "=", "1", ",", "end", "=", "None", ")", ",", "indices", ".", "slice_axis", "(", "axis", "=", "0", ",", "begin", "=", "0", ",", "end", "=", "1", ")", ",", "dim", "=", "0", ")", "return", "[", "]", ",", "(", "step", ",", "new_samples", ",", "new_indices", ",", "new_step_input", ",", "new_valid_length", ",", "new_scores", ",", "new_beam_alive_mask", ")", "+", "tuple", "(", "new_new_states", ")", "_", ",", "pad_samples", ",", "indices", ",", "_", ",", "new_valid_length", ",", "new_scores", ",", "new_beam_alive_mask", "=", "F", ".", "contrib", ".", "while_loop", "(", "cond", "=", "_loop_cond", ",", "func", "=", "_loop_func", ",", "max_iterations", "=", "self", ".", "_max_length", ",", "loop_vars", "=", "(", "F", ".", "zeros", "(", "shape", "=", "(", "1", ",", ")", ",", "dtype", "=", "np", ".", "int32", ")", ",", "# i", "F", ".", "zeros", "(", "shape", "=", "(", "batch_size", ",", "beam_size", ",", "self", ".", "_max_length", ")", ",", "dtype", "=", "np", ".", "int32", ")", ",", "# samples", "F", ".", "arange", "(", "start", "=", "0", ",", "stop", "=", "self", ".", "_max_length", ",", "dtype", "=", "np", ".", "int32", ")", ",", "# indices", "step_input", ",", "# step_input", "F", ".", "ones", "(", "shape", "=", "(", "batch_size", ",", "beam_size", ")", ",", "dtype", "=", "np", ".", "int32", ")", ",", "# valid_length", "init_scores", ",", "# scores", "F", ".", "ones", "(", "shape", "=", "(", "batch_size", ",", "beam_size", ")", ",", "dtype", "=", "np", ".", "int32", ")", ",", "# beam_alive_mask", ")", "+", "tuple", "(", "states", ")", ")", "[", "1", "]", "[", ":", "7", "]", "# I hate Python 2", "samples", "=", "pad_samples", ".", "take", "(", "indices", ",", "axis", "=", "2", ")", "def", "_then_func", "(", ")", ":", "new_samples", "=", "F", ".", "concat", "(", "step_input", ".", "reshape", "(", "(", "batch_size", ",", "beam_size", ",", "1", ")", ")", ",", "samples", ",", "F", ".", "full", "(", "shape", "=", "(", "batch_size", ",", "beam_size", ",", "1", ")", ",", "val", "=", "-", "1", ",", "dtype", "=", "np", ".", "int32", ")", ",", "dim", "=", "2", ",", "name", "=", "'concat3'", ")", "new_new_valid_length", "=", "new_valid_length", "return", "new_samples", ",", "new_new_valid_length", "def", "_else_func", "(", ")", ":", "final_word", "=", "F", ".", "where", "(", "new_beam_alive_mask", ",", "F", ".", "full", "(", "shape", "=", "(", "batch_size", ",", "beam_size", ")", ",", "val", "=", "self", ".", "_eos_id", ",", "dtype", "=", "np", ".", "int32", ")", ",", "F", ".", "full", "(", "shape", "=", "(", "batch_size", ",", "beam_size", ")", ",", "val", "=", "-", "1", ",", "dtype", "=", "np", ".", "int32", ")", ")", "new_samples", "=", "F", ".", "concat", "(", "step_input", ".", "reshape", "(", "(", "batch_size", ",", "beam_size", ",", "1", ")", ")", ",", "samples", ",", "final_word", ".", "reshape", "(", "(", "0", ",", "0", ",", "1", ")", ")", ",", "dim", "=", "2", ")", "new_new_valid_length", "=", "new_valid_length", "+", "new_beam_alive_mask", "return", "new_samples", ",", "new_new_valid_length", "new_samples", ",", "new_new_valid_length", "=", "F", ".", "contrib", ".", "cond", "(", "F", ".", "sum", "(", "new_beam_alive_mask", ")", "==", "0", ",", "_then_func", ",", "_else_func", ")", "return", "new_samples", ",", "new_scores", ",", "new_new_valid_length" ]
Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or Symbols The initial states of the decoder. Returns ------- samples : NDArray or Symbol Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32. scores : NDArray or Symbol Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are in descending order. valid_length : NDArray or Symbol The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32.
[ "Sample", "by", "beam", "search", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L605-L710
train
dmlc/gluon-nlp
src/gluonnlp/model/parameter.py
WeightDropParameter.data
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx """ d = self._check_and_get(self._data, ctx) if self._rate: d = nd.Dropout(d, self._rate, self._mode, self._axes) return d
python
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx """ d = self._check_and_get(self._data, ctx) if self._rate: d = nd.Dropout(d, self._rate, self._mode, self._axes) return d
[ "def", "data", "(", "self", ",", "ctx", "=", "None", ")", ":", "d", "=", "self", ".", "_check_and_get", "(", "self", ".", "_data", ",", "ctx", ")", "if", "self", ".", "_rate", ":", "d", "=", "nd", ".", "Dropout", "(", "d", ",", "self", ".", "_rate", ",", "self", ".", "_mode", ",", "self", ".", "_axes", ")", "return", "d" ]
Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx
[ "Returns", "a", "copy", "of", "this", "parameter", "on", "one", "context", ".", "Must", "have", "been", "initialized", "on", "this", "context", "before", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/parameter.py#L59-L74
train
dmlc/gluon-nlp
src/gluonnlp/model/elmo.py
elmo_2x1024_128_2048cnn_1xhighway
def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. pretrained : bool, default False Whether to load 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 """ predefined_args = {'rnn_type': 'lstmpc', 'output_size': 128, 'filters': [[1, 32], [2, 32], [3, 64], [4, 128], [5, 256], [6, 512], [7, 1024]], 'char_embed_size': 16, 'num_highway': 1, 'conv_layer_activation': 'relu', 'max_chars_per_token': 50, 'input_size': 128, 'hidden_size': 1024, 'proj_size': 128, 'num_layers': 2, 'cell_clip': 3, 'proj_clip': 3, 'skip_connection': True} assert all((k not in kwargs) for k in predefined_args), \ 'Cannot override predefined model settings.' predefined_args.update(kwargs) return _get_elmo_model(ELMoBiLM, 'elmo_2x1024_128_2048cnn_1xhighway', dataset_name, pretrained, ctx, root, **predefined_args)
python
def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. pretrained : bool, default False Whether to load 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 """ predefined_args = {'rnn_type': 'lstmpc', 'output_size': 128, 'filters': [[1, 32], [2, 32], [3, 64], [4, 128], [5, 256], [6, 512], [7, 1024]], 'char_embed_size': 16, 'num_highway': 1, 'conv_layer_activation': 'relu', 'max_chars_per_token': 50, 'input_size': 128, 'hidden_size': 1024, 'proj_size': 128, 'num_layers': 2, 'cell_clip': 3, 'proj_clip': 3, 'skip_connection': True} assert all((k not in kwargs) for k in predefined_args), \ 'Cannot override predefined model settings.' predefined_args.update(kwargs) return _get_elmo_model(ELMoBiLM, 'elmo_2x1024_128_2048cnn_1xhighway', dataset_name, pretrained, ctx, root, **predefined_args)
[ "def", "elmo_2x1024_128_2048cnn_1xhighway", "(", "dataset_name", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ")", ",", "*", "*", "kwargs", ")", ":", "predefined_args", "=", "{", "'rnn_type'", ":", "'lstmpc'", ",", "'output_size'", ":", "128", ",", "'filters'", ":", "[", "[", "1", ",", "32", "]", ",", "[", "2", ",", "32", "]", ",", "[", "3", ",", "64", "]", ",", "[", "4", ",", "128", "]", ",", "[", "5", ",", "256", "]", ",", "[", "6", ",", "512", "]", ",", "[", "7", ",", "1024", "]", "]", ",", "'char_embed_size'", ":", "16", ",", "'num_highway'", ":", "1", ",", "'conv_layer_activation'", ":", "'relu'", ",", "'max_chars_per_token'", ":", "50", ",", "'input_size'", ":", "128", ",", "'hidden_size'", ":", "1024", ",", "'proj_size'", ":", "128", ",", "'num_layers'", ":", "2", ",", "'cell_clip'", ":", "3", ",", "'proj_clip'", ":", "3", ",", "'skip_connection'", ":", "True", "}", "assert", "all", "(", "(", "k", "not", "in", "kwargs", ")", "for", "k", "in", "predefined_args", ")", ",", "'Cannot override predefined model settings.'", "predefined_args", ".", "update", "(", "kwargs", ")", "return", "_get_elmo_model", "(", "ELMoBiLM", ",", "'elmo_2x1024_128_2048cnn_1xhighway'", ",", "dataset_name", ",", "pretrained", ",", "ctx", ",", "root", ",", "*", "*", "predefined_args", ")" ]
r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. pretrained : bool, default False Whether to load 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
[ "r", "ELMo", "2", "-", "layer", "BiLSTM", "with", "1024", "hidden", "units", "128", "projection", "size", "1", "highway", "layer", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L308-L349
train
dmlc/gluon-nlp
src/gluonnlp/model/elmo.py
ELMoCharacterEncoder.hybrid_forward
def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. Returns ------- token_embedding : NDArray Shape (batch_size, sequence_length, embedding_size) with context insensitive token representations. """ # the character id embedding # (batch_size * sequence_length, max_chars_per_token, embed_dim) character_embedding = self._char_embedding(inputs.reshape((-1, self._max_chars_per_token))) character_embedding = F.transpose(character_embedding, axes=(1, 0, 2)) token_embedding = self._convolutions(character_embedding) out_shape_ref = inputs.slice_axis(axis=-1, begin=0, end=1) out_shape_ref = out_shape_ref.broadcast_axes(axis=(2,), size=(self._output_size)) return token_embedding.reshape_like(out_shape_ref)
python
def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. Returns ------- token_embedding : NDArray Shape (batch_size, sequence_length, embedding_size) with context insensitive token representations. """ # the character id embedding # (batch_size * sequence_length, max_chars_per_token, embed_dim) character_embedding = self._char_embedding(inputs.reshape((-1, self._max_chars_per_token))) character_embedding = F.transpose(character_embedding, axes=(1, 0, 2)) token_embedding = self._convolutions(character_embedding) out_shape_ref = inputs.slice_axis(axis=-1, begin=0, end=1) out_shape_ref = out_shape_ref.broadcast_axes(axis=(2,), size=(self._output_size)) return token_embedding.reshape_like(out_shape_ref)
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ")", ":", "# pylint: disable=arguments-differ", "# the character id embedding", "# (batch_size * sequence_length, max_chars_per_token, embed_dim)", "character_embedding", "=", "self", ".", "_char_embedding", "(", "inputs", ".", "reshape", "(", "(", "-", "1", ",", "self", ".", "_max_chars_per_token", ")", ")", ")", "character_embedding", "=", "F", ".", "transpose", "(", "character_embedding", ",", "axes", "=", "(", "1", ",", "0", ",", "2", ")", ")", "token_embedding", "=", "self", ".", "_convolutions", "(", "character_embedding", ")", "out_shape_ref", "=", "inputs", ".", "slice_axis", "(", "axis", "=", "-", "1", ",", "begin", "=", "0", ",", "end", "=", "1", ")", "out_shape_ref", "=", "out_shape_ref", ".", "broadcast_axes", "(", "axis", "=", "(", "2", ",", ")", ",", "size", "=", "(", "self", ".", "_output_size", ")", ")", "return", "token_embedding", ".", "reshape_like", "(", "out_shape_ref", ")" ]
Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. Returns ------- token_embedding : NDArray Shape (batch_size, sequence_length, embedding_size) with context insensitive token representations.
[ "Compute", "context", "insensitive", "token", "embeddings", "for", "ELMo", "representations", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L103-L131
train
dmlc/gluon-nlp
src/gluonnlp/model/elmo.py
ELMoBiLM.hybrid_forward
def hybrid_forward(self, F, inputs, states=None, mask=None): # pylint: disable=arguments-differ """ Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward layer states, while the second is the states from backward layer. Each is a list of states for each layer. The state of each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). mask : NDArray Shape (batch_size, sequence_length) with sequence mask. Returns ------- output : list of NDArray A list of activations at each layer of the network, each of shape (batch_size, sequence_length, embedding_size) states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward layer states, while the second is the states from backward layer. Each is a list of states for each layer. The state of each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). """ type_representation = self._elmo_char_encoder(inputs) type_representation = type_representation.transpose(axes=(1, 0, 2)) lstm_outputs, states = self._elmo_lstm(type_representation, states, mask) lstm_outputs = lstm_outputs.transpose(axes=(0, 2, 1, 3)) type_representation = type_representation.transpose(axes=(1, 0, 2)) # Prepare the output. The first layer is duplicated. output = F.concat(*[type_representation, type_representation], dim=-1) if mask is not None: output = output * mask.expand_dims(axis=-1) output = [output] output.extend([layer_activations.squeeze(axis=0) for layer_activations in F.split(lstm_outputs, self._num_layers, axis=0)]) return output, states
python
def hybrid_forward(self, F, inputs, states=None, mask=None): # pylint: disable=arguments-differ """ Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward layer states, while the second is the states from backward layer. Each is a list of states for each layer. The state of each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). mask : NDArray Shape (batch_size, sequence_length) with sequence mask. Returns ------- output : list of NDArray A list of activations at each layer of the network, each of shape (batch_size, sequence_length, embedding_size) states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward layer states, while the second is the states from backward layer. Each is a list of states for each layer. The state of each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). """ type_representation = self._elmo_char_encoder(inputs) type_representation = type_representation.transpose(axes=(1, 0, 2)) lstm_outputs, states = self._elmo_lstm(type_representation, states, mask) lstm_outputs = lstm_outputs.transpose(axes=(0, 2, 1, 3)) type_representation = type_representation.transpose(axes=(1, 0, 2)) # Prepare the output. The first layer is duplicated. output = F.concat(*[type_representation, type_representation], dim=-1) if mask is not None: output = output * mask.expand_dims(axis=-1) output = [output] output.extend([layer_activations.squeeze(axis=0) for layer_activations in F.split(lstm_outputs, self._num_layers, axis=0)]) return output, states
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", "=", "None", ",", "mask", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "type_representation", "=", "self", ".", "_elmo_char_encoder", "(", "inputs", ")", "type_representation", "=", "type_representation", ".", "transpose", "(", "axes", "=", "(", "1", ",", "0", ",", "2", ")", ")", "lstm_outputs", ",", "states", "=", "self", ".", "_elmo_lstm", "(", "type_representation", ",", "states", ",", "mask", ")", "lstm_outputs", "=", "lstm_outputs", ".", "transpose", "(", "axes", "=", "(", "0", ",", "2", ",", "1", ",", "3", ")", ")", "type_representation", "=", "type_representation", ".", "transpose", "(", "axes", "=", "(", "1", ",", "0", ",", "2", ")", ")", "# Prepare the output. The first layer is duplicated.", "output", "=", "F", ".", "concat", "(", "*", "[", "type_representation", ",", "type_representation", "]", ",", "dim", "=", "-", "1", ")", "if", "mask", "is", "not", "None", ":", "output", "=", "output", "*", "mask", ".", "expand_dims", "(", "axis", "=", "-", "1", ")", "output", "=", "[", "output", "]", "output", ".", "extend", "(", "[", "layer_activations", ".", "squeeze", "(", "axis", "=", "0", ")", "for", "layer_activations", "in", "F", ".", "split", "(", "lstm_outputs", ",", "self", ".", "_num_layers", ",", "axis", "=", "0", ")", "]", ")", "return", "output", ",", "states" ]
Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward layer states, while the second is the states from backward layer. Each is a list of states for each layer. The state of each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size). mask : NDArray Shape (batch_size, sequence_length) with sequence mask. Returns ------- output : list of NDArray A list of activations at each layer of the network, each of shape (batch_size, sequence_length, embedding_size) states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward layer states, while the second is the states from backward layer. Each is a list of states for each layer. The state of each layer has a list of two initial tensors with shape (batch_size, proj_size) and (batch_size, hidden_size).
[ "Parameters", "----------", "inputs", ":", "NDArray", "Shape", "(", "batch_size", "sequence_length", "max_character_per_token", ")", "of", "character", "ids", "representing", "the", "current", "batch", ".", "states", ":", "(", "list", "of", "list", "of", "NDArray", "list", "of", "list", "of", "NDArray", ")", "The", "states", ".", "First", "tuple", "element", "is", "the", "forward", "layer", "states", "while", "the", "second", "is", "the", "states", "from", "backward", "layer", ".", "Each", "is", "a", "list", "of", "states", "for", "each", "layer", ".", "The", "state", "of", "each", "layer", "has", "a", "list", "of", "two", "initial", "tensors", "with", "shape", "(", "batch_size", "proj_size", ")", "and", "(", "batch_size", "hidden_size", ")", ".", "mask", ":", "NDArray", "Shape", "(", "batch_size", "sequence_length", ")", "with", "sequence", "mask", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L243-L284
train
dmlc/gluon-nlp
src/gluonnlp/model/language_model.py
awd_lstm_lm_1150
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. 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 73.32/69.74 ppl on Val and Test of wikitext-2 respectively. vocab : gluonnlp.Vocab or None, default None Vocab 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': 400, 'hidden_size': 1150, 'mode': 'lstm', 'num_layers': 3, 'tie_weights': True, 'dropout': 0.4, 'weight_drop': 0.5, 'drop_h': 0.2, 'drop_i': 0.65, 'drop_e': 0.1} mutable_args = frozenset(['dropout', 'weight_drop', 'drop_h', 'drop_i', 'drop_e']) 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(AWDRNN, 'awd_lstm_lm_1150', dataset_name, vocab, pretrained, ctx, root, **predefined_args)
python
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. 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 73.32/69.74 ppl on Val and Test of wikitext-2 respectively. vocab : gluonnlp.Vocab or None, default None Vocab 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': 400, 'hidden_size': 1150, 'mode': 'lstm', 'num_layers': 3, 'tie_weights': True, 'dropout': 0.4, 'weight_drop': 0.5, 'drop_h': 0.2, 'drop_i': 0.65, 'drop_e': 0.1} mutable_args = frozenset(['dropout', 'weight_drop', 'drop_h', 'drop_i', 'drop_e']) 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(AWDRNN, 'awd_lstm_lm_1150', dataset_name, vocab, pretrained, ctx, root, **predefined_args)
[ "def", "awd_lstm_lm_1150", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ")", ",", "*", "*", "kwargs", ")", ":", "predefined_args", "=", "{", "'embed_size'", ":", "400", ",", "'hidden_size'", ":", "1150", ",", "'mode'", ":", "'lstm'", ",", "'num_layers'", ":", "3", ",", "'tie_weights'", ":", "True", ",", "'dropout'", ":", "0.4", ",", "'weight_drop'", ":", "0.5", ",", "'drop_h'", ":", "0.2", ",", "'drop_i'", ":", "0.65", ",", "'drop_e'", ":", "0.1", "}", "mutable_args", "=", "frozenset", "(", "[", "'dropout'", ",", "'weight_drop'", ",", "'drop_h'", ",", "'drop_i'", ",", "'drop_e'", "]", ")", "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", "(", "AWDRNN", ",", "'awd_lstm_lm_1150'", ",", "dataset_name", ",", "vocab", ",", "pretrained", ",", "ctx", ",", "root", ",", "*", "*", "predefined_args", ")" ]
r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are '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 73.32/69.74 ppl on Val and Test of wikitext-2 respectively. vocab : gluonnlp.Vocab or None, default None Vocab 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", "3", "-", "layer", "LSTM", "language", "model", "with", "weight", "-", "drop", "variational", "dropout", "and", "tied", "weights", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L181-L226
train