id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32,500 | 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",
")",
... | 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 |
32,501 | 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",... | 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 |
32,502 | 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",
"=",
"l... | 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 |
32,503 | 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",
... | 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 |
32,504 | 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",
... | 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 |
32,505 | 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 |
32,506 | 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",
"=",... | 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 |
32,507 | 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",
"="... | 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 |
32,508 | 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 fun... | 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 |
32,509 | 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... | 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 |
32,510 | 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",
")",
":",
... | 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 |
32,511 | 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",
".",
"_... | 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 |
32,512 | 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 |
32,513 | 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",
",... | 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 |
32,514 | 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",
"(",
")",
",",... | 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 |
32,515 | 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",
"=",
"[",
"]",
... | 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 |
32,516 | 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",
".",
"forw... | 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 |
32,517 | 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",
"=",
"unk... | 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 |
32,518 | 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",
"[",
"... | 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 |
32,519 | 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_... | 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 |
32,520 | 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",
",",
"(",
... | 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 |
32,521 | 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",
"... | 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 |
32,522 | 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",
"(",
"(",
... | 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... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/utils/parameter.py#L28-L97 |
32,523 | 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",
",",
... | forward backward implementation | [
"forward",
"backward",
"implementation"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining.py#L77-L90 |
32,524 | 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",
".",
... | 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 |
32,525 | 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",
"]",
",",
"s... | 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 |
32,526 | 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",
... | 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 |
32,527 | 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",
"(",
... | 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 |
32,528 | 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 |
32,529 | 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 |
32,530 | 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... | 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 |
32,531 | 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... | 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 |
32,532 | 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",
... | 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 |
32,533 | 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",
"... | 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 |
32,534 | 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",
".",
... | 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 |
32,535 | 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",
"(... | 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 |
32,536 | 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 |
32,537 | 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",
... | 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 |
32,538 | 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"... | 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 |
32,539 | 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... | 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 |
32,540 | 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",
",",
"*",... | 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 |
32,541 | 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",
"embe... | 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 |
32,542 | 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.seria... | 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 |
32,543 | 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_... | 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 |
32,544 | 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",
"[",
... | 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 |
32,545 | 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"... | 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 |
32,546 | 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",
... | 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 |
32,547 | 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",
"(",
"... | 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 |
32,548 | 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",
",... | 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 |
32,549 | 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",
",",
"cel... | 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 |
32,550 | 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",
"... | 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 |
32,551 | 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",
")",
... | 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 |
32,552 | 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",
".",
"... | 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 |
32,553 | 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'",
... | 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 |
32,554 | 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'... | 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 |
32,555 | dmlc/gluon-nlp | src/gluonnlp/model/language_model.py | standard_lstm_lm_200 | def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Standard 2-layer LSTM language model with tied embedding and output weights.
Both embedding and hidden dimensions are 200.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
The pre-trained model achieves 108.25/102.26 ppl on Val and Test of wikitext-2 respectively.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
Returns
-------
gluon.Block, gluonnlp.Vocab
"""
predefined_args = {'embed_size': 200,
'hidden_size': 200,
'mode': 'lstm',
'num_layers': 2,
'tie_weights': True,
'dropout': 0.2}
mutable_args = ['dropout']
assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \
'Cannot override predefined model settings.'
predefined_args.update(kwargs)
return _get_rnn_model(StandardRNN, 'standard_lstm_lm_200', dataset_name, vocab, pretrained,
ctx, root, **predefined_args) | python | def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Standard 2-layer LSTM language model with tied embedding and output weights.
Both embedding and hidden dimensions are 200.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
The pre-trained model achieves 108.25/102.26 ppl on Val and Test of wikitext-2 respectively.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
Returns
-------
gluon.Block, gluonnlp.Vocab
"""
predefined_args = {'embed_size': 200,
'hidden_size': 200,
'mode': 'lstm',
'num_layers': 2,
'tie_weights': True,
'dropout': 0.2}
mutable_args = ['dropout']
assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \
'Cannot override predefined model settings.'
predefined_args.update(kwargs)
return _get_rnn_model(StandardRNN, 'standard_lstm_lm_200', dataset_name, vocab, pretrained,
ctx, root, **predefined_args) | [
"def",
"standard_lstm_lm_200",
"(",
"dataset_name",
"=",
"None",
",",
"vocab",
"=",
"None",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'mod... | r"""Standard 2-layer LSTM language model with tied embedding and output weights.
Both embedding and hidden dimensions are 200.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
The pre-trained model achieves 108.25/102.26 ppl on Val and Test of wikitext-2 respectively.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
Returns
-------
gluon.Block, gluonnlp.Vocab | [
"r",
"Standard",
"2",
"-",
"layer",
"LSTM",
"language",
"model",
"with",
"tied",
"embedding",
"and",
"output",
"weights",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L276-L317 |
32,556 | dmlc/gluon-nlp | src/gluonnlp/model/language_model.py | big_rnn_lm_2048_512 | def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Big 1-layer LSTMP language model.
Both embedding and projection size are 512. Hidden size is 2048.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'gbw'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
The pre-trained model achieves 44.05 ppl on Test of GBW dataset.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
Returns
-------
gluon.Block, gluonnlp.Vocab
"""
predefined_args = {'embed_size': 512,
'hidden_size': 2048,
'projection_size': 512,
'num_layers': 1,
'embed_dropout': 0.1,
'encode_dropout': 0.1}
mutable_args = ['embed_dropout', 'encode_dropout']
assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \
'Cannot override predefined model settings.'
predefined_args.update(kwargs)
return _get_rnn_model(BigRNN, 'big_rnn_lm_2048_512', dataset_name, vocab, pretrained,
ctx, root, **predefined_args) | python | def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Big 1-layer LSTMP language model.
Both embedding and projection size are 512. Hidden size is 2048.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'gbw'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
The pre-trained model achieves 44.05 ppl on Test of GBW dataset.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
Returns
-------
gluon.Block, gluonnlp.Vocab
"""
predefined_args = {'embed_size': 512,
'hidden_size': 2048,
'projection_size': 512,
'num_layers': 1,
'embed_dropout': 0.1,
'encode_dropout': 0.1}
mutable_args = ['embed_dropout', 'encode_dropout']
assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \
'Cannot override predefined model settings.'
predefined_args.update(kwargs)
return _get_rnn_model(BigRNN, 'big_rnn_lm_2048_512', dataset_name, vocab, pretrained,
ctx, root, **predefined_args) | [
"def",
"big_rnn_lm_2048_512",
"(",
"dataset_name",
"=",
"None",
",",
"vocab",
"=",
"None",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'mode... | r"""Big 1-layer LSTMP language model.
Both embedding and projection size are 512. Hidden size is 2048.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'gbw'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
The pre-trained model achieves 44.05 ppl on Test of GBW dataset.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
Returns
-------
gluon.Block, gluonnlp.Vocab | [
"r",
"Big",
"1",
"-",
"layer",
"LSTMP",
"language",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L512-L553 |
32,557 | dmlc/gluon-nlp | src/gluonnlp/model/seq2seq_encoder_decoder.py | _get_cell_type | def _get_cell_type(cell_type):
"""Get the object type of the cell by parsing the input
Parameters
----------
cell_type : str or type
Returns
-------
cell_constructor: type
The constructor of the RNNCell
"""
if isinstance(cell_type, str):
if cell_type == 'lstm':
return rnn.LSTMCell
elif cell_type == 'gru':
return rnn.GRUCell
elif cell_type == 'relu_rnn':
return partial(rnn.RNNCell, activation='relu')
elif cell_type == 'tanh_rnn':
return partial(rnn.RNNCell, activation='tanh')
else:
raise NotImplementedError
else:
return cell_type | python | def _get_cell_type(cell_type):
"""Get the object type of the cell by parsing the input
Parameters
----------
cell_type : str or type
Returns
-------
cell_constructor: type
The constructor of the RNNCell
"""
if isinstance(cell_type, str):
if cell_type == 'lstm':
return rnn.LSTMCell
elif cell_type == 'gru':
return rnn.GRUCell
elif cell_type == 'relu_rnn':
return partial(rnn.RNNCell, activation='relu')
elif cell_type == 'tanh_rnn':
return partial(rnn.RNNCell, activation='tanh')
else:
raise NotImplementedError
else:
return cell_type | [
"def",
"_get_cell_type",
"(",
"cell_type",
")",
":",
"if",
"isinstance",
"(",
"cell_type",
",",
"str",
")",
":",
"if",
"cell_type",
"==",
"'lstm'",
":",
"return",
"rnn",
".",
"LSTMCell",
"elif",
"cell_type",
"==",
"'gru'",
":",
"return",
"rnn",
".",
"GRU... | Get the object type of the cell by parsing the input
Parameters
----------
cell_type : str or type
Returns
-------
cell_constructor: type
The constructor of the RNNCell | [
"Get",
"the",
"object",
"type",
"of",
"the",
"cell",
"by",
"parsing",
"the",
"input"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/seq2seq_encoder_decoder.py#L30-L54 |
32,558 | dmlc/gluon-nlp | src/gluonnlp/data/batchify/embedding.py | _get_context | def _get_context(center_idx, sentence_boundaries, window_size,
random_window_size, seed):
"""Compute the context with respect to a center word in a sentence.
Takes an numpy array of sentences boundaries.
"""
random.seed(seed + center_idx)
sentence_index = np.searchsorted(sentence_boundaries, center_idx)
sentence_start, sentence_end = _get_sentence_start_end(
sentence_boundaries, sentence_index)
if random_window_size:
window_size = random.randint(1, window_size)
start_idx = max(sentence_start, center_idx - window_size)
end_idx = min(sentence_end, center_idx + window_size + 1)
if start_idx != center_idx and center_idx + 1 != end_idx:
context = np.concatenate((np.arange(start_idx, center_idx),
np.arange(center_idx + 1, end_idx)))
elif start_idx != center_idx:
context = np.arange(start_idx, center_idx)
elif center_idx + 1 != end_idx:
context = np.arange(center_idx + 1, end_idx)
else:
context = None
return context | python | def _get_context(center_idx, sentence_boundaries, window_size,
random_window_size, seed):
"""Compute the context with respect to a center word in a sentence.
Takes an numpy array of sentences boundaries.
"""
random.seed(seed + center_idx)
sentence_index = np.searchsorted(sentence_boundaries, center_idx)
sentence_start, sentence_end = _get_sentence_start_end(
sentence_boundaries, sentence_index)
if random_window_size:
window_size = random.randint(1, window_size)
start_idx = max(sentence_start, center_idx - window_size)
end_idx = min(sentence_end, center_idx + window_size + 1)
if start_idx != center_idx and center_idx + 1 != end_idx:
context = np.concatenate((np.arange(start_idx, center_idx),
np.arange(center_idx + 1, end_idx)))
elif start_idx != center_idx:
context = np.arange(start_idx, center_idx)
elif center_idx + 1 != end_idx:
context = np.arange(center_idx + 1, end_idx)
else:
context = None
return context | [
"def",
"_get_context",
"(",
"center_idx",
",",
"sentence_boundaries",
",",
"window_size",
",",
"random_window_size",
",",
"seed",
")",
":",
"random",
".",
"seed",
"(",
"seed",
"+",
"center_idx",
")",
"sentence_index",
"=",
"np",
".",
"searchsorted",
"(",
"sent... | Compute the context with respect to a center word in a sentence.
Takes an numpy array of sentences boundaries. | [
"Compute",
"the",
"context",
"with",
"respect",
"to",
"a",
"center",
"word",
"in",
"a",
"sentence",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/batchify/embedding.py#L246-L274 |
32,559 | dmlc/gluon-nlp | scripts/sentiment_analysis/text_cnn.py | model | def model(dropout, vocab, model_mode, output_size):
"""Construct the model."""
textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\
output_size=output_size)
textCNN.hybridize()
return textCNN | python | def model(dropout, vocab, model_mode, output_size):
"""Construct the model."""
textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\
output_size=output_size)
textCNN.hybridize()
return textCNN | [
"def",
"model",
"(",
"dropout",
",",
"vocab",
",",
"model_mode",
",",
"output_size",
")",
":",
"textCNN",
"=",
"SentimentNet",
"(",
"dropout",
"=",
"dropout",
",",
"vocab_size",
"=",
"len",
"(",
"vocab",
")",
",",
"model_mode",
"=",
"model_mode",
",",
"o... | Construct the model. | [
"Construct",
"the",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L40-L46 |
32,560 | dmlc/gluon-nlp | scripts/sentiment_analysis/text_cnn.py | init | def init(textCNN, vocab, model_mode, context, lr):
"""Initialize parameters."""
textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)
if model_mode != 'rand':
textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'multichannel':
textCNN.embedding_extend.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'static' or model_mode == 'multichannel':
# Parameters of textCNN.embedding are not updated during training.
textCNN.embedding.collect_params().setattr('grad_req', 'null')
trainer = gluon.Trainer(textCNN.collect_params(), 'adam', {'learning_rate': lr})
return textCNN, trainer | python | def init(textCNN, vocab, model_mode, context, lr):
"""Initialize parameters."""
textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)
if model_mode != 'rand':
textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'multichannel':
textCNN.embedding_extend.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'static' or model_mode == 'multichannel':
# Parameters of textCNN.embedding are not updated during training.
textCNN.embedding.collect_params().setattr('grad_req', 'null')
trainer = gluon.Trainer(textCNN.collect_params(), 'adam', {'learning_rate': lr})
return textCNN, trainer | [
"def",
"init",
"(",
"textCNN",
",",
"vocab",
",",
"model_mode",
",",
"context",
",",
"lr",
")",
":",
"textCNN",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
")",
",",
"ctx",
"=",
"context",
",",
"force_reinit",
"=",
"True",
")",
"... | Initialize parameters. | [
"Initialize",
"parameters",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L48-L60 |
32,561 | dmlc/gluon-nlp | scripts/bert/bert_qa_dataset.py | preprocess_dataset | def preprocess_dataset(dataset, transform, num_workers=8):
"""Use multiprocessing to perform transform for dataset.
Parameters
----------
dataset: dataset-like object
Source dataset.
transform: callable
Transformer function.
num_workers: int, default 8
The number of multiprocessing workers to use for data preprocessing.
"""
worker_fn = partial(_worker_fn, transform=transform)
start = time.time()
pool = mp.Pool(num_workers)
dataset_transform = []
dataset_len = []
for data in pool.map(worker_fn, dataset):
if data:
for _data in data:
dataset_transform.append(_data[:-1])
dataset_len.append(_data[-1])
dataset = SimpleDataset(dataset_transform).transform(
lambda x: (x[0], x[1], x[2], x[3], x[4], x[5]))
end = time.time()
pool.close()
print('Done! Transform dataset costs %.2f seconds.' % (end-start))
return dataset, dataset_len | python | def preprocess_dataset(dataset, transform, num_workers=8):
"""Use multiprocessing to perform transform for dataset.
Parameters
----------
dataset: dataset-like object
Source dataset.
transform: callable
Transformer function.
num_workers: int, default 8
The number of multiprocessing workers to use for data preprocessing.
"""
worker_fn = partial(_worker_fn, transform=transform)
start = time.time()
pool = mp.Pool(num_workers)
dataset_transform = []
dataset_len = []
for data in pool.map(worker_fn, dataset):
if data:
for _data in data:
dataset_transform.append(_data[:-1])
dataset_len.append(_data[-1])
dataset = SimpleDataset(dataset_transform).transform(
lambda x: (x[0], x[1], x[2], x[3], x[4], x[5]))
end = time.time()
pool.close()
print('Done! Transform dataset costs %.2f seconds.' % (end-start))
return dataset, dataset_len | [
"def",
"preprocess_dataset",
"(",
"dataset",
",",
"transform",
",",
"num_workers",
"=",
"8",
")",
":",
"worker_fn",
"=",
"partial",
"(",
"_worker_fn",
",",
"transform",
"=",
"transform",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"pool",
"=",
"mp"... | Use multiprocessing to perform transform for dataset.
Parameters
----------
dataset: dataset-like object
Source dataset.
transform: callable
Transformer function.
num_workers: int, default 8
The number of multiprocessing workers to use for data preprocessing. | [
"Use",
"multiprocessing",
"to",
"perform",
"transform",
"for",
"dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_dataset.py#L56-L86 |
32,562 | dmlc/gluon-nlp | src/gluonnlp/model/attention_cell.py | _masked_softmax | def _masked_softmax(F, att_score, mask, dtype):
"""Ignore the masked elements when calculating the softmax
Parameters
----------
F : symbol or ndarray
att_score : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
mask : Symbol or NDArray or None
Shape (batch_size, query_length, memory_length)
Returns
-------
att_weights : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
"""
if mask is not None:
# Fill in the masked scores with a very small value
neg = -1e4 if np.dtype(dtype) == np.float16 else -1e18
att_score = F.where(mask, att_score, neg * F.ones_like(att_score))
att_weights = F.softmax(att_score, axis=-1) * mask
else:
att_weights = F.softmax(att_score, axis=-1)
return att_weights | python | def _masked_softmax(F, att_score, mask, dtype):
"""Ignore the masked elements when calculating the softmax
Parameters
----------
F : symbol or ndarray
att_score : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
mask : Symbol or NDArray or None
Shape (batch_size, query_length, memory_length)
Returns
-------
att_weights : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
"""
if mask is not None:
# Fill in the masked scores with a very small value
neg = -1e4 if np.dtype(dtype) == np.float16 else -1e18
att_score = F.where(mask, att_score, neg * F.ones_like(att_score))
att_weights = F.softmax(att_score, axis=-1) * mask
else:
att_weights = F.softmax(att_score, axis=-1)
return att_weights | [
"def",
"_masked_softmax",
"(",
"F",
",",
"att_score",
",",
"mask",
",",
"dtype",
")",
":",
"if",
"mask",
"is",
"not",
"None",
":",
"# Fill in the masked scores with a very small value",
"neg",
"=",
"-",
"1e4",
"if",
"np",
".",
"dtype",
"(",
"dtype",
")",
"... | Ignore the masked elements when calculating the softmax
Parameters
----------
F : symbol or ndarray
att_score : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
mask : Symbol or NDArray or None
Shape (batch_size, query_length, memory_length)
Returns
-------
att_weights : Symborl or NDArray
Shape (batch_size, query_length, memory_length) | [
"Ignore",
"the",
"masked",
"elements",
"when",
"calculating",
"the",
"softmax"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L33-L55 |
32,563 | dmlc/gluon-nlp | src/gluonnlp/model/attention_cell.py | AttentionCell._read_by_weight | def _read_by_weight(self, F, att_weights, value):
"""Read from the value matrix given the attention weights.
Parameters
----------
F : symbol or ndarray
att_weights : Symbol or NDArray
Attention weights.
For single-head attention,
Shape (batch_size, query_length, memory_length).
For multi-head attention,
Shape (batch_size, num_heads, query_length, memory_length).
value : Symbol or NDArray
Value of the memory. Shape (batch_size, memory_length, total_value_dim)
Returns
-------
context_vec: Symbol or NDArray
Shape (batch_size, query_length, context_vec_dim)
"""
output = F.batch_dot(att_weights, value)
return output | python | def _read_by_weight(self, F, att_weights, value):
"""Read from the value matrix given the attention weights.
Parameters
----------
F : symbol or ndarray
att_weights : Symbol or NDArray
Attention weights.
For single-head attention,
Shape (batch_size, query_length, memory_length).
For multi-head attention,
Shape (batch_size, num_heads, query_length, memory_length).
value : Symbol or NDArray
Value of the memory. Shape (batch_size, memory_length, total_value_dim)
Returns
-------
context_vec: Symbol or NDArray
Shape (batch_size, query_length, context_vec_dim)
"""
output = F.batch_dot(att_weights, value)
return output | [
"def",
"_read_by_weight",
"(",
"self",
",",
"F",
",",
"att_weights",
",",
"value",
")",
":",
"output",
"=",
"F",
".",
"batch_dot",
"(",
"att_weights",
",",
"value",
")",
"return",
"output"
] | Read from the value matrix given the attention weights.
Parameters
----------
F : symbol or ndarray
att_weights : Symbol or NDArray
Attention weights.
For single-head attention,
Shape (batch_size, query_length, memory_length).
For multi-head attention,
Shape (batch_size, num_heads, query_length, memory_length).
value : Symbol or NDArray
Value of the memory. Shape (batch_size, memory_length, total_value_dim)
Returns
-------
context_vec: Symbol or NDArray
Shape (batch_size, query_length, context_vec_dim) | [
"Read",
"from",
"the",
"value",
"matrix",
"given",
"the",
"attention",
"weights",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L99-L120 |
32,564 | dmlc/gluon-nlp | scripts/machine_translation/translation.py | BeamSearchTranslator.translate | def translate(self, src_seq, src_valid_length):
"""Get the translation result given the input sentence.
Parameters
----------
src_seq : mx.nd.NDArray
Shape (batch_size, length)
src_valid_length : mx.nd.NDArray
Shape (batch_size,)
Returns
-------
samples : NDArray
Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32.
scores : NDArray
Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are
in descending order.
valid_length : NDArray
The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32.
"""
batch_size = src_seq.shape[0]
encoder_outputs, _ = self._model.encode(src_seq, valid_length=src_valid_length)
decoder_states = self._model.decoder.init_state_from_encoder(encoder_outputs,
src_valid_length)
inputs = mx.nd.full(shape=(batch_size,), ctx=src_seq.context, dtype=np.float32,
val=self._model.tgt_vocab.token_to_idx[self._model.tgt_vocab.bos_token])
samples, scores, sample_valid_length = self._sampler(inputs, decoder_states)
return samples, scores, sample_valid_length | python | def translate(self, src_seq, src_valid_length):
"""Get the translation result given the input sentence.
Parameters
----------
src_seq : mx.nd.NDArray
Shape (batch_size, length)
src_valid_length : mx.nd.NDArray
Shape (batch_size,)
Returns
-------
samples : NDArray
Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32.
scores : NDArray
Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are
in descending order.
valid_length : NDArray
The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32.
"""
batch_size = src_seq.shape[0]
encoder_outputs, _ = self._model.encode(src_seq, valid_length=src_valid_length)
decoder_states = self._model.decoder.init_state_from_encoder(encoder_outputs,
src_valid_length)
inputs = mx.nd.full(shape=(batch_size,), ctx=src_seq.context, dtype=np.float32,
val=self._model.tgt_vocab.token_to_idx[self._model.tgt_vocab.bos_token])
samples, scores, sample_valid_length = self._sampler(inputs, decoder_states)
return samples, scores, sample_valid_length | [
"def",
"translate",
"(",
"self",
",",
"src_seq",
",",
"src_valid_length",
")",
":",
"batch_size",
"=",
"src_seq",
".",
"shape",
"[",
"0",
"]",
"encoder_outputs",
",",
"_",
"=",
"self",
".",
"_model",
".",
"encode",
"(",
"src_seq",
",",
"valid_length",
"=... | Get the translation result given the input sentence.
Parameters
----------
src_seq : mx.nd.NDArray
Shape (batch_size, length)
src_valid_length : mx.nd.NDArray
Shape (batch_size,)
Returns
-------
samples : NDArray
Samples draw by beam search. Shape (batch_size, beam_size, length). dtype is int32.
scores : NDArray
Scores of the samples. Shape (batch_size, beam_size). We make sure that scores[i, :] are
in descending order.
valid_length : NDArray
The valid length of the samples. Shape (batch_size, beam_size). dtype will be int32. | [
"Get",
"the",
"translation",
"result",
"given",
"the",
"input",
"sentence",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/translation.py#L55-L82 |
32,565 | dmlc/gluon-nlp | scripts/parsing/parser/evaluate/evaluate.py | evaluate_official_script | def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file,
debug=False):
"""Evaluate parser on a data set
Parameters
----------
parser : BiaffineParser
biaffine parser
vocab : ParserVocabulary
vocabulary built from data set
num_buckets_test : int
size of buckets (cluster sentences into this number of clusters)
test_batch_size : int
batch size
test_file : str
gold test file
output_file : str
output result to this file
debug : bool
only evaluate first 1000 sentences for debugging
Returns
-------
tuple
UAS, LAS, speed
"""
if output_file is None:
output_file = tempfile.NamedTemporaryFile().name
data_loader = DataLoader(test_file, num_buckets_test, vocab)
record = data_loader.idx_sequence
results = [None] * len(record)
idx = 0
seconds = time.time()
for words, tags, arcs, rels in data_loader.get_batches(batch_size=test_batch_size,
shuffle=False):
outputs = parser.forward(words, tags)
for output in outputs:
sent_idx = record[idx]
results[sent_idx] = output
idx += 1
assert idx == len(results), 'parser swallowed some sentences'
seconds = time.time() - seconds
speed = len(record) / seconds
arcs = reduce(lambda x, y: x + y, [list(result[0]) for result in results])
rels = reduce(lambda x, y: x + y, [list(result[1]) for result in results])
idx = 0
with open(test_file) as f:
if debug:
f = f.readlines()[:1000]
with open(output_file, 'w') as fo:
for line in f:
info = line.strip().split()
if info:
arc_offset = 5
rel_offset = 6
if len(info) == 10: # conll or conllx
arc_offset = 6
rel_offset = 7
# assert len(info) == 10, 'Illegal line: %s' % line
info[arc_offset] = str(arcs[idx])
info[rel_offset] = vocab.id2rel(rels[idx])
fo.write('\t'.join(info) + '\n')
idx += 1
else:
fo.write('\n')
os.system('perl %s -q -b -g %s -s %s -o tmp' % (
os.path.join(os.path.dirname(os.path.realpath(__file__)), 'eval.pl'), test_file, output_file))
os.system('tail -n 3 tmp > score_tmp')
LAS, UAS = [float(line.strip().split()[-2]) for line in open('score_tmp').readlines()[:2]]
# print('UAS %.2f, LAS %.2f' % (UAS, LAS))
os.system('rm tmp score_tmp')
os.remove(output_file)
return UAS, LAS, speed | python | def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file,
debug=False):
"""Evaluate parser on a data set
Parameters
----------
parser : BiaffineParser
biaffine parser
vocab : ParserVocabulary
vocabulary built from data set
num_buckets_test : int
size of buckets (cluster sentences into this number of clusters)
test_batch_size : int
batch size
test_file : str
gold test file
output_file : str
output result to this file
debug : bool
only evaluate first 1000 sentences for debugging
Returns
-------
tuple
UAS, LAS, speed
"""
if output_file is None:
output_file = tempfile.NamedTemporaryFile().name
data_loader = DataLoader(test_file, num_buckets_test, vocab)
record = data_loader.idx_sequence
results = [None] * len(record)
idx = 0
seconds = time.time()
for words, tags, arcs, rels in data_loader.get_batches(batch_size=test_batch_size,
shuffle=False):
outputs = parser.forward(words, tags)
for output in outputs:
sent_idx = record[idx]
results[sent_idx] = output
idx += 1
assert idx == len(results), 'parser swallowed some sentences'
seconds = time.time() - seconds
speed = len(record) / seconds
arcs = reduce(lambda x, y: x + y, [list(result[0]) for result in results])
rels = reduce(lambda x, y: x + y, [list(result[1]) for result in results])
idx = 0
with open(test_file) as f:
if debug:
f = f.readlines()[:1000]
with open(output_file, 'w') as fo:
for line in f:
info = line.strip().split()
if info:
arc_offset = 5
rel_offset = 6
if len(info) == 10: # conll or conllx
arc_offset = 6
rel_offset = 7
# assert len(info) == 10, 'Illegal line: %s' % line
info[arc_offset] = str(arcs[idx])
info[rel_offset] = vocab.id2rel(rels[idx])
fo.write('\t'.join(info) + '\n')
idx += 1
else:
fo.write('\n')
os.system('perl %s -q -b -g %s -s %s -o tmp' % (
os.path.join(os.path.dirname(os.path.realpath(__file__)), 'eval.pl'), test_file, output_file))
os.system('tail -n 3 tmp > score_tmp')
LAS, UAS = [float(line.strip().split()[-2]) for line in open('score_tmp').readlines()[:2]]
# print('UAS %.2f, LAS %.2f' % (UAS, LAS))
os.system('rm tmp score_tmp')
os.remove(output_file)
return UAS, LAS, speed | [
"def",
"evaluate_official_script",
"(",
"parser",
",",
"vocab",
",",
"num_buckets_test",
",",
"test_batch_size",
",",
"test_file",
",",
"output_file",
",",
"debug",
"=",
"False",
")",
":",
"if",
"output_file",
"is",
"None",
":",
"output_file",
"=",
"tempfile",
... | Evaluate parser on a data set
Parameters
----------
parser : BiaffineParser
biaffine parser
vocab : ParserVocabulary
vocabulary built from data set
num_buckets_test : int
size of buckets (cluster sentences into this number of clusters)
test_batch_size : int
batch size
test_file : str
gold test file
output_file : str
output result to this file
debug : bool
only evaluate first 1000 sentences for debugging
Returns
-------
tuple
UAS, LAS, speed | [
"Evaluate",
"parser",
"on",
"a",
"data",
"set"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/evaluate/evaluate.py#L28-L102 |
32,566 | dmlc/gluon-nlp | scripts/parsing/parser/biaffine_parser.py | BiaffineParser.parameter_from_numpy | def parameter_from_numpy(self, name, array):
""" Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.gluon.parameter
a parameter object
"""
p = self.params.get(name, shape=array.shape, init=mx.init.Constant(array))
return p | python | def parameter_from_numpy(self, name, array):
""" Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.gluon.parameter
a parameter object
"""
p = self.params.get(name, shape=array.shape, init=mx.init.Constant(array))
return p | [
"def",
"parameter_from_numpy",
"(",
"self",
",",
"name",
",",
"array",
")",
":",
"p",
"=",
"self",
".",
"params",
".",
"get",
"(",
"name",
",",
"shape",
"=",
"array",
".",
"shape",
",",
"init",
"=",
"mx",
".",
"init",
".",
"Constant",
"(",
"array",... | Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.gluon.parameter
a parameter object | [
"Create",
"parameter",
"with",
"its",
"value",
"initialized",
"according",
"to",
"a",
"numpy",
"tensor"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L122-L138 |
32,567 | dmlc/gluon-nlp | scripts/parsing/parser/biaffine_parser.py | BiaffineParser.parameter_init | def parameter_init(self, name, shape, init):
"""Create parameter given name, shape and initiator
Parameters
----------
name : str
parameter name
shape : tuple
parameter shape
init : mxnet.initializer
an initializer
Returns
-------
mxnet.gluon.parameter
a parameter object
"""
p = self.params.get(name, shape=shape, init=init)
return p | python | def parameter_init(self, name, shape, init):
"""Create parameter given name, shape and initiator
Parameters
----------
name : str
parameter name
shape : tuple
parameter shape
init : mxnet.initializer
an initializer
Returns
-------
mxnet.gluon.parameter
a parameter object
"""
p = self.params.get(name, shape=shape, init=init)
return p | [
"def",
"parameter_init",
"(",
"self",
",",
"name",
",",
"shape",
",",
"init",
")",
":",
"p",
"=",
"self",
".",
"params",
".",
"get",
"(",
"name",
",",
"shape",
"=",
"shape",
",",
"init",
"=",
"init",
")",
"return",
"p"
] | Create parameter given name, shape and initiator
Parameters
----------
name : str
parameter name
shape : tuple
parameter shape
init : mxnet.initializer
an initializer
Returns
-------
mxnet.gluon.parameter
a parameter object | [
"Create",
"parameter",
"given",
"name",
"shape",
"and",
"initiator"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L140-L158 |
32,568 | dmlc/gluon-nlp | src/gluonnlp/data/dataloader.py | _thread_worker_fn | def _thread_worker_fn(samples, batchify_fn, dataset):
"""Threadpool worker function for processing data."""
if isinstance(samples[0], (list, tuple)):
batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
else:
batch = batchify_fn([dataset[i] for i in samples])
return batch | python | def _thread_worker_fn(samples, batchify_fn, dataset):
"""Threadpool worker function for processing data."""
if isinstance(samples[0], (list, tuple)):
batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
else:
batch = batchify_fn([dataset[i] for i in samples])
return batch | [
"def",
"_thread_worker_fn",
"(",
"samples",
",",
"batchify_fn",
",",
"dataset",
")",
":",
"if",
"isinstance",
"(",
"samples",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"batch",
"=",
"[",
"batchify_fn",
"(",
"[",
"dataset",
"[",
"i... | Threadpool worker function for processing data. | [
"Threadpool",
"worker",
"function",
"for",
"processing",
"data",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataloader.py#L54-L60 |
32,569 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding._check_source | def _check_source(cls, source_file_hash, source):
"""Checks if a pre-trained token embedding source name is valid.
Parameters
----------
source : str
The pre-trained token embedding source.
"""
embedding_name = cls.__name__.lower()
if source not in source_file_hash:
raise KeyError('Cannot find pre-trained source {} for token embedding {}. '
'Valid pre-trained file names for embedding {}: {}'.format(
source, embedding_name, embedding_name,
', '.join(source_file_hash.keys()))) | python | def _check_source(cls, source_file_hash, source):
"""Checks if a pre-trained token embedding source name is valid.
Parameters
----------
source : str
The pre-trained token embedding source.
"""
embedding_name = cls.__name__.lower()
if source not in source_file_hash:
raise KeyError('Cannot find pre-trained source {} for token embedding {}. '
'Valid pre-trained file names for embedding {}: {}'.format(
source, embedding_name, embedding_name,
', '.join(source_file_hash.keys()))) | [
"def",
"_check_source",
"(",
"cls",
",",
"source_file_hash",
",",
"source",
")",
":",
"embedding_name",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"if",
"source",
"not",
"in",
"source_file_hash",
":",
"raise",
"KeyError",
"(",
"'Cannot find pre-train... | Checks if a pre-trained token embedding source name is valid.
Parameters
----------
source : str
The pre-trained token embedding source. | [
"Checks",
"if",
"a",
"pre",
"-",
"trained",
"token",
"embedding",
"source",
"name",
"is",
"valid",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L643-L657 |
32,570 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding.from_file | def from_file(file_path, elem_delim=' ', encoding='utf8', **kwargs):
"""Creates a user-defined token embedding from a pre-trained embedding file.
This is to load embedding vectors from a user-defined pre-trained token embedding file.
For example, if `elem_delim` = ' ', the expected format of a custom pre-trained token
embedding file may look like:
'hello 0.1 0.2 0.3 0.4 0.5\\\\nworld 1.1 1.2 1.3 1.4 1.5\\\\n'
where embedding vectors of words `hello` and `world` are [0.1, 0.2, 0.3, 0.4, 0.5] and
[1.1, 1.2, 1.3, 1.4, 1.5] respectively.
Parameters
----------
file_path : str
The path to the user-defined pre-trained token embedding file.
elem_delim : str, default ' '
The delimiter for splitting a token and every embedding vector element value on the same
line of the custom pre-trained token embedding file.
encoding : str, default 'utf8'
The encoding scheme for reading the custom pre-trained token embedding file.
kwargs : dict
All other keyword arguments are passed to the TokenEmbedding initializer.
Returns
-------
instance of :class:`gluonnlp.embedding.TokenEmbedding`
The user-defined token embedding instance.
"""
embedding = TokenEmbedding(**kwargs)
embedding._load_embedding(file_path, elem_delim=elem_delim, encoding=encoding)
return embedding | python | def from_file(file_path, elem_delim=' ', encoding='utf8', **kwargs):
"""Creates a user-defined token embedding from a pre-trained embedding file.
This is to load embedding vectors from a user-defined pre-trained token embedding file.
For example, if `elem_delim` = ' ', the expected format of a custom pre-trained token
embedding file may look like:
'hello 0.1 0.2 0.3 0.4 0.5\\\\nworld 1.1 1.2 1.3 1.4 1.5\\\\n'
where embedding vectors of words `hello` and `world` are [0.1, 0.2, 0.3, 0.4, 0.5] and
[1.1, 1.2, 1.3, 1.4, 1.5] respectively.
Parameters
----------
file_path : str
The path to the user-defined pre-trained token embedding file.
elem_delim : str, default ' '
The delimiter for splitting a token and every embedding vector element value on the same
line of the custom pre-trained token embedding file.
encoding : str, default 'utf8'
The encoding scheme for reading the custom pre-trained token embedding file.
kwargs : dict
All other keyword arguments are passed to the TokenEmbedding initializer.
Returns
-------
instance of :class:`gluonnlp.embedding.TokenEmbedding`
The user-defined token embedding instance.
"""
embedding = TokenEmbedding(**kwargs)
embedding._load_embedding(file_path, elem_delim=elem_delim, encoding=encoding)
return embedding | [
"def",
"from_file",
"(",
"file_path",
",",
"elem_delim",
"=",
"' '",
",",
"encoding",
"=",
"'utf8'",
",",
"*",
"*",
"kwargs",
")",
":",
"embedding",
"=",
"TokenEmbedding",
"(",
"*",
"*",
"kwargs",
")",
"embedding",
".",
"_load_embedding",
"(",
"file_path",... | Creates a user-defined token embedding from a pre-trained embedding file.
This is to load embedding vectors from a user-defined pre-trained token embedding file.
For example, if `elem_delim` = ' ', the expected format of a custom pre-trained token
embedding file may look like:
'hello 0.1 0.2 0.3 0.4 0.5\\\\nworld 1.1 1.2 1.3 1.4 1.5\\\\n'
where embedding vectors of words `hello` and `world` are [0.1, 0.2, 0.3, 0.4, 0.5] and
[1.1, 1.2, 1.3, 1.4, 1.5] respectively.
Parameters
----------
file_path : str
The path to the user-defined pre-trained token embedding file.
elem_delim : str, default ' '
The delimiter for splitting a token and every embedding vector element value on the same
line of the custom pre-trained token embedding file.
encoding : str, default 'utf8'
The encoding scheme for reading the custom pre-trained token embedding file.
kwargs : dict
All other keyword arguments are passed to the TokenEmbedding initializer.
Returns
-------
instance of :class:`gluonnlp.embedding.TokenEmbedding`
The user-defined token embedding instance. | [
"Creates",
"a",
"user",
"-",
"defined",
"token",
"embedding",
"from",
"a",
"pre",
"-",
"trained",
"embedding",
"file",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L660-L694 |
32,571 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding.serialize | def serialize(self, file_path, compress=True):
"""Serializes the TokenEmbedding to a file specified by file_path.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more
information on the format.
Parameters
----------
file_path : str or file
The path at which to create the file holding the serialized
TokenEmbedding. If file is a string or a Path, the .npz extension
will be appended to the file name if it is not already there.
compress : bool, default True
Compress the Zipfile or leave it uncompressed.
"""
if self.unknown_lookup is not None:
warnings.warn(
'Serialization of `unknown_lookup` is not supported. '
'Save it manually and pass the loaded lookup object '
'during deserialization.')
unknown_token = np.array(self.unknown_token)
idx_to_token = np.array(self.idx_to_token, dtype='O')
idx_to_vec = self.idx_to_vec.asnumpy()
if not unknown_token: # Store empty string instead of None
unknown_token = ''
else:
assert unknown_token == idx_to_token[C.UNK_IDX]
if not compress:
np.savez(file=file_path, unknown_token=unknown_token,
idx_to_token=idx_to_token, idx_to_vec=idx_to_vec)
else:
np.savez_compressed(file=file_path, unknown_token=unknown_token,
idx_to_token=idx_to_token,
idx_to_vec=idx_to_vec) | python | def serialize(self, file_path, compress=True):
"""Serializes the TokenEmbedding to a file specified by file_path.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more
information on the format.
Parameters
----------
file_path : str or file
The path at which to create the file holding the serialized
TokenEmbedding. If file is a string or a Path, the .npz extension
will be appended to the file name if it is not already there.
compress : bool, default True
Compress the Zipfile or leave it uncompressed.
"""
if self.unknown_lookup is not None:
warnings.warn(
'Serialization of `unknown_lookup` is not supported. '
'Save it manually and pass the loaded lookup object '
'during deserialization.')
unknown_token = np.array(self.unknown_token)
idx_to_token = np.array(self.idx_to_token, dtype='O')
idx_to_vec = self.idx_to_vec.asnumpy()
if not unknown_token: # Store empty string instead of None
unknown_token = ''
else:
assert unknown_token == idx_to_token[C.UNK_IDX]
if not compress:
np.savez(file=file_path, unknown_token=unknown_token,
idx_to_token=idx_to_token, idx_to_vec=idx_to_vec)
else:
np.savez_compressed(file=file_path, unknown_token=unknown_token,
idx_to_token=idx_to_token,
idx_to_vec=idx_to_vec) | [
"def",
"serialize",
"(",
"self",
",",
"file_path",
",",
"compress",
"=",
"True",
")",
":",
"if",
"self",
".",
"unknown_lookup",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"'Serialization of `unknown_lookup` is not supported. '",
"'Save it manually and p... | Serializes the TokenEmbedding to a file specified by file_path.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more
information on the format.
Parameters
----------
file_path : str or file
The path at which to create the file holding the serialized
TokenEmbedding. If file is a string or a Path, the .npz extension
will be appended to the file name if it is not already there.
compress : bool, default True
Compress the Zipfile or leave it uncompressed. | [
"Serializes",
"the",
"TokenEmbedding",
"to",
"a",
"file",
"specified",
"by",
"file_path",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L696-L737 |
32,572 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding.deserialize | def deserialize(cls, file_path, **kwargs):
"""Create a new TokenEmbedding from a serialized one.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more
information on the format.
Parameters
----------
file_path : str or file
The path to a file that holds the serialized TokenEmbedding.
kwargs : dict
Keyword arguments are passed to the TokenEmbedding initializer.
Useful for attaching unknown_lookup.
"""
# idx_to_token is of dtype 'O' so we need to allow pickle
npz_dict = np.load(file_path, allow_pickle=True)
unknown_token = npz_dict['unknown_token']
if not unknown_token:
unknown_token = None
else:
if isinstance(unknown_token, np.ndarray):
if unknown_token.dtype.kind == 'S':
unknown_token = unknown_token.tobytes().decode()
else:
unknown_token = str(unknown_token)
idx_to_token = npz_dict['idx_to_token'].tolist()
idx_to_vec = nd.array(npz_dict['idx_to_vec'])
embedding = cls(unknown_token=unknown_token, **kwargs)
if unknown_token:
assert unknown_token == idx_to_token[C.UNK_IDX]
embedding._token_to_idx = DefaultLookupDict(C.UNK_IDX)
else:
embedding._token_to_idx = {}
embedding._idx_to_token = idx_to_token
embedding._idx_to_vec = idx_to_vec
embedding._token_to_idx.update((token, idx) for idx, token in enumerate(idx_to_token))
return embedding | python | def deserialize(cls, file_path, **kwargs):
"""Create a new TokenEmbedding from a serialized one.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more
information on the format.
Parameters
----------
file_path : str or file
The path to a file that holds the serialized TokenEmbedding.
kwargs : dict
Keyword arguments are passed to the TokenEmbedding initializer.
Useful for attaching unknown_lookup.
"""
# idx_to_token is of dtype 'O' so we need to allow pickle
npz_dict = np.load(file_path, allow_pickle=True)
unknown_token = npz_dict['unknown_token']
if not unknown_token:
unknown_token = None
else:
if isinstance(unknown_token, np.ndarray):
if unknown_token.dtype.kind == 'S':
unknown_token = unknown_token.tobytes().decode()
else:
unknown_token = str(unknown_token)
idx_to_token = npz_dict['idx_to_token'].tolist()
idx_to_vec = nd.array(npz_dict['idx_to_vec'])
embedding = cls(unknown_token=unknown_token, **kwargs)
if unknown_token:
assert unknown_token == idx_to_token[C.UNK_IDX]
embedding._token_to_idx = DefaultLookupDict(C.UNK_IDX)
else:
embedding._token_to_idx = {}
embedding._idx_to_token = idx_to_token
embedding._idx_to_vec = idx_to_vec
embedding._token_to_idx.update((token, idx) for idx, token in enumerate(idx_to_token))
return embedding | [
"def",
"deserialize",
"(",
"cls",
",",
"file_path",
",",
"*",
"*",
"kwargs",
")",
":",
"# idx_to_token is of dtype 'O' so we need to allow pickle",
"npz_dict",
"=",
"np",
".",
"load",
"(",
"file_path",
",",
"allow_pickle",
"=",
"True",
")",
"unknown_token",
"=",
... | Create a new TokenEmbedding from a serialized one.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html for more
information on the format.
Parameters
----------
file_path : str or file
The path to a file that holds the serialized TokenEmbedding.
kwargs : dict
Keyword arguments are passed to the TokenEmbedding initializer.
Useful for attaching unknown_lookup. | [
"Create",
"a",
"new",
"TokenEmbedding",
"from",
"a",
"serialized",
"one",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L740-L784 |
32,573 | dmlc/gluon-nlp | scripts/bert/staticbert/static_export_squad.py | evaluate | def evaluate(data_source):
"""Evaluate the model on a mini-batch.
"""
log.info('Start predict')
tic = time.time()
for batch in data_source:
inputs, token_types, valid_length = batch
out = net(inputs.astype('float32').as_in_context(ctx),
token_types.astype('float32').as_in_context(ctx),
valid_length.astype('float32').as_in_context(ctx))
toc = time.time()
log.info('Inference time cost={:.2f} s, Thoughput={:.2f} samples/s'
.format(toc - tic,
len(data_source) / (toc - tic))) | python | def evaluate(data_source):
"""Evaluate the model on a mini-batch.
"""
log.info('Start predict')
tic = time.time()
for batch in data_source:
inputs, token_types, valid_length = batch
out = net(inputs.astype('float32').as_in_context(ctx),
token_types.astype('float32').as_in_context(ctx),
valid_length.astype('float32').as_in_context(ctx))
toc = time.time()
log.info('Inference time cost={:.2f} s, Thoughput={:.2f} samples/s'
.format(toc - tic,
len(data_source) / (toc - tic))) | [
"def",
"evaluate",
"(",
"data_source",
")",
":",
"log",
".",
"info",
"(",
"'Start predict'",
")",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"for",
"batch",
"in",
"data_source",
":",
"inputs",
",",
"token_types",
",",
"valid_length",
"=",
"batch",
"out",... | Evaluate the model on a mini-batch. | [
"Evaluate",
"the",
"model",
"on",
"a",
"mini",
"-",
"batch",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_export_squad.py#L210-L223 |
32,574 | dmlc/gluon-nlp | src/gluonnlp/data/registry.py | register | def register(class_=None, **kwargs):
"""Registers a dataset with segment specific hyperparameters.
When passing keyword arguments to `register`, they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry. Registered keyword arguments can be retrieved with
the `list_datasets` function.
All arguments that result in creation of separate datasets should be
registered. Examples are datasets divided in different segments or
categories, or datasets containing multiple languages.
Once registered, an instance can be created by calling
:func:`~gluonnlp.data.create` with the class name.
Parameters
----------
**kwargs : list or tuple of allowed argument values
For each keyword argument, it's value must be a list or tuple of the
allowed argument values.
Examples
--------
>>> @gluonnlp.data.register(segment=['train', 'test', 'dev'])
... class MyDataset(gluon.data.Dataset):
... def __init__(self, segment='train'):
... pass
>>> my_dataset = gluonnlp.data.create('MyDataset')
>>> print(type(my_dataset))
<class 'MyDataset'>
"""
def _real_register(class_):
# Assert that the passed kwargs are meaningful
for kwarg_name, values in kwargs.items():
try:
real_args = inspect.getfullargspec(class_).args
except AttributeError:
# pylint: disable=deprecated-method
real_args = inspect.getargspec(class_.__init__).args
if not kwarg_name in real_args:
raise RuntimeError(
('{} is not a valid argument for {}. '
'Only valid arguments can be registered.').format(
kwarg_name, class_.__name__))
if not isinstance(values, (list, tuple)):
raise RuntimeError(('{} should be a list of '
'valid arguments for {}. ').format(
values, kwarg_name))
# Save the kwargs associated with this class_
_REGSITRY_NAME_KWARGS[class_] = kwargs
register_ = registry.get_register_func(Dataset, 'dataset')
return register_(class_)
if class_ is not None:
# Decorator was called without arguments
return _real_register(class_)
return _real_register | python | def register(class_=None, **kwargs):
"""Registers a dataset with segment specific hyperparameters.
When passing keyword arguments to `register`, they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry. Registered keyword arguments can be retrieved with
the `list_datasets` function.
All arguments that result in creation of separate datasets should be
registered. Examples are datasets divided in different segments or
categories, or datasets containing multiple languages.
Once registered, an instance can be created by calling
:func:`~gluonnlp.data.create` with the class name.
Parameters
----------
**kwargs : list or tuple of allowed argument values
For each keyword argument, it's value must be a list or tuple of the
allowed argument values.
Examples
--------
>>> @gluonnlp.data.register(segment=['train', 'test', 'dev'])
... class MyDataset(gluon.data.Dataset):
... def __init__(self, segment='train'):
... pass
>>> my_dataset = gluonnlp.data.create('MyDataset')
>>> print(type(my_dataset))
<class 'MyDataset'>
"""
def _real_register(class_):
# Assert that the passed kwargs are meaningful
for kwarg_name, values in kwargs.items():
try:
real_args = inspect.getfullargspec(class_).args
except AttributeError:
# pylint: disable=deprecated-method
real_args = inspect.getargspec(class_.__init__).args
if not kwarg_name in real_args:
raise RuntimeError(
('{} is not a valid argument for {}. '
'Only valid arguments can be registered.').format(
kwarg_name, class_.__name__))
if not isinstance(values, (list, tuple)):
raise RuntimeError(('{} should be a list of '
'valid arguments for {}. ').format(
values, kwarg_name))
# Save the kwargs associated with this class_
_REGSITRY_NAME_KWARGS[class_] = kwargs
register_ = registry.get_register_func(Dataset, 'dataset')
return register_(class_)
if class_ is not None:
# Decorator was called without arguments
return _real_register(class_)
return _real_register | [
"def",
"register",
"(",
"class_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_real_register",
"(",
"class_",
")",
":",
"# Assert that the passed kwargs are meaningful",
"for",
"kwarg_name",
",",
"values",
"in",
"kwargs",
".",
"items",
"(",
")",
... | Registers a dataset with segment specific hyperparameters.
When passing keyword arguments to `register`, they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry. Registered keyword arguments can be retrieved with
the `list_datasets` function.
All arguments that result in creation of separate datasets should be
registered. Examples are datasets divided in different segments or
categories, or datasets containing multiple languages.
Once registered, an instance can be created by calling
:func:`~gluonnlp.data.create` with the class name.
Parameters
----------
**kwargs : list or tuple of allowed argument values
For each keyword argument, it's value must be a list or tuple of the
allowed argument values.
Examples
--------
>>> @gluonnlp.data.register(segment=['train', 'test', 'dev'])
... class MyDataset(gluon.data.Dataset):
... def __init__(self, segment='train'):
... pass
>>> my_dataset = gluonnlp.data.create('MyDataset')
>>> print(type(my_dataset))
<class 'MyDataset'> | [
"Registers",
"a",
"dataset",
"with",
"segment",
"specific",
"hyperparameters",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L34-L97 |
32,575 | dmlc/gluon-nlp | src/gluonnlp/data/registry.py | create | def create(name, **kwargs):
"""Creates an instance of a registered dataset.
Parameters
----------
name : str
The dataset name (case-insensitive).
Returns
-------
An instance of :class:`mxnet.gluon.data.Dataset` constructed with the
keyword arguments passed to the create function.
"""
create_ = registry.get_create_func(Dataset, 'dataset')
return create_(name, **kwargs) | python | def create(name, **kwargs):
"""Creates an instance of a registered dataset.
Parameters
----------
name : str
The dataset name (case-insensitive).
Returns
-------
An instance of :class:`mxnet.gluon.data.Dataset` constructed with the
keyword arguments passed to the create function.
"""
create_ = registry.get_create_func(Dataset, 'dataset')
return create_(name, **kwargs) | [
"def",
"create",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"create_",
"=",
"registry",
".",
"get_create_func",
"(",
"Dataset",
",",
"'dataset'",
")",
"return",
"create_",
"(",
"name",
",",
"*",
"*",
"kwargs",
")"
] | Creates an instance of a registered dataset.
Parameters
----------
name : str
The dataset name (case-insensitive).
Returns
-------
An instance of :class:`mxnet.gluon.data.Dataset` constructed with the
keyword arguments passed to the create function. | [
"Creates",
"an",
"instance",
"of",
"a",
"registered",
"dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L100-L115 |
32,576 | dmlc/gluon-nlp | src/gluonnlp/data/registry.py | list_datasets | def list_datasets(name=None):
"""Get valid datasets and registered parameters.
Parameters
----------
name : str or None, default None
Return names and registered parameters of registered datasets. If name
is specified, only registered parameters of the respective dataset are
returned.
Returns
-------
dict:
A dict of all the valid keyword parameters names for the specified
dataset. If name is set to None, returns a dict mapping each valid name
to its respective keyword parameter dict. The valid names can be
plugged in `gluonnlp.model.word_evaluation_model.create(name)`.
"""
reg = registry.get_registry(Dataset)
if name is not None:
class_ = reg[name.lower()]
return _REGSITRY_NAME_KWARGS[class_]
else:
return {
dataset_name: _REGSITRY_NAME_KWARGS[class_]
for dataset_name, class_ in registry.get_registry(Dataset).items()
} | python | def list_datasets(name=None):
"""Get valid datasets and registered parameters.
Parameters
----------
name : str or None, default None
Return names and registered parameters of registered datasets. If name
is specified, only registered parameters of the respective dataset are
returned.
Returns
-------
dict:
A dict of all the valid keyword parameters names for the specified
dataset. If name is set to None, returns a dict mapping each valid name
to its respective keyword parameter dict. The valid names can be
plugged in `gluonnlp.model.word_evaluation_model.create(name)`.
"""
reg = registry.get_registry(Dataset)
if name is not None:
class_ = reg[name.lower()]
return _REGSITRY_NAME_KWARGS[class_]
else:
return {
dataset_name: _REGSITRY_NAME_KWARGS[class_]
for dataset_name, class_ in registry.get_registry(Dataset).items()
} | [
"def",
"list_datasets",
"(",
"name",
"=",
"None",
")",
":",
"reg",
"=",
"registry",
".",
"get_registry",
"(",
"Dataset",
")",
"if",
"name",
"is",
"not",
"None",
":",
"class_",
"=",
"reg",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"return",
"_REGSITRY... | Get valid datasets and registered parameters.
Parameters
----------
name : str or None, default None
Return names and registered parameters of registered datasets. If name
is specified, only registered parameters of the respective dataset are
returned.
Returns
-------
dict:
A dict of all the valid keyword parameters names for the specified
dataset. If name is set to None, returns a dict mapping each valid name
to its respective keyword parameter dict. The valid names can be
plugged in `gluonnlp.model.word_evaluation_model.create(name)`. | [
"Get",
"valid",
"datasets",
"and",
"registered",
"parameters",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L118-L146 |
32,577 | dmlc/gluon-nlp | scripts/word_embeddings/extract_vocab.py | get_vocab | def get_vocab(args):
"""Compute the vocabulary."""
counter = nlp.data.Counter()
start = time.time()
for filename in args.files:
print('Starting processing of {} after {:.1f} seconds.'.format(
filename,
time.time() - start))
with open(filename, 'r') as f:
tokens = itertools.chain.from_iterable((l.split() for l in f))
counter.update(tokens)
if args.max_word_length:
counter = {
w: c
for w, c in counter.items() if len(w) < args.max_word_length
}
total_time = time.time() - start
print('Finished after {:.1f} seconds.'.format(total_time))
num_words = sum(counter.values())
print('Got {} words. Processed {:.1f} per second.'.format(
num_words, num_words / total_time))
start = time.time()
print('Starting creation of vocabulary.')
vocab = nlp.Vocab(counter, max_size=args.max_size, min_freq=args.min_freq,
unknown_token=None, padding_token=None, bos_token=None,
eos_token=None)
with open(args.vocab_output, 'w') as f:
f.write(vocab.to_json())
print('Finished creation of vocabulary after {:.1f} seconds.'.format(
time.time() - start))
print('Writing word counts.')
start = time.time()
idx_to_counts = [counter[t] for t in vocab.idx_to_token]
with open(args.counts_output, 'w') as f:
json.dump(idx_to_counts, f)
print('Finished writing word counts after {:.1f} seconds..'.format(
time.time() - start)) | python | def get_vocab(args):
"""Compute the vocabulary."""
counter = nlp.data.Counter()
start = time.time()
for filename in args.files:
print('Starting processing of {} after {:.1f} seconds.'.format(
filename,
time.time() - start))
with open(filename, 'r') as f:
tokens = itertools.chain.from_iterable((l.split() for l in f))
counter.update(tokens)
if args.max_word_length:
counter = {
w: c
for w, c in counter.items() if len(w) < args.max_word_length
}
total_time = time.time() - start
print('Finished after {:.1f} seconds.'.format(total_time))
num_words = sum(counter.values())
print('Got {} words. Processed {:.1f} per second.'.format(
num_words, num_words / total_time))
start = time.time()
print('Starting creation of vocabulary.')
vocab = nlp.Vocab(counter, max_size=args.max_size, min_freq=args.min_freq,
unknown_token=None, padding_token=None, bos_token=None,
eos_token=None)
with open(args.vocab_output, 'w') as f:
f.write(vocab.to_json())
print('Finished creation of vocabulary after {:.1f} seconds.'.format(
time.time() - start))
print('Writing word counts.')
start = time.time()
idx_to_counts = [counter[t] for t in vocab.idx_to_token]
with open(args.counts_output, 'w') as f:
json.dump(idx_to_counts, f)
print('Finished writing word counts after {:.1f} seconds..'.format(
time.time() - start)) | [
"def",
"get_vocab",
"(",
"args",
")",
":",
"counter",
"=",
"nlp",
".",
"data",
".",
"Counter",
"(",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"filename",
"in",
"args",
".",
"files",
":",
"print",
"(",
"'Starting processing of {} after {:.1... | Compute the vocabulary. | [
"Compute",
"the",
"vocabulary",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/extract_vocab.py#L47-L87 |
32,578 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | add_parameters | def add_parameters(parser):
"""Add evaluation specific parameters to parser."""
group = parser.add_argument_group('Evaluation arguments')
group.add_argument('--eval-batch-size', type=int, default=1024)
# Datasets
group.add_argument(
'--similarity-datasets', type=str,
default=nlp.data.word_embedding_evaluation.word_similarity_datasets,
nargs='*',
help='Word similarity datasets to use for intrinsic evaluation.')
group.add_argument(
'--similarity-functions', type=str,
default=nlp.embedding.evaluation.list_evaluation_functions(
'similarity'), nargs='+',
help='Word similarity functions to use for intrinsic evaluation.')
group.add_argument(
'--analogy-datasets', type=str, default=['GoogleAnalogyTestSet'],
nargs='*',
help='Word similarity datasets to use for intrinsic evaluation.')
group.add_argument(
'--analogy-functions', type=str,
default=nlp.embedding.evaluation.list_evaluation_functions('analogy'),
nargs='+',
help='Word analogy functions to use for intrinsic evaluation. ')
## Analogy evaluation specific arguments
group.add_argument(
'--analogy-dont-exclude-question-words', action='store_true',
help=('Exclude input words from valid output analogies.'
'The performance of word embeddings on the analogy task '
'is around 0% accuracy if input words are not excluded.')) | python | def add_parameters(parser):
"""Add evaluation specific parameters to parser."""
group = parser.add_argument_group('Evaluation arguments')
group.add_argument('--eval-batch-size', type=int, default=1024)
# Datasets
group.add_argument(
'--similarity-datasets', type=str,
default=nlp.data.word_embedding_evaluation.word_similarity_datasets,
nargs='*',
help='Word similarity datasets to use for intrinsic evaluation.')
group.add_argument(
'--similarity-functions', type=str,
default=nlp.embedding.evaluation.list_evaluation_functions(
'similarity'), nargs='+',
help='Word similarity functions to use for intrinsic evaluation.')
group.add_argument(
'--analogy-datasets', type=str, default=['GoogleAnalogyTestSet'],
nargs='*',
help='Word similarity datasets to use for intrinsic evaluation.')
group.add_argument(
'--analogy-functions', type=str,
default=nlp.embedding.evaluation.list_evaluation_functions('analogy'),
nargs='+',
help='Word analogy functions to use for intrinsic evaluation. ')
## Analogy evaluation specific arguments
group.add_argument(
'--analogy-dont-exclude-question-words', action='store_true',
help=('Exclude input words from valid output analogies.'
'The performance of word embeddings on the analogy task '
'is around 0% accuracy if input words are not excluded.')) | [
"def",
"add_parameters",
"(",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Evaluation arguments'",
")",
"group",
".",
"add_argument",
"(",
"'--eval-batch-size'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1024",
")",
"# Dat... | Add evaluation specific parameters to parser. | [
"Add",
"evaluation",
"specific",
"parameters",
"to",
"parser",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L38-L70 |
32,579 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | iterate_similarity_datasets | def iterate_similarity_datasets(args):
"""Generator over all similarity evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.similarity_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_values))
yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs) | python | def iterate_similarity_datasets(args):
"""Generator over all similarity evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.similarity_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_values))
yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs) | [
"def",
"iterate_similarity_datasets",
"(",
"args",
")",
":",
"for",
"dataset_name",
"in",
"args",
".",
"similarity_datasets",
":",
"parameters",
"=",
"nlp",
".",
"data",
".",
"list_datasets",
"(",
"dataset_name",
")",
"for",
"key_values",
"in",
"itertools",
".",... | Generator over all similarity evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset. | [
"Generator",
"over",
"all",
"similarity",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L92-L103 |
32,580 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | iterate_analogy_datasets | def iterate_analogy_datasets(args):
"""Generator over all analogy evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.analogy_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_values))
yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs) | python | def iterate_analogy_datasets(args):
"""Generator over all analogy evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.analogy_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_values))
yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs) | [
"def",
"iterate_analogy_datasets",
"(",
"args",
")",
":",
"for",
"dataset_name",
"in",
"args",
".",
"analogy_datasets",
":",
"parameters",
"=",
"nlp",
".",
"data",
".",
"list_datasets",
"(",
"dataset_name",
")",
"for",
"key_values",
"in",
"itertools",
".",
"pr... | Generator over all analogy evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset. | [
"Generator",
"over",
"all",
"analogy",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L106-L117 |
32,581 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | get_similarity_task_tokens | def get_similarity_task_tokens(args):
"""Returns a set of all tokens occurring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_similarity_datasets(args):
tokens.update(
itertools.chain.from_iterable((d[0], d[1]) for d in dataset))
return tokens | python | def get_similarity_task_tokens(args):
"""Returns a set of all tokens occurring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_similarity_datasets(args):
tokens.update(
itertools.chain.from_iterable((d[0], d[1]) for d in dataset))
return tokens | [
"def",
"get_similarity_task_tokens",
"(",
"args",
")",
":",
"tokens",
"=",
"set",
"(",
")",
"for",
"_",
",",
"_",
",",
"dataset",
"in",
"iterate_similarity_datasets",
"(",
"args",
")",
":",
"tokens",
".",
"update",
"(",
"itertools",
".",
"chain",
".",
"f... | Returns a set of all tokens occurring the evaluation datasets. | [
"Returns",
"a",
"set",
"of",
"all",
"tokens",
"occurring",
"the",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L120-L126 |
32,582 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | get_analogy_task_tokens | def get_analogy_task_tokens(args):
"""Returns a set of all tokens occuring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_analogy_datasets(args):
tokens.update(
itertools.chain.from_iterable(
(d[0], d[1], d[2], d[3]) for d in dataset))
return tokens | python | def get_analogy_task_tokens(args):
"""Returns a set of all tokens occuring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_analogy_datasets(args):
tokens.update(
itertools.chain.from_iterable(
(d[0], d[1], d[2], d[3]) for d in dataset))
return tokens | [
"def",
"get_analogy_task_tokens",
"(",
"args",
")",
":",
"tokens",
"=",
"set",
"(",
")",
"for",
"_",
",",
"_",
",",
"dataset",
"in",
"iterate_analogy_datasets",
"(",
"args",
")",
":",
"tokens",
".",
"update",
"(",
"itertools",
".",
"chain",
".",
"from_it... | Returns a set of all tokens occuring the evaluation datasets. | [
"Returns",
"a",
"set",
"of",
"all",
"tokens",
"occuring",
"the",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L129-L136 |
32,583 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | evaluate_similarity | def evaluate_similarity(args, token_embedding, ctx, logfile=None,
global_step=0):
"""Evaluate on specified similarity datasets."""
results = []
for similarity_function in args.similarity_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
idx_to_vec=token_embedding.idx_to_vec,
similarity_function=similarity_function)
evaluator.initialize(ctx=ctx)
if not args.no_hybridize:
evaluator.hybridize()
# Evaluate all datasets
for (dataset_name, dataset_kwargs,
dataset) in iterate_similarity_datasets(args):
initial_length = len(dataset)
dataset_coded = [[
token_embedding.token_to_idx[d[0]],
token_embedding.token_to_idx[d[1]], d[2]
] for d in dataset if d[0] in token_embedding.token_to_idx
and d[1] in token_embedding.token_to_idx]
num_dropped = initial_length - len(dataset_coded)
# All words are unknown
if not len(dataset_coded):
correlation = 0
else:
words1, words2, scores = zip(*dataset_coded)
pred_similarity = evaluator(
mx.nd.array(words1, ctx=ctx), mx.nd.array(words2, ctx=ctx))
sr = stats.spearmanr(pred_similarity.asnumpy(),
np.array(scores))
correlation = sr.correlation
logging.info(
'Spearman rank correlation on %s (%s pairs) %s with %s:\t%s',
dataset.__class__.__name__, len(dataset_coded),
str(dataset_kwargs), similarity_function, correlation)
result = dict(
task='similarity',
dataset_name=dataset_name,
dataset_kwargs=dataset_kwargs,
similarity_function=similarity_function,
spearmanr=correlation,
num_dropped=num_dropped,
global_step=global_step,
)
log_similarity_result(logfile, result)
results.append(result)
return results | python | def evaluate_similarity(args, token_embedding, ctx, logfile=None,
global_step=0):
"""Evaluate on specified similarity datasets."""
results = []
for similarity_function in args.similarity_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
idx_to_vec=token_embedding.idx_to_vec,
similarity_function=similarity_function)
evaluator.initialize(ctx=ctx)
if not args.no_hybridize:
evaluator.hybridize()
# Evaluate all datasets
for (dataset_name, dataset_kwargs,
dataset) in iterate_similarity_datasets(args):
initial_length = len(dataset)
dataset_coded = [[
token_embedding.token_to_idx[d[0]],
token_embedding.token_to_idx[d[1]], d[2]
] for d in dataset if d[0] in token_embedding.token_to_idx
and d[1] in token_embedding.token_to_idx]
num_dropped = initial_length - len(dataset_coded)
# All words are unknown
if not len(dataset_coded):
correlation = 0
else:
words1, words2, scores = zip(*dataset_coded)
pred_similarity = evaluator(
mx.nd.array(words1, ctx=ctx), mx.nd.array(words2, ctx=ctx))
sr = stats.spearmanr(pred_similarity.asnumpy(),
np.array(scores))
correlation = sr.correlation
logging.info(
'Spearman rank correlation on %s (%s pairs) %s with %s:\t%s',
dataset.__class__.__name__, len(dataset_coded),
str(dataset_kwargs), similarity_function, correlation)
result = dict(
task='similarity',
dataset_name=dataset_name,
dataset_kwargs=dataset_kwargs,
similarity_function=similarity_function,
spearmanr=correlation,
num_dropped=num_dropped,
global_step=global_step,
)
log_similarity_result(logfile, result)
results.append(result)
return results | [
"def",
"evaluate_similarity",
"(",
"args",
",",
"token_embedding",
",",
"ctx",
",",
"logfile",
"=",
"None",
",",
"global_step",
"=",
"0",
")",
":",
"results",
"=",
"[",
"]",
"for",
"similarity_function",
"in",
"args",
".",
"similarity_functions",
":",
"evalu... | Evaluate on specified similarity datasets. | [
"Evaluate",
"on",
"specified",
"similarity",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L145-L197 |
32,584 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | evaluate_analogy | def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_words = not args.analogy_dont_exclude_question_words
for analogy_function in args.analogy_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingAnalogy(
idx_to_vec=token_embedding.idx_to_vec,
exclude_question_words=exclude_question_words,
analogy_function=analogy_function)
evaluator.initialize(ctx=ctx)
if not args.no_hybridize:
evaluator.hybridize()
for (dataset_name, dataset_kwargs,
dataset) in iterate_analogy_datasets(args):
initial_length = len(dataset)
dataset_coded = [[
token_embedding.token_to_idx[d[0]],
token_embedding.token_to_idx[d[1]],
token_embedding.token_to_idx[d[2]],
token_embedding.token_to_idx[d[3]]
] for d in dataset if d[0] in token_embedding.token_to_idx
and d[1] in token_embedding.token_to_idx
and d[2] in token_embedding.token_to_idx
and d[3] in token_embedding.token_to_idx]
num_dropped = initial_length - len(dataset_coded)
dataset_coded_batched = mx.gluon.data.DataLoader(
dataset_coded, batch_size=args.eval_batch_size)
acc = mx.metric.Accuracy()
for batch in dataset_coded_batched:
batch = batch.as_in_context(ctx)
words1, words2, words3, words4 = (batch[:, 0], batch[:, 1],
batch[:, 2], batch[:, 3])
pred_idxs = evaluator(words1, words2, words3)
acc.update(pred_idxs[:, 0], words4.astype(np.float32))
logging.info('Accuracy on %s (%s quadruples) %s with %s:\t%s',
dataset.__class__.__name__, len(dataset_coded),
str(dataset_kwargs), analogy_function,
acc.get()[1])
result = dict(
task='analogy',
dataset_name=dataset_name,
dataset_kwargs=dataset_kwargs,
analogy_function=analogy_function,
accuracy=acc.get()[1],
num_dropped=num_dropped,
global_step=global_step,
)
log_analogy_result(logfile, result)
results.append(result)
return results | python | def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_words = not args.analogy_dont_exclude_question_words
for analogy_function in args.analogy_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingAnalogy(
idx_to_vec=token_embedding.idx_to_vec,
exclude_question_words=exclude_question_words,
analogy_function=analogy_function)
evaluator.initialize(ctx=ctx)
if not args.no_hybridize:
evaluator.hybridize()
for (dataset_name, dataset_kwargs,
dataset) in iterate_analogy_datasets(args):
initial_length = len(dataset)
dataset_coded = [[
token_embedding.token_to_idx[d[0]],
token_embedding.token_to_idx[d[1]],
token_embedding.token_to_idx[d[2]],
token_embedding.token_to_idx[d[3]]
] for d in dataset if d[0] in token_embedding.token_to_idx
and d[1] in token_embedding.token_to_idx
and d[2] in token_embedding.token_to_idx
and d[3] in token_embedding.token_to_idx]
num_dropped = initial_length - len(dataset_coded)
dataset_coded_batched = mx.gluon.data.DataLoader(
dataset_coded, batch_size=args.eval_batch_size)
acc = mx.metric.Accuracy()
for batch in dataset_coded_batched:
batch = batch.as_in_context(ctx)
words1, words2, words3, words4 = (batch[:, 0], batch[:, 1],
batch[:, 2], batch[:, 3])
pred_idxs = evaluator(words1, words2, words3)
acc.update(pred_idxs[:, 0], words4.astype(np.float32))
logging.info('Accuracy on %s (%s quadruples) %s with %s:\t%s',
dataset.__class__.__name__, len(dataset_coded),
str(dataset_kwargs), analogy_function,
acc.get()[1])
result = dict(
task='analogy',
dataset_name=dataset_name,
dataset_kwargs=dataset_kwargs,
analogy_function=analogy_function,
accuracy=acc.get()[1],
num_dropped=num_dropped,
global_step=global_step,
)
log_analogy_result(logfile, result)
results.append(result)
return results | [
"def",
"evaluate_analogy",
"(",
"args",
",",
"token_embedding",
",",
"ctx",
",",
"logfile",
"=",
"None",
",",
"global_step",
"=",
"0",
")",
":",
"results",
"=",
"[",
"]",
"exclude_question_words",
"=",
"not",
"args",
".",
"analogy_dont_exclude_question_words",
... | Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens. | [
"Evaluate",
"on",
"specified",
"analogy",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L200-L259 |
32,585 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | log_similarity_result | def log_similarity_result(logfile, result):
"""Log a similarity evaluation result dictionary as TSV to logfile."""
assert result['task'] == 'similarity'
if not logfile:
return
with open(logfile, 'a') as f:
f.write('\t'.join([
str(result['global_step']),
result['task'],
result['dataset_name'],
json.dumps(result['dataset_kwargs']),
result['similarity_function'],
str(result['spearmanr']),
str(result['num_dropped']),
]))
f.write('\n') | python | def log_similarity_result(logfile, result):
"""Log a similarity evaluation result dictionary as TSV to logfile."""
assert result['task'] == 'similarity'
if not logfile:
return
with open(logfile, 'a') as f:
f.write('\t'.join([
str(result['global_step']),
result['task'],
result['dataset_name'],
json.dumps(result['dataset_kwargs']),
result['similarity_function'],
str(result['spearmanr']),
str(result['num_dropped']),
]))
f.write('\n') | [
"def",
"log_similarity_result",
"(",
"logfile",
",",
"result",
")",
":",
"assert",
"result",
"[",
"'task'",
"]",
"==",
"'similarity'",
"if",
"not",
"logfile",
":",
"return",
"with",
"open",
"(",
"logfile",
",",
"'a'",
")",
"as",
"f",
":",
"f",
".",
"wr... | Log a similarity evaluation result dictionary as TSV to logfile. | [
"Log",
"a",
"similarity",
"evaluation",
"result",
"dictionary",
"as",
"TSV",
"to",
"logfile",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L262-L280 |
32,586 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | get_model_loss | def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
"""Get model for pre-training."""
# model
model, vocabulary = nlp.model.get_model(model,
dataset_name=dataset_name,
pretrained=pretrained, ctx=ctx)
if not pretrained:
model.initialize(init=mx.init.Normal(0.02), ctx=ctx)
model.cast(dtype)
if ckpt_dir and start_step:
param_path = os.path.join(ckpt_dir, '%07d.params'%start_step)
model.load_parameters(param_path, ctx=ctx)
logging.info('Loading step %d checkpoints from %s.', start_step, param_path)
model.hybridize(static_alloc=True)
# losses
nsp_loss = mx.gluon.loss.SoftmaxCELoss()
mlm_loss = mx.gluon.loss.SoftmaxCELoss()
nsp_loss.hybridize(static_alloc=True)
mlm_loss.hybridize(static_alloc=True)
return model, nsp_loss, mlm_loss, vocabulary | python | def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
"""Get model for pre-training."""
# model
model, vocabulary = nlp.model.get_model(model,
dataset_name=dataset_name,
pretrained=pretrained, ctx=ctx)
if not pretrained:
model.initialize(init=mx.init.Normal(0.02), ctx=ctx)
model.cast(dtype)
if ckpt_dir and start_step:
param_path = os.path.join(ckpt_dir, '%07d.params'%start_step)
model.load_parameters(param_path, ctx=ctx)
logging.info('Loading step %d checkpoints from %s.', start_step, param_path)
model.hybridize(static_alloc=True)
# losses
nsp_loss = mx.gluon.loss.SoftmaxCELoss()
mlm_loss = mx.gluon.loss.SoftmaxCELoss()
nsp_loss.hybridize(static_alloc=True)
mlm_loss.hybridize(static_alloc=True)
return model, nsp_loss, mlm_loss, vocabulary | [
"def",
"get_model_loss",
"(",
"ctx",
",",
"model",
",",
"pretrained",
",",
"dataset_name",
",",
"dtype",
",",
"ckpt_dir",
"=",
"None",
",",
"start_step",
"=",
"None",
")",
":",
"# model",
"model",
",",
"vocabulary",
"=",
"nlp",
".",
"model",
".",
"get_mo... | Get model for pre-training. | [
"Get",
"model",
"for",
"pre",
"-",
"training",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L36-L60 |
32,587 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | get_pretrain_dataset | def get_pretrain_dataset(data, batch_size, num_ctxes, shuffle, use_avg_len,
num_buckets, num_parts=1, part_idx=0, prefetch=True):
"""create dataset for pretraining."""
num_files = len(glob.glob(os.path.expanduser(data)))
logging.debug('%d files found.', num_files)
assert num_files >= num_parts, \
'Number of training files must be greater than the number of partitions'
split_sampler = nlp.data.SplitSampler(num_files, num_parts=num_parts, part_index=part_idx)
stream = nlp.data.SimpleDatasetStream(nlp.data.NumpyDataset, data, split_sampler)
if prefetch:
stream = nlp.data.PrefetchingStream(stream)
def get_dataloader(dataset):
"""create data loader based on the dataset chunk"""
lengths = dataset.get_field('valid_lengths')
# A batch includes: input_id, masked_id, masked_position, masked_weight,
# next_sentence_label, segment_id, valid_length
batchify_fn = Tuple(Pad(), Pad(), Pad(), Pad(), Stack(), Pad(), Stack())
if use_avg_len:
# sharded data loader
sampler = nlp.data.FixedBucketSampler(lengths=lengths,
# batch_size per shard
batch_size=batch_size,
num_buckets=num_buckets,
shuffle=shuffle,
use_average_length=True,
num_shards=num_ctxes)
dataloader = nlp.data.ShardedDataLoader(dataset,
batch_sampler=sampler,
batchify_fn=batchify_fn,
num_workers=num_ctxes)
else:
sampler = nlp.data.FixedBucketSampler(lengths,
batch_size=batch_size * num_ctxes,
num_buckets=num_buckets,
ratio=0,
shuffle=shuffle)
dataloader = DataLoader(dataset=dataset,
batch_sampler=sampler,
batchify_fn=batchify_fn,
num_workers=1)
logging.debug('Sampler created for a new dataset:\n%s', sampler.stats())
return dataloader
stream = stream.transform(get_dataloader)
return stream | python | def get_pretrain_dataset(data, batch_size, num_ctxes, shuffle, use_avg_len,
num_buckets, num_parts=1, part_idx=0, prefetch=True):
"""create dataset for pretraining."""
num_files = len(glob.glob(os.path.expanduser(data)))
logging.debug('%d files found.', num_files)
assert num_files >= num_parts, \
'Number of training files must be greater than the number of partitions'
split_sampler = nlp.data.SplitSampler(num_files, num_parts=num_parts, part_index=part_idx)
stream = nlp.data.SimpleDatasetStream(nlp.data.NumpyDataset, data, split_sampler)
if prefetch:
stream = nlp.data.PrefetchingStream(stream)
def get_dataloader(dataset):
"""create data loader based on the dataset chunk"""
lengths = dataset.get_field('valid_lengths')
# A batch includes: input_id, masked_id, masked_position, masked_weight,
# next_sentence_label, segment_id, valid_length
batchify_fn = Tuple(Pad(), Pad(), Pad(), Pad(), Stack(), Pad(), Stack())
if use_avg_len:
# sharded data loader
sampler = nlp.data.FixedBucketSampler(lengths=lengths,
# batch_size per shard
batch_size=batch_size,
num_buckets=num_buckets,
shuffle=shuffle,
use_average_length=True,
num_shards=num_ctxes)
dataloader = nlp.data.ShardedDataLoader(dataset,
batch_sampler=sampler,
batchify_fn=batchify_fn,
num_workers=num_ctxes)
else:
sampler = nlp.data.FixedBucketSampler(lengths,
batch_size=batch_size * num_ctxes,
num_buckets=num_buckets,
ratio=0,
shuffle=shuffle)
dataloader = DataLoader(dataset=dataset,
batch_sampler=sampler,
batchify_fn=batchify_fn,
num_workers=1)
logging.debug('Sampler created for a new dataset:\n%s', sampler.stats())
return dataloader
stream = stream.transform(get_dataloader)
return stream | [
"def",
"get_pretrain_dataset",
"(",
"data",
",",
"batch_size",
",",
"num_ctxes",
",",
"shuffle",
",",
"use_avg_len",
",",
"num_buckets",
",",
"num_parts",
"=",
"1",
",",
"part_idx",
"=",
"0",
",",
"prefetch",
"=",
"True",
")",
":",
"num_files",
"=",
"len",... | create dataset for pretraining. | [
"create",
"dataset",
"for",
"pretraining",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L62-L107 |
32,588 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | get_dummy_dataloader | def get_dummy_dataloader(dataloader, target_shape):
"""Return a dummy data loader which returns a fixed data batch of target shape"""
data_iter = enumerate(dataloader)
_, data_batch = next(data_iter)
logging.debug('Searching target batch shape: %s', target_shape)
while data_batch[0].shape != target_shape:
logging.debug('Skip batch with shape %s', data_batch[0].shape)
_, data_batch = next(data_iter)
logging.debug('Found target dummy batch.')
class DummyIter():
def __init__(self, batch):
self._batch = batch
def __iter__(self):
while True:
yield self._batch
return DummyIter(data_batch) | python | def get_dummy_dataloader(dataloader, target_shape):
"""Return a dummy data loader which returns a fixed data batch of target shape"""
data_iter = enumerate(dataloader)
_, data_batch = next(data_iter)
logging.debug('Searching target batch shape: %s', target_shape)
while data_batch[0].shape != target_shape:
logging.debug('Skip batch with shape %s', data_batch[0].shape)
_, data_batch = next(data_iter)
logging.debug('Found target dummy batch.')
class DummyIter():
def __init__(self, batch):
self._batch = batch
def __iter__(self):
while True:
yield self._batch
return DummyIter(data_batch) | [
"def",
"get_dummy_dataloader",
"(",
"dataloader",
",",
"target_shape",
")",
":",
"data_iter",
"=",
"enumerate",
"(",
"dataloader",
")",
"_",
",",
"data_batch",
"=",
"next",
"(",
"data_iter",
")",
"logging",
".",
"debug",
"(",
"'Searching target batch shape: %s'",
... | Return a dummy data loader which returns a fixed data batch of target shape | [
"Return",
"a",
"dummy",
"data",
"loader",
"which",
"returns",
"a",
"fixed",
"data",
"batch",
"of",
"target",
"shape"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L109-L127 |
32,589 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | save_params | def save_params(step_num, model, trainer, ckpt_dir):
"""Save the model parameter, marked by step_num."""
param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)
trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)
logging.info('[step %d] Saving checkpoints to %s, %s.',
step_num, param_path, trainer_path)
model.save_parameters(param_path)
trainer.save_states(trainer_path) | python | def save_params(step_num, model, trainer, ckpt_dir):
"""Save the model parameter, marked by step_num."""
param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)
trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)
logging.info('[step %d] Saving checkpoints to %s, %s.',
step_num, param_path, trainer_path)
model.save_parameters(param_path)
trainer.save_states(trainer_path) | [
"def",
"save_params",
"(",
"step_num",
",",
"model",
",",
"trainer",
",",
"ckpt_dir",
")",
":",
"param_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ckpt_dir",
",",
"'%07d.params'",
"%",
"step_num",
")",
"trainer_path",
"=",
"os",
".",
"path",
".",
... | Save the model parameter, marked by step_num. | [
"Save",
"the",
"model",
"parameter",
"marked",
"by",
"step_num",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L129-L136 |
32,590 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | log | def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num,
mlm_metric, nsp_metric, trainer, log_interval):
"""Log training progress."""
end_time = time.time()
duration = end_time - begin_time
throughput = running_num_tks / duration / 1000.0
running_mlm_loss = running_mlm_loss / log_interval
running_nsp_loss = running_nsp_loss / log_interval
lr = trainer.learning_rate if trainer else 0
# pylint: disable=line-too-long
logging.info('[step {}]\tmlm_loss={:.5f}\tmlm_acc={:.5f}\tnsp_loss={:.5f}\tnsp_acc={:.3f}\tthroughput={:.1f}K tks/s\tlr={:.7f} time={:.2f}, latency={:.1f} ms/batch'
.format(step_num, running_mlm_loss.asscalar(), mlm_metric.get()[1] * 100, running_nsp_loss.asscalar(),
nsp_metric.get()[1] * 100, throughput.asscalar(), lr, duration, duration*1000/log_interval)) | python | def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num,
mlm_metric, nsp_metric, trainer, log_interval):
"""Log training progress."""
end_time = time.time()
duration = end_time - begin_time
throughput = running_num_tks / duration / 1000.0
running_mlm_loss = running_mlm_loss / log_interval
running_nsp_loss = running_nsp_loss / log_interval
lr = trainer.learning_rate if trainer else 0
# pylint: disable=line-too-long
logging.info('[step {}]\tmlm_loss={:.5f}\tmlm_acc={:.5f}\tnsp_loss={:.5f}\tnsp_acc={:.3f}\tthroughput={:.1f}K tks/s\tlr={:.7f} time={:.2f}, latency={:.1f} ms/batch'
.format(step_num, running_mlm_loss.asscalar(), mlm_metric.get()[1] * 100, running_nsp_loss.asscalar(),
nsp_metric.get()[1] * 100, throughput.asscalar(), lr, duration, duration*1000/log_interval)) | [
"def",
"log",
"(",
"begin_time",
",",
"running_num_tks",
",",
"running_mlm_loss",
",",
"running_nsp_loss",
",",
"step_num",
",",
"mlm_metric",
",",
"nsp_metric",
",",
"trainer",
",",
"log_interval",
")",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"... | Log training progress. | [
"Log",
"training",
"progress",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L138-L150 |
32,591 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | split_and_load | def split_and_load(arrs, ctx):
"""split and load arrays to a list of contexts"""
assert isinstance(arrs, (list, tuple))
# split and load
loaded_arrs = [mx.gluon.utils.split_and_load(arr, ctx, even_split=False) for arr in arrs]
return zip(*loaded_arrs) | python | def split_and_load(arrs, ctx):
"""split and load arrays to a list of contexts"""
assert isinstance(arrs, (list, tuple))
# split and load
loaded_arrs = [mx.gluon.utils.split_and_load(arr, ctx, even_split=False) for arr in arrs]
return zip(*loaded_arrs) | [
"def",
"split_and_load",
"(",
"arrs",
",",
"ctx",
")",
":",
"assert",
"isinstance",
"(",
"arrs",
",",
"(",
"list",
",",
"tuple",
")",
")",
"# split and load",
"loaded_arrs",
"=",
"[",
"mx",
".",
"gluon",
".",
"utils",
".",
"split_and_load",
"(",
"arr",
... | split and load arrays to a list of contexts | [
"split",
"and",
"load",
"arrays",
"to",
"a",
"list",
"of",
"contexts"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L153-L158 |
32,592 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | forward | def forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype):
"""forward computation for evaluation"""
(input_id, masked_id, masked_position, masked_weight, \
next_sentence_label, segment_id, valid_length) = data
num_masks = masked_weight.sum() + 1e-8
valid_length = valid_length.reshape(-1)
masked_id = masked_id.reshape(-1)
valid_length_typed = valid_length.astype(dtype, copy=False)
_, _, classified, decoded = model(input_id, segment_id, valid_length_typed,
masked_position)
decoded = decoded.reshape((-1, vocab_size))
ls1 = mlm_loss(decoded.astype('float32', copy=False),
masked_id, masked_weight.reshape((-1, 1)))
ls2 = nsp_loss(classified.astype('float32', copy=False), next_sentence_label)
ls1 = ls1.sum() / num_masks
ls2 = ls2.mean()
ls = ls1 + ls2
return ls, next_sentence_label, classified, masked_id, decoded, \
masked_weight, ls1, ls2, valid_length.astype('float32', copy=False) | python | def forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype):
"""forward computation for evaluation"""
(input_id, masked_id, masked_position, masked_weight, \
next_sentence_label, segment_id, valid_length) = data
num_masks = masked_weight.sum() + 1e-8
valid_length = valid_length.reshape(-1)
masked_id = masked_id.reshape(-1)
valid_length_typed = valid_length.astype(dtype, copy=False)
_, _, classified, decoded = model(input_id, segment_id, valid_length_typed,
masked_position)
decoded = decoded.reshape((-1, vocab_size))
ls1 = mlm_loss(decoded.astype('float32', copy=False),
masked_id, masked_weight.reshape((-1, 1)))
ls2 = nsp_loss(classified.astype('float32', copy=False), next_sentence_label)
ls1 = ls1.sum() / num_masks
ls2 = ls2.mean()
ls = ls1 + ls2
return ls, next_sentence_label, classified, masked_id, decoded, \
masked_weight, ls1, ls2, valid_length.astype('float32', copy=False) | [
"def",
"forward",
"(",
"data",
",",
"model",
",",
"mlm_loss",
",",
"nsp_loss",
",",
"vocab_size",
",",
"dtype",
")",
":",
"(",
"input_id",
",",
"masked_id",
",",
"masked_position",
",",
"masked_weight",
",",
"next_sentence_label",
",",
"segment_id",
",",
"va... | forward computation for evaluation | [
"forward",
"computation",
"for",
"evaluation"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L161-L179 |
32,593 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | evaluate | def evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype):
"""Evaluation function."""
mlm_metric = MaskedAccuracy()
nsp_metric = MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
eval_begin_time = time.time()
begin_time = time.time()
step_num = 0
running_mlm_loss = running_nsp_loss = 0
total_mlm_loss = total_nsp_loss = 0
running_num_tks = 0
for _, dataloader in enumerate(data_eval):
for _, data_batch in enumerate(dataloader):
step_num += 1
data_list = split_and_load(data_batch, ctx)
loss_list = []
ns_label_list, ns_pred_list = [], []
mask_label_list, mask_pred_list, mask_weight_list = [], [], []
for data in data_list:
out = forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype)
(ls, next_sentence_label, classified, masked_id,
decoded, masked_weight, ls1, ls2, valid_length) = out
loss_list.append(ls)
ns_label_list.append(next_sentence_label)
ns_pred_list.append(classified)
mask_label_list.append(masked_id)
mask_pred_list.append(decoded)
mask_weight_list.append(masked_weight)
running_mlm_loss += ls1.as_in_context(mx.cpu())
running_nsp_loss += ls2.as_in_context(mx.cpu())
running_num_tks += valid_length.sum().as_in_context(mx.cpu())
nsp_metric.update(ns_label_list, ns_pred_list)
mlm_metric.update(mask_label_list, mask_pred_list, mask_weight_list)
# logging
if (step_num + 1) % (log_interval) == 0:
total_mlm_loss += running_mlm_loss
total_nsp_loss += running_nsp_loss
log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss,
step_num, mlm_metric, nsp_metric, None, log_interval)
begin_time = time.time()
running_mlm_loss = running_nsp_loss = running_num_tks = 0
mlm_metric.reset_local()
nsp_metric.reset_local()
mx.nd.waitall()
eval_end_time = time.time()
total_mlm_loss /= step_num
total_nsp_loss /= step_num
logging.info('mlm_loss={:.3f}\tmlm_acc={:.1f}\tnsp_loss={:.3f}\tnsp_acc={:.1f}\t'
.format(total_mlm_loss.asscalar(), mlm_metric.get_global()[1] * 100,
total_nsp_loss.asscalar(), nsp_metric.get_global()[1] * 100))
logging.info('Eval cost={:.1f}s'.format(eval_end_time - eval_begin_time)) | python | def evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype):
"""Evaluation function."""
mlm_metric = MaskedAccuracy()
nsp_metric = MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
eval_begin_time = time.time()
begin_time = time.time()
step_num = 0
running_mlm_loss = running_nsp_loss = 0
total_mlm_loss = total_nsp_loss = 0
running_num_tks = 0
for _, dataloader in enumerate(data_eval):
for _, data_batch in enumerate(dataloader):
step_num += 1
data_list = split_and_load(data_batch, ctx)
loss_list = []
ns_label_list, ns_pred_list = [], []
mask_label_list, mask_pred_list, mask_weight_list = [], [], []
for data in data_list:
out = forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype)
(ls, next_sentence_label, classified, masked_id,
decoded, masked_weight, ls1, ls2, valid_length) = out
loss_list.append(ls)
ns_label_list.append(next_sentence_label)
ns_pred_list.append(classified)
mask_label_list.append(masked_id)
mask_pred_list.append(decoded)
mask_weight_list.append(masked_weight)
running_mlm_loss += ls1.as_in_context(mx.cpu())
running_nsp_loss += ls2.as_in_context(mx.cpu())
running_num_tks += valid_length.sum().as_in_context(mx.cpu())
nsp_metric.update(ns_label_list, ns_pred_list)
mlm_metric.update(mask_label_list, mask_pred_list, mask_weight_list)
# logging
if (step_num + 1) % (log_interval) == 0:
total_mlm_loss += running_mlm_loss
total_nsp_loss += running_nsp_loss
log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss,
step_num, mlm_metric, nsp_metric, None, log_interval)
begin_time = time.time()
running_mlm_loss = running_nsp_loss = running_num_tks = 0
mlm_metric.reset_local()
nsp_metric.reset_local()
mx.nd.waitall()
eval_end_time = time.time()
total_mlm_loss /= step_num
total_nsp_loss /= step_num
logging.info('mlm_loss={:.3f}\tmlm_acc={:.1f}\tnsp_loss={:.3f}\tnsp_acc={:.1f}\t'
.format(total_mlm_loss.asscalar(), mlm_metric.get_global()[1] * 100,
total_nsp_loss.asscalar(), nsp_metric.get_global()[1] * 100))
logging.info('Eval cost={:.1f}s'.format(eval_end_time - eval_begin_time)) | [
"def",
"evaluate",
"(",
"data_eval",
",",
"model",
",",
"nsp_loss",
",",
"mlm_loss",
",",
"vocab_size",
",",
"ctx",
",",
"log_interval",
",",
"dtype",
")",
":",
"mlm_metric",
"=",
"MaskedAccuracy",
"(",
")",
"nsp_metric",
"=",
"MaskedAccuracy",
"(",
")",
"... | Evaluation function. | [
"Evaluation",
"function",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L182-L238 |
32,594 | dmlc/gluon-nlp | scripts/machine_translation/dataprocessor.py | _cache_dataset | def _cache_dataset(dataset, prefix):
"""Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str
"""
if not os.path.exists(_constants.CACHE_PATH):
os.makedirs(_constants.CACHE_PATH)
src_data = np.concatenate([e[0] for e in dataset])
tgt_data = np.concatenate([e[1] for e in dataset])
src_cumlen = np.cumsum([0]+[len(e[0]) for e in dataset])
tgt_cumlen = np.cumsum([0]+[len(e[1]) for e in dataset])
np.savez(os.path.join(_constants.CACHE_PATH, prefix + '.npz'),
src_data=src_data, tgt_data=tgt_data,
src_cumlen=src_cumlen, tgt_cumlen=tgt_cumlen) | python | def _cache_dataset(dataset, prefix):
"""Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str
"""
if not os.path.exists(_constants.CACHE_PATH):
os.makedirs(_constants.CACHE_PATH)
src_data = np.concatenate([e[0] for e in dataset])
tgt_data = np.concatenate([e[1] for e in dataset])
src_cumlen = np.cumsum([0]+[len(e[0]) for e in dataset])
tgt_cumlen = np.cumsum([0]+[len(e[1]) for e in dataset])
np.savez(os.path.join(_constants.CACHE_PATH, prefix + '.npz'),
src_data=src_data, tgt_data=tgt_data,
src_cumlen=src_cumlen, tgt_cumlen=tgt_cumlen) | [
"def",
"_cache_dataset",
"(",
"dataset",
",",
"prefix",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"_constants",
".",
"CACHE_PATH",
")",
":",
"os",
".",
"makedirs",
"(",
"_constants",
".",
"CACHE_PATH",
")",
"src_data",
"=",
"np",
".... | Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str | [
"Cache",
"the",
"processed",
"npy",
"dataset",
"the",
"dataset",
"into",
"a",
"npz"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/dataprocessor.py#L33-L49 |
32,595 | dmlc/gluon-nlp | src/gluonnlp/model/train/embedding.py | FasttextEmbeddingModel.load_fasttext_format | def load_fasttext_format(cls, path, ctx=cpu(), **kwargs):
"""Create an instance of the class and load weights.
Load the weights from the fastText binary format created by
https://github.com/facebookresearch/fastText
Parameters
----------
path : str
Path to the .bin model file.
ctx : mx.Context, default mx.cpu()
Context to initialize the weights on.
kwargs : dict
Keyword arguments are passed to the class initializer.
"""
with open(path, 'rb') as f:
new_format, dim, bucket, minn, maxn, = cls._read_model_params(f)
idx_to_token = cls._read_vocab(f, new_format)
dim, matrix = cls._read_vectors(f, new_format, bucket,
len(idx_to_token))
token_to_idx = {token: idx for idx, token in enumerate(idx_to_token)}
if len(token_to_idx) != len(idx_to_token):
# If multiple tokens with invalid encoding were collapsed in a
# single token due to replacement of invalid bytes with Unicode
# replacement character
warnings.warn(
'There are duplicate tokens in the embedding file. '
'This is likely due to decoding errors for some tokens, '
'where invalid bytes were replaced by '
'the Unicode replacement character. '
'This affects {} tokens.'.format(
len(idx_to_token) - len(token_to_idx)))
for _ in range(len(token_to_idx), len(idx_to_token)):
# Add pseudo tokens to make sure length is the same
token_to_idx[object()] = -1
assert len(token_to_idx) == len(idx_to_token)
subword_function = create_subword_function(
'NGramHashes', num_subwords=matrix.shape[0] - len(idx_to_token),
ngrams=list(range(minn, maxn + 1)), special_tokens={'</s>'})
self = cls(token_to_idx, subword_function, output_dim=dim, **kwargs)
self.initialize(ctx=ctx)
self.weight.set_data(nd.array(matrix))
return self | python | def load_fasttext_format(cls, path, ctx=cpu(), **kwargs):
"""Create an instance of the class and load weights.
Load the weights from the fastText binary format created by
https://github.com/facebookresearch/fastText
Parameters
----------
path : str
Path to the .bin model file.
ctx : mx.Context, default mx.cpu()
Context to initialize the weights on.
kwargs : dict
Keyword arguments are passed to the class initializer.
"""
with open(path, 'rb') as f:
new_format, dim, bucket, minn, maxn, = cls._read_model_params(f)
idx_to_token = cls._read_vocab(f, new_format)
dim, matrix = cls._read_vectors(f, new_format, bucket,
len(idx_to_token))
token_to_idx = {token: idx for idx, token in enumerate(idx_to_token)}
if len(token_to_idx) != len(idx_to_token):
# If multiple tokens with invalid encoding were collapsed in a
# single token due to replacement of invalid bytes with Unicode
# replacement character
warnings.warn(
'There are duplicate tokens in the embedding file. '
'This is likely due to decoding errors for some tokens, '
'where invalid bytes were replaced by '
'the Unicode replacement character. '
'This affects {} tokens.'.format(
len(idx_to_token) - len(token_to_idx)))
for _ in range(len(token_to_idx), len(idx_to_token)):
# Add pseudo tokens to make sure length is the same
token_to_idx[object()] = -1
assert len(token_to_idx) == len(idx_to_token)
subword_function = create_subword_function(
'NGramHashes', num_subwords=matrix.shape[0] - len(idx_to_token),
ngrams=list(range(minn, maxn + 1)), special_tokens={'</s>'})
self = cls(token_to_idx, subword_function, output_dim=dim, **kwargs)
self.initialize(ctx=ctx)
self.weight.set_data(nd.array(matrix))
return self | [
"def",
"load_fasttext_format",
"(",
"cls",
",",
"path",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"new_format",
",",
"dim",
",",
"bucket",
",",
"minn",
",",... | Create an instance of the class and load weights.
Load the weights from the fastText binary format created by
https://github.com/facebookresearch/fastText
Parameters
----------
path : str
Path to the .bin model file.
ctx : mx.Context, default mx.cpu()
Context to initialize the weights on.
kwargs : dict
Keyword arguments are passed to the class initializer. | [
"Create",
"an",
"instance",
"of",
"the",
"class",
"and",
"load",
"weights",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/embedding.py#L232-L280 |
32,596 | dmlc/gluon-nlp | scripts/natural_language_inference/utils.py | logging_config | def logging_config(logpath=None,
level=logging.DEBUG,
console_level=logging.INFO,
no_console=False):
"""
Config the logging.
"""
logger = logging.getLogger('nli')
# Remove all the current handlers
for handler in logger.handlers:
logger.removeHandler(handler)
logger.handlers = []
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(filename)s:%(funcName)s: %(message)s')
if logpath is not None:
print('All Logs will be saved to {}'.format(logpath))
logfile = logging.FileHandler(logpath, mode='w')
logfile.setLevel(level)
logfile.setFormatter(formatter)
logger.addHandler(logfile)
if not no_console:
# Initialze the console logging
logconsole = logging.StreamHandler()
logconsole.setLevel(console_level)
logconsole.setFormatter(formatter)
logger.addHandler(logconsole) | python | def logging_config(logpath=None,
level=logging.DEBUG,
console_level=logging.INFO,
no_console=False):
"""
Config the logging.
"""
logger = logging.getLogger('nli')
# Remove all the current handlers
for handler in logger.handlers:
logger.removeHandler(handler)
logger.handlers = []
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(filename)s:%(funcName)s: %(message)s')
if logpath is not None:
print('All Logs will be saved to {}'.format(logpath))
logfile = logging.FileHandler(logpath, mode='w')
logfile.setLevel(level)
logfile.setFormatter(formatter)
logger.addHandler(logfile)
if not no_console:
# Initialze the console logging
logconsole = logging.StreamHandler()
logconsole.setLevel(console_level)
logconsole.setFormatter(formatter)
logger.addHandler(logconsole) | [
"def",
"logging_config",
"(",
"logpath",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"console_level",
"=",
"logging",
".",
"INFO",
",",
"no_console",
"=",
"False",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'nli'",
")",... | Config the logging. | [
"Config",
"the",
"logging",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/utils.py#L27-L56 |
32,597 | dmlc/gluon-nlp | scripts/word_embeddings/train_glove.py | get_train_data | def get_train_data(args):
"""Helper function to get training data."""
counter = dict()
with io.open(args.vocab, 'r', encoding='utf-8') as f:
for line in f:
token, count = line.split('\t')
counter[token] = int(count)
vocab = nlp.Vocab(counter, unknown_token=None, padding_token=None,
bos_token=None, eos_token=None, min_freq=1)
npz = np.load(args.cooccurrences)
row, col, counts = npz['row'], npz['col'], npz['data']
rank_dtype = 'int32'
if row.max() >= np.iinfo(np.int32).max:
rank_dtype = 'int64'
# MXNet has no support for uint32, so we must fall back to int64
logging.info('More words than could be counted using int32. '
'Using int64 to represent word indices.')
row = mx.nd.array(row, dtype=rank_dtype)
col = mx.nd.array(col, dtype=rank_dtype)
# row is always used as 'source' and col as 'context' word. Therefore
# duplicate the entries.
assert row.shape == col.shape
row = mx.nd.concatenate([row, col])
col = mx.nd.concatenate([col, row[:len(row) // 2]])
counts = mx.nd.array(counts, dtype='float32')
counts = mx.nd.concatenate([counts, counts])
return vocab, row, col, counts | python | def get_train_data(args):
"""Helper function to get training data."""
counter = dict()
with io.open(args.vocab, 'r', encoding='utf-8') as f:
for line in f:
token, count = line.split('\t')
counter[token] = int(count)
vocab = nlp.Vocab(counter, unknown_token=None, padding_token=None,
bos_token=None, eos_token=None, min_freq=1)
npz = np.load(args.cooccurrences)
row, col, counts = npz['row'], npz['col'], npz['data']
rank_dtype = 'int32'
if row.max() >= np.iinfo(np.int32).max:
rank_dtype = 'int64'
# MXNet has no support for uint32, so we must fall back to int64
logging.info('More words than could be counted using int32. '
'Using int64 to represent word indices.')
row = mx.nd.array(row, dtype=rank_dtype)
col = mx.nd.array(col, dtype=rank_dtype)
# row is always used as 'source' and col as 'context' word. Therefore
# duplicate the entries.
assert row.shape == col.shape
row = mx.nd.concatenate([row, col])
col = mx.nd.concatenate([col, row[:len(row) // 2]])
counts = mx.nd.array(counts, dtype='float32')
counts = mx.nd.concatenate([counts, counts])
return vocab, row, col, counts | [
"def",
"get_train_data",
"(",
"args",
")",
":",
"counter",
"=",
"dict",
"(",
")",
"with",
"io",
".",
"open",
"(",
"args",
".",
"vocab",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"token",
",",... | Helper function to get training data. | [
"Helper",
"function",
"to",
"get",
"training",
"data",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L130-L161 |
32,598 | dmlc/gluon-nlp | scripts/word_embeddings/train_glove.py | log | def log(args, kwargs):
"""Log to a file."""
logfile = os.path.join(args.logdir, 'log.tsv')
if 'log_created' not in globals():
if os.path.exists(logfile):
logging.error('Logfile %s already exists.', logfile)
sys.exit(1)
global log_created
log_created = sorted(kwargs.keys())
header = '\t'.join((str(k) for k in log_created)) + '\n'
with open(logfile, 'w') as f:
f.write(header)
# Log variables shouldn't change during training
assert log_created == sorted(kwargs.keys())
with open(logfile, 'a') as f:
f.write('\t'.join((str(kwargs[k]) for k in log_created)) + '\n') | python | def log(args, kwargs):
"""Log to a file."""
logfile = os.path.join(args.logdir, 'log.tsv')
if 'log_created' not in globals():
if os.path.exists(logfile):
logging.error('Logfile %s already exists.', logfile)
sys.exit(1)
global log_created
log_created = sorted(kwargs.keys())
header = '\t'.join((str(k) for k in log_created)) + '\n'
with open(logfile, 'w') as f:
f.write(header)
# Log variables shouldn't change during training
assert log_created == sorted(kwargs.keys())
with open(logfile, 'a') as f:
f.write('\t'.join((str(kwargs[k]) for k in log_created)) + '\n') | [
"def",
"log",
"(",
"args",
",",
"kwargs",
")",
":",
"logfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"logdir",
",",
"'log.tsv'",
")",
"if",
"'log_created'",
"not",
"in",
"globals",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"ex... | Log to a file. | [
"Log",
"to",
"a",
"file",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L396-L416 |
32,599 | dmlc/gluon-nlp | src/gluonnlp/metric/masked_accuracy.py | MaskedAccuracy.update | def update(self, labels, preds, masks=None):
# pylint: disable=arguments-differ
"""Updates the internal evaluation result.
Parameters
----------
labels : list of `NDArray`
The labels of the data with class indices as values, one per sample.
preds : list of `NDArray`
Prediction values for samples. Each prediction value can either be the class index,
or a vector of likelihoods for all classes.
masks : list of `NDArray` or None, optional
Masks for samples, with the same shape as `labels`. value of its element must
be either 1 or 0. If None, all samples are considered valid.
"""
labels, preds = check_label_shapes(labels, preds, True)
masks = [None] * len(labels) if masks is None else masks
for label, pred_label, mask in zip(labels, preds, masks):
if pred_label.shape != label.shape:
# TODO(haibin) topk does not support fp16. Issue tracked at:
# https://github.com/apache/incubator-mxnet/issues/14125
# topk is used because argmax is slow:
# https://github.com/apache/incubator-mxnet/issues/11061
pred_label = ndarray.topk(pred_label.astype('float32', copy=False),
k=1, ret_typ='indices', axis=self.axis)
# flatten before checking shapes to avoid shape miss match
pred_label = pred_label.astype('int32', copy=False).reshape((-1,))
label = label.astype('int32', copy=False).reshape((-1,))
check_label_shapes(label, pred_label)
if mask is not None:
mask = mask.astype('int32', copy=False).reshape((-1,))
check_label_shapes(label, mask)
num_correct = ((pred_label == label) * mask).sum().asscalar()
num_inst = mask.sum().asscalar()
else:
num_correct = (pred_label == label).sum().asscalar()
num_inst = len(label)
self.sum_metric += num_correct
self.global_sum_metric += num_correct
self.num_inst += num_inst
self.global_num_inst += num_inst | python | def update(self, labels, preds, masks=None):
# pylint: disable=arguments-differ
"""Updates the internal evaluation result.
Parameters
----------
labels : list of `NDArray`
The labels of the data with class indices as values, one per sample.
preds : list of `NDArray`
Prediction values for samples. Each prediction value can either be the class index,
or a vector of likelihoods for all classes.
masks : list of `NDArray` or None, optional
Masks for samples, with the same shape as `labels`. value of its element must
be either 1 or 0. If None, all samples are considered valid.
"""
labels, preds = check_label_shapes(labels, preds, True)
masks = [None] * len(labels) if masks is None else masks
for label, pred_label, mask in zip(labels, preds, masks):
if pred_label.shape != label.shape:
# TODO(haibin) topk does not support fp16. Issue tracked at:
# https://github.com/apache/incubator-mxnet/issues/14125
# topk is used because argmax is slow:
# https://github.com/apache/incubator-mxnet/issues/11061
pred_label = ndarray.topk(pred_label.astype('float32', copy=False),
k=1, ret_typ='indices', axis=self.axis)
# flatten before checking shapes to avoid shape miss match
pred_label = pred_label.astype('int32', copy=False).reshape((-1,))
label = label.astype('int32', copy=False).reshape((-1,))
check_label_shapes(label, pred_label)
if mask is not None:
mask = mask.astype('int32', copy=False).reshape((-1,))
check_label_shapes(label, mask)
num_correct = ((pred_label == label) * mask).sum().asscalar()
num_inst = mask.sum().asscalar()
else:
num_correct = (pred_label == label).sum().asscalar()
num_inst = len(label)
self.sum_metric += num_correct
self.global_sum_metric += num_correct
self.num_inst += num_inst
self.global_num_inst += num_inst | [
"def",
"update",
"(",
"self",
",",
"labels",
",",
"preds",
",",
"masks",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"labels",
",",
"preds",
"=",
"check_label_shapes",
"(",
"labels",
",",
"preds",
",",
"True",
")",
"masks",
"=",
"[",
"None... | Updates the internal evaluation result.
Parameters
----------
labels : list of `NDArray`
The labels of the data with class indices as values, one per sample.
preds : list of `NDArray`
Prediction values for samples. Each prediction value can either be the class index,
or a vector of likelihoods for all classes.
masks : list of `NDArray` or None, optional
Masks for samples, with the same shape as `labels`. value of its element must
be either 1 or 0. If None, all samples are considered valid. | [
"Updates",
"the",
"internal",
"evaluation",
"result",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/metric/masked_accuracy.py#L232-L275 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.