code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def index(self, q, return_vector=True): """Gets a key for an index or multiple indices.""" if isinstance(q, list) or isinstance(q, tuple): return self._keys_for_indices(q, return_vector=return_vector) else: return self._key_for_index_cached(q, return_vector=return_vector)
Gets a key for an index or multiple indices.
index
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _query_numpy(self, key, contextualize=False, normalized=None): """Returns the query for a key, forcibly converting the resulting vector to a numpy array. """ normalized = normalized if normalized is not None else self.normalized key_is_list = isinstance(key, list) key...
Returns the query for a key, forcibly converting the resulting vector to a numpy array.
_query_numpy
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _query_is_cached(self, key, normalized=None): """Checks if the query been cached by Magnitude.""" normalized = normalized if normalized is not None else self.normalized return ((self._vector_for_key_cached._cache.get((key, frozenset([('normalized', normalized)]))) is not None) or ( # noqa ...
Checks if the query been cached by Magnitude.
_query_is_cached
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def distance(self, key, q): """Calculates the distance from key to the key(s) in q.""" a = self._query_numpy(key, normalized=self.normalized) if not isinstance(q, list): b = self._query_numpy(q, normalized=self.normalized) return np.linalg.norm(a - b) else: ...
Calculates the distance from key to the key(s) in q.
distance
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def similarity(self, key, q): """Calculates the similarity from key to the key(s) in q.""" a = self._query_numpy(key, normalized=True) if not isinstance(q, list): b = self._query_numpy(q, normalized=True) return np.inner(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) ...
Calculates the similarity from key to the key(s) in q.
similarity
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def most_similar_to_given(self, key, q): """Calculates the most similar key in q to key.""" similarities = self.similarity(key, q) min_index, _ = max(enumerate(similarities), key=operator.itemgetter(1)) return q[min_index]
Calculates the most similar key in q to key.
most_similar_to_given
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def doesnt_match(self, q): """Given a set of keys, figures out which key doesn't match the rest. """ mean_vector = np.mean(self._query_numpy( q, contextualize=True, normalized=True), axis=0) mean_unit_vector = mean_vector / np.linalg.norm(mean_vector) distance...
Given a set of keys, figures out which key doesn't match the rest.
doesnt_match
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _db_query_similarity( self, positive, negative, min_similarity=None, topn=10, exclude_keys=set(), return_similarities=False, method='distance', effort=1.0): """Runs a database query to find vectors cl...
Runs a database query to find vectors close to vector.
_db_query_similarity
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def most_similar(self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True): """Finds the topn most similar vectors under or equal to max distance. """ positive, negative = self._handle_pos_neg_args(positive, negative) return self._...
Finds the topn most similar vectors under or equal to max distance.
most_similar
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def most_similar_cosmul(self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True): """Finds the topn most similar vectors under or equal to max distance using 3CosMul: [Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618) """...
Finds the topn most similar vectors under or equal to max distance using 3CosMul: [Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618)
most_similar_cosmul
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def most_similar_approx( self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True, effort=1.0): """Approximates the topn most similar vectors under or equal to max distance using Annoy: ...
Approximates the topn most similar vectors under or equal to max distance using Annoy: https://github.com/spotify/annoy
most_similar_approx
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def closer_than(self, key, q, topn=None): """Finds all keys closer to key than q is to key.""" epsilon = (10.0 / 10**6) min_similarity = self.similarity(key, q) + epsilon return self.most_similar(key, topn=topn, min_similarity=min_similarity, return_simi...
Finds all keys closer to key than q is to key.
closer_than
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def get_vectors_mmap(self, log=True): """Gets a numpy.memmap of all vectors, blocks if it is still being built. """ if self._all_vectors is None: logged = False while True: if not self.setup_for_mmap: self._setup_for_mmap() ...
Gets a numpy.memmap of all vectors, blocks if it is still being built.
get_vectors_mmap
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def get_approx_index_chunks(self): """Gets decompressed chunks of the AnnoyIndex of the vectors from the database.""" try: db = self._db(force_new=True, downloader=True) num_chunks = db.execute( """ SELECT COUNT(rowid) ...
Gets decompressed chunks of the AnnoyIndex of the vectors from the database.
get_approx_index_chunks
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def get_meta_chunks(self, meta_index): """Gets decompressed chunks of a meta file embedded in the database.""" try: db = self._db(force_new=True, downloader=True) num_chunks = db.execute( """ SELECT COUNT(rowid) FROM...
Gets decompressed chunks of a meta file embedded in the database.
get_meta_chunks
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def get_approx_index(self, log=True): """Gets an AnnoyIndex of the vectors from the database.""" chunks = self.get_approx_index_chunks() if self._approx_index is None: logged = False while True: if not self.setup_for_mmap: self._setup_f...
Gets an AnnoyIndex of the vectors from the database.
get_approx_index
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def get_elmo_embedder(self, log=True): """Gets an ElmoEmbedder of the vectors from the database.""" meta_1_chunks = self.get_meta_chunks(1) meta_2_chunks = self.get_meta_chunks(2) if self._elmo_embedder is None: logged = False while True: if not se...
Gets an ElmoEmbedder of the vectors from the database.
get_elmo_embedder
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _iter(self, put_cache, downloader=False): """Yields keys and vectors for all vectors in the store.""" try: db = self._db(force_new=True, downloader=downloader) results = db.execute( """ SELECT * FROM `magnitude` ...
Yields keys and vectors for all vectors in the store.
_iter
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def __getitem__(self, q): """Performs the index method when indexed.""" if isinstance(q, slice): return self.index(list(range(*q.indices(self.length))), return_vector=True) else: return self.index(q, return_vector=True)
Performs the index method when indexed.
__getitem__
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _take(self, q, multikey, i): """Selects only the i'th element from the inner-most axis and reduces the dimensions of the tensor q by 1. """ if multikey == -1: return q else: cut = np.take(q, [i], axis=multikey) result = np.reshape(cut, np.s...
Selects only the i'th element from the inner-most axis and reduces the dimensions of the tensor q by 1.
_take
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _hstack(self, ls, use_numpy): """Horizontally stacks NumPy arrays or Python lists""" if use_numpy: return np.concatenate(ls, axis=-1) else: return list(chain.from_iterable(ls))
Horizontally stacks NumPy arrays or Python lists
_hstack
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _dstack(self, ls, use_numpy): """Depth stacks NumPy arrays or Python lists""" if use_numpy: return np.concatenate(ls, axis=-1) else: return [self._hstack((l3[example] for l3 in ls), use_numpy=use_numpy) for example in xrange(len(ls[0])...
Depth stacks NumPy arrays or Python lists
_dstack
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def query(self, q, pad_to_length=None, pad_left=None, truncate_left=None, normalized=None): """Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys. """ # Check if keys are specified for each concatenated model ...
Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys.
query
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def download_model( model, download_dir=os.path.expanduser('~/.magnitude/'), remote_path='http://magnitude.plasticity.ai/', log=False, _download=True, _local=False): """ Downloads a remote Magnitude model locally (if it doesn't already ...
Downloads a remote Magnitude model locally (if it doesn't already exist) and synchronously returns the local file path once it has been completed
download_model
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def batchify(X, y, batch_size): # noqa: N803 """ Creates an iterator that chunks `X` and `y` into batches that each contain `batch_size` elements and loops forever""" X_batch_generator = cycle([X[i: i + batch_size] # noqa: N806 for i in xrange(0, len(X), batc...
Creates an iterator that chunks `X` and `y` into batches that each contain `batch_size` elements and loops forever
batchify
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def class_encoding(): """Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.""" class_to_int_map = {} int_to_class_map = None def add_class(c): global int_to_class_map int_to_class_map = None ...
Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.
class_encoding
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def to_categorical(y, num_classes=None): """Converts a class vector (integers) to binary class matrix. """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1 and len(input_shape) > 1: input_shape = tuple(input_shape[:-1]) ...
Converts a class vector (integers) to binary class matrix.
to_categorical
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def get_cache(self, amount, offset): """Checks if a cache exists for the data offset, and amount to read, if so, return the cache, and the start and end range to read from the cache's data. Keeps track of forward sequential reads, and backward seq...
Checks if a cache exists for the data offset, and amount to read, if so, return the cache, and the start and end range to read from the cache's data. Keeps track of forward sequential reads, and backward sequential reads for the cache.
get_cache
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def write_data(self, start_offset, data, amount, offset): """Writes data fetched to the network cache and returns only the amount requested back.""" # Writes the entire data fetched to the cache if self.vfsfile.should_cache: # Uses itself as a cache object...
Writes data fetched to the network cache and returns only the amount requested back.
write_data
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def _prefetch_in_background( self, _prefetch_in_background, amount, offset, sequential): """Prefetches data from the network to the cache.""" # Store the extra data fetched back in the network cache if se...
Prefetches data from the network to the cache.
_prefetch_in_background
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def prefetch_in_background( self, _prefetch_in_background, amount, offset, sequential=False): """Prefetches data from the network to the cache in the background.""" if self.vfsfile.trace_log: ...
Prefetches data from the network to the cache in the background.
prefetch_in_background
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def read_data(self, amount, offset, _prefetch_in_background=None): """Reads data from the network cache and returns only the amount requested back or Returns None if there is a cache miss, and prefetches more data into the cache using _prefetch_in_background(amount, offse...
Reads data from the network cache and returns only the amount requested back or Returns None if there is a cache miss, and prefetches more data into the cache using _prefetch_in_background(amount, offset) if it detects a non-sequential access pattern in the ca...
read_data
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def length_of_data(self): """Returns the length of the cached data.""" try: return os.path.getsize(os.path.join(self.cache_dir_path, self.cache_key)) except BaseException: return 0
Returns the length of the cached data.
length_of_data
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def add_to_mmaps(self, new, mm): """Adds a new mmap, evicting old mmaps if the maximum has been reached.""" while (len(self.vfsfile.cache_mmaps_heap) >= self.vfsfile.mmap_max_files): _, evict = heapq.heappop(self.vfsfile.cache_mmaps_heap) ...
Adds a new mmap, evicting old mmaps if the maximum has been reached.
add_to_mmaps
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def get_mmap(self, create=True): """Gets the mmap for a key, opening a mmap to the file if a mmap doesn't exist, creating a file, then opening a mmap to it if the file doesn't exist.""" if (self.cache_key not in self.vfsfile.cache_mmaps and create): joined...
Gets the mmap for a key, opening a mmap to the file if a mmap doesn't exist, creating a file, then opening a mmap to it if the file doesn't exist.
get_mmap
python
plasticityai/magnitude
pymagnitude/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py
MIT
def dry_run_from_args(args ): u""" Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path serialization_dir = args.serialization_dir overrides = args.overrides params = Params.from_file(parameter_path, overrides) dry_run_f...
Just converts from an ``argparse.Namespace`` object to params.
dry_run_from_args
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/dry_run.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/dry_run.py
MIT
def __init__(self, options_file = DEFAULT_OPTIONS_FILE, weight_file = DEFAULT_WEIGHT_FILE, cuda_device = -1) : u""" Parameters ---------- options_file : ``str``, optional A path or URL to an ELMo options...
Parameters ---------- options_file : ``str``, optional A path or URL to an ELMo options file. weight_file : ``str``, optional A path or URL to an ELMo weights file. cuda_device : ``int``, optional, (default=-1) The GPU device to run on. ...
__init__
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/elmo.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py
MIT
def batch_to_embeddings(self, batch ) : u""" Parameters ---------- batch : ``List[List[str]]``, required A list of tokenized sentences. Returns ------- A tuple of tensors, the first representing ...
Parameters ---------- batch : ``List[List[str]]``, required A list of tokenized sentences. Returns ------- A tuple of tensors, the first representing activations (batch_size, 3, num_timesteps, 1024) and the second a mask (batch_size, num_timestep...
batch_to_embeddings
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/elmo.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py
MIT
def embed_batch(self, batch ) : u""" Computes the ELMo embeddings for a batch of tokenized sentences. Please note that ELMo has internal state and will give different results for the same input. See the comment under the class definition. P...
Computes the ELMo embeddings for a batch of tokenized sentences. Please note that ELMo has internal state and will give different results for the same input. See the comment under the class definition. Parameters ---------- batch : ``List[List[str]]``, required ...
embed_batch
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/elmo.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py
MIT
def embed_sentences(self, sentences , batch_size = DEFAULT_BATCH_SIZE) : u""" Computes the ELMo embeddings for a iterable of sentences. Please note that ELMo has internal state and will give diffe...
Computes the ELMo embeddings for a iterable of sentences. Please note that ELMo has internal state and will give different results for the same input. See the comment under the class definition. Parameters ---------- sentences : ``Iterable[List[str]]``, required ...
embed_sentences
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/elmo.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py
MIT
def embed_file(self, input_file , output_file_path , output_format = u"all", batch_size = DEFAULT_BATCH_SIZE, forget_sentences = False, use_sentence_keys = False) : ...
Computes ELMo embeddings from an input_file where each line contains a sentence tokenized by whitespace. The ELMo embeddings are written out in HDF5 format, where each sentence embedding is saved in a dataset with the line number in the original file as the key. Parameters ----...
embed_file
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/elmo.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py
MIT
def fine_tune_model_from_args(args ): u""" Just converts from an ``argparse.Namespace`` object to string paths. """ fine_tune_model_from_file_paths(model_archive_path=args.model_archive, config_file=args.config_file, ...
Just converts from an ``argparse.Namespace`` object to string paths.
fine_tune_model_from_args
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/fine_tune.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/fine_tune.py
MIT
def fine_tune_model_from_file_paths(model_archive_path , config_file , serialization_dir , overrides = u"", extend_vocab = False, ...
A wrapper around :func:`fine_tune_model` which loads the model archive from a file. Parameters ---------- model_archive_path : ``str`` Path to a saved model archive that is the result of running the ``train`` command. config_file : ``str`` A configuration file specifying how to con...
fine_tune_model_from_file_paths
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/fine_tune.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/fine_tune.py
MIT
def fine_tune_model(model , params , serialization_dir , extend_vocab = False, file_friendly_logging = False) : u""" Fine tunes the given model, using a set of parameters that is largely identica...
Fine tunes the given model, using a set of parameters that is largely identical to those used for :func:`~allennlp.commands.train.train_model`, except that the ``model`` section is ignored, if it is present (as we are already given a ``Model`` here). The main difference between the logic done here and...
fine_tune_model
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/fine_tune.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/fine_tune.py
MIT
def make_vocab_from_args(args ): u""" Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path overrides = args.overrides serialization_dir = args.serialization_dir params = Params.from_file(parameter_path, overrides) make_v...
Just converts from an ``argparse.Namespace`` object to params.
make_vocab_from_args
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/make_vocab.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/make_vocab.py
MIT
def train_model_from_args(args ): u""" Just converts from an ``argparse.Namespace`` object to string paths. """ train_model_from_file(args.param_path, args.serialization_dir, args.overrides, args.file_friend...
Just converts from an ``argparse.Namespace`` object to string paths.
train_model_from_args
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/train.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py
MIT
def train_model_from_file(parameter_filename , serialization_dir , overrides = u"", file_friendly_logging = False, recover = False) : u""" A wrapper around :func:`train_model`...
A wrapper around :func:`train_model` which loads the params from a file. Parameters ---------- param_path : ``str`` A json parameter file specifying an AllenNLP experiment. serialization_dir : ``str`` The directory in which to save results and logs. We just pass this along to ...
train_model_from_file
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/train.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py
MIT
def datasets_from_params(params ) : u""" Load all the datasets specified by the config. """ dataset_reader = DatasetReader.from_params(params.pop(u'dataset_reader')) validation_dataset_reader_params = params.pop(u"validation_dataset_reader", None) validati...
Load all the datasets specified by the config.
datasets_from_params
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/train.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py
MIT
def create_serialization_dir(params , serialization_dir , recover ) : u""" This function creates the serialization directory if it doesn't exist. If it already exists and is non-empty, then it verifies that we're recovering from a training with an identical configuration. Parame...
This function creates the serialization directory if it doesn't exist. If it already exists and is non-empty, then it verifies that we're recovering from a training with an identical configuration. Parameters ---------- params: ``Params`` A parameter object specifying an AllenNLP Experime...
create_serialization_dir
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/train.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py
MIT
def train_model(params , serialization_dir , file_friendly_logging = False, recover = False) : u""" Trains the model specified in the given :class:`Params` object, using the data and training parameters also specified in that obj...
Trains the model specified in the given :class:`Params` object, using the data and training parameters also specified in that object, and saves the results in ``serialization_dir``. Parameters ---------- params : ``Params`` A parameter object specifying an AllenNLP Experiment. serializ...
train_model
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/train.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py
MIT
def main(prog = None, subcommand_overrides = {}) : u""" The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unl...
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unless you use the ``--include-package`` flag.
main
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/commands/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/__init__.py
MIT
def full_name(cla55 ) : u""" Return the full name (including module) of the given class. """ # Special case to handle None: if cla55 is None: return u"?" if issubclass(cla55, Initializer) and cla55 != Initializer: init_fn = cla55()._init_function ret...
Return the full name (including module) of the given class.
full_name
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/configuration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py
MIT
def _get_config_type(cla55 ) : u""" Find the name (if any) that a subclass was registered under. We do this simply by iterating through the registry until we find it. """ # Special handling for pytorch RNN types: if cla55 == torch.nn.RNN: return u"rnn" elif c...
Find the name (if any) that a subclass was registered under. We do this simply by iterating through the registry until we find it.
_get_config_type
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/configuration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py
MIT
def _docspec_comments(obj) : u""" Inspect the docstring and get the comments for each parameter. """ # Sometimes our docstring is on the class, and sometimes it's on the initializer, # so we've got to check both. class_docstring = getattr(obj, u'__doc__', None) init_docstrin...
Inspect the docstring and get the comments for each parameter.
_docspec_comments
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/configuration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py
MIT
def _auto_config(cla55 ) : u""" Create the ``Config`` for a class by reflecting on its ``__init__`` method and applying a few hacks. """ typ3 = _get_config_type(cla55) # Don't include self, or vocab names_to_ignore = set([u"self", u"vocab"]) # Hack for RNNs if c...
Create the ``Config`` for a class by reflecting on its ``__init__`` method and applying a few hacks.
_auto_config
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/configuration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py
MIT
def render_config(config , indent = u"") : u""" Pretty-print a config in sort-of-JSON+comments. """ # Add four spaces to the indent. new_indent = indent + u" " return u"".join([ # opening brace + newline u"{\n", # "type": "...", (if prese...
Pretty-print a config in sort-of-JSON+comments.
render_config
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/configuration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py
MIT
def _render(item , indent = u"") : u""" Render a single config item, with the provided indent """ optional = item.default_value != _NO_DEFAULT if is_configurable(item.annotation): rendered_annotation = "{item.annotation} (configurable)" else: rendered_annot...
Render a single config item, with the provided indent
_render
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/configuration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py
MIT
def _valid_choices(cla55 ) : u""" Return a mapping {registered_name -> subclass_name} for the registered subclasses of `cla55`. """ choices = {} if cla55 not in Registrable._registry: raise ValueError("{cla55} is not a known Registrable class") ...
Return a mapping {registered_name -> subclass_name} for the registered subclasses of `cla55`.
_valid_choices
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/configuration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py
MIT
def filename_to_url(filename , cache_dir = None) : u""" Return the url and etag (which may be ``None``) stored for `filename`. Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist. """ if cache_dir is None: cache_dir = DATASET_CACHE ca...
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
filename_to_url
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/file_utils.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/file_utils.py
MIT
def cached_path(url_or_filename , cache_dir = None) : u""" Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the f...
Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and then return the path.
cached_path
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/file_utils.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/file_utils.py
MIT
def split_s3_path(url ) : u"""Split a full s3 path into the bucket name and path.""" parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError(u"bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at beg...
Split a full s3 path into the bucket name and path.
split_s3_path
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/file_utils.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/file_utils.py
MIT
def s3_request(func ): u""" Wrapper function for s3 requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url , *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.res...
Wrapper function for s3 requests in order to create more helpful error messages.
s3_request
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/file_utils.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/file_utils.py
MIT
def get_from_cache(url , cache_dir = None) : u""" Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it. Then return the path to the cached file. """ if cache_dir is None: cache_dir = DATASET_CACHE os.makedirs(cache_dir) #...
Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it. Then return the path to the cached file.
get_from_cache
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/file_utils.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/file_utils.py
MIT
def takes_arg(obj, arg ) : u""" Checks whether the provided obj takes a certain arg. If it's a class, we're really checking whether its constructor does. If it's a function or method, we're checking the object itself. Otherwise, we raise an error. """ if inspect.isclass(obj): ...
Checks whether the provided obj takes a certain arg. If it's a class, we're really checking whether its constructor does. If it's a function or method, we're checking the object itself. Otherwise, we raise an error.
takes_arg
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/from_params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py
MIT
def remove_optional(annotation ): u""" Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away. """ origin = getattr(annotation, u'__origin__', None) args = getattr(annotation, u'__args__'...
Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away.
remove_optional
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/from_params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py
MIT
def create_kwargs(cls , params , **extras) : u""" Given some class, a `Params` object, and potentially other keyword arguments, create a dict of keyword args suitable for passing to the class's constructor. The function does this by finding the class's constructor, match...
Given some class, a `Params` object, and potentially other keyword arguments, create a dict of keyword args suitable for passing to the class's constructor. The function does this by finding the class's constructor, matching the constructor arguments to entries in the `params` object, and instantiatin...
create_kwargs
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/from_params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py
MIT
def from_params(cls , params , **extras) : u""" This is the automatic implementation of `from_params`. Any class that subclasses `FromParams` (or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free. If you want your class to be instan...
This is the automatic implementation of `from_params`. Any class that subclasses `FromParams` (or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free. If you want your class to be instantiated from params in the "obvious" way -- pop off parameters and ...
from_params
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/from_params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py
MIT
def unflatten(flat_dict ) : u""" Given a "flattened" dict with compound keys, e.g. {"a.b": 0} unflatten it: {"a": {"b": 0}} """ unflat = {} for compound_key, value in list(flat_dict.items()): curr_dict = unflat part...
Given a "flattened" dict with compound keys, e.g. {"a.b": 0} unflatten it: {"a": {"b": 0}}
unflatten
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def with_fallback(preferred , fallback ) : u""" Deep merge two dicts, preferring values from `preferred`. """ preferred_keys = set(preferred.keys()) fallback_keys = set(fallback.keys()) common_keys = preferred_keys & fallback_keys merged ...
Deep merge two dicts, preferring values from `preferred`.
with_fallback
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def add_file_to_archive(self, name ) : u""" Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` pa...
Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` params.add_file_to_archive("input_file") ``` wh...
add_file_to_archive
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def pop(self, key , default = DEFAULT) : u""" Performs the functionality associated with dict.pop(key), along with checking for returned dictionaries, replacing them with Param objects with an updated history. If ``key`` is not present in the dictionary, and no default wa...
Performs the functionality associated with dict.pop(key), along with checking for returned dictionaries, replacing them with Param objects with an updated history. If ``key`` is not present in the dictionary, and no default was specified, we raise a ``ConfigurationError``, instead of t...
pop
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def pop_int(self, key , default = DEFAULT) : u""" Performs a pop and coerces to an int. """ value = self.pop(key, default) if value is None: return None else: return int(value)
Performs a pop and coerces to an int.
pop_int
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def pop_float(self, key , default = DEFAULT) : u""" Performs a pop and coerces to a float. """ value = self.pop(key, default) if value is None: return None else: return float(value)
Performs a pop and coerces to a float.
pop_float
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def pop_bool(self, key , default = DEFAULT) : u""" Performs a pop and coerces to a bool. """ value = self.pop(key, default) if value is None: return None elif isinstance(value, bool): return value elif value == u"true": ...
Performs a pop and coerces to a bool.
pop_bool
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def get(self, key , default = DEFAULT): u""" Performs the functionality associated with dict.get(key) but also checks for returned dicts and returns a Params object in their place with an updated history. """ if default is self.DEFAULT: try: v...
Performs the functionality associated with dict.get(key) but also checks for returned dicts and returns a Params object in their place with an updated history.
get
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def pop_choice(self, key , choices , default_to_first_choice = False) : u""" Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of the given choices. Note that this `pops` the key from params, modifying the dictionary, consist...
Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of the given choices. Note that this `pops` the key from params, modifying the dictionary, consistent with how parameters are processed in this codebase. Parameters ---------- key: st...
pop_choice
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def as_dict(self, quiet=False): u""" Sometimes we need to just represent the parameters as a dict, for instance when we pass them to a Keras layer(so that they can be serialised). Parameters ---------- quiet: bool, optional (default = False) Whether to log th...
Sometimes we need to just represent the parameters as a dict, for instance when we pass them to a Keras layer(so that they can be serialised). Parameters ---------- quiet: bool, optional (default = False) Whether to log the parameters before returning them as a dict...
as_dict
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def as_flat_dict(self): u""" Returns the parameters of a flat dictionary from keys to values. Nested structure is collapsed with periods. """ flat_params = {} def recurse(parameters, path): for key, value in list(parameters.items()): newpath = ...
Returns the parameters of a flat dictionary from keys to values. Nested structure is collapsed with periods.
as_flat_dict
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def assert_empty(self, class_name ): u""" Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling...
Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling` class, the one that got extra parameters (i...
assert_empty
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def from_file(params_file , params_overrides = u"") : u""" Load a `Params` object from a configuration file. """ # redirect to cache, if necessary params_file = cached_path(params_file) ext_vars = dict(os.environ) file_dict = json.loads(evalua...
Load a `Params` object from a configuration file.
from_file
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def as_ordered_dict(self, preference_orders = None) : u""" Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partia...
Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partial preference orders. ["A", "B", "C"] means "A" > "B" > "C". For multiple preference_o...
as_ordered_dict
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def pop_choice(params , key , choices , default_to_first_choice = False, history = u"?.") : u""" Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with places tha...
Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with places that the Params object is not welcome, such as inside Keras layers. See the docstring of that method for more detail on how this function works. This method adds a ``history`` parameter, in the off-c...
pop_choice
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/params.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py
MIT
def list_available(cls) : u"""List default first if it exists""" keys = list(Registrable._registry[cls].keys()) default = cls.default_implementation if default is None: return keys elif default not in keys: message = u"Default implementation %...
List default first if it exists
list_available
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/registrable.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/registrable.py
MIT
def normalize_answer(s): u"""Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(ur'\b(a|an|the)\b', u' ', text) def white_space_fix(text): return u' '.join(text.split()) def remove_punc(text): exclude = set(string.punct...
Lower text and remove punctuation, articles and extra whitespace.
normalize_answer
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/squad_eval.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/squad_eval.py
MIT
def replace_cr_with_newline(message ): u""" TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output. Displaying those in a file won't work correctly, so we'll just make sure that each batch shows up on its one line. ...
TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output. Displaying those in a file won't work correctly, so we'll just make sure that each batch shows up on its one line. :param message: the message to permute :retu...
replace_cr_with_newline
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/tee_logger.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/tee_logger.py
MIT
def set_slower_interval(use_slower_interval ) : u""" If ``use_slower_interval`` is ``True``, we will dramatically slow down ``tqdm's`` default output rate. ``tqdm's`` default output rate is great for interactively watching progress, but it is not great for log files. You mi...
If ``use_slower_interval`` is ``True``, we will dramatically slow down ``tqdm's`` default output rate. ``tqdm's`` default output rate is great for interactively watching progress, but it is not great for log files. You might want to set this if you are primarily going to be looking at...
set_slower_interval
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/tqdm.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/tqdm.py
MIT
def sanitize(x ) : # pylint: disable=invalid-name,too-many-return-statements u""" Sanitize turns PyTorch and Numpy types into basic Python types so they can be serialized into JSON. """ if isinstance(x, (unicode, float, int, bool)): # x is already serializable return x ...
Sanitize turns PyTorch and Numpy types into basic Python types so they can be serialized into JSON.
sanitize
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def pad_sequence_to_length(sequence , desired_length , default_value = lambda: 0, padding_on_right = True) : u""" Take a list of objects and pads it to the desired length, returning the padd...
Take a list of objects and pads it to the desired length, returning the padded list. The original list is not modified. Parameters ---------- sequence : List A list of objects to be padded. desired_length : int Maximum length of each sequence. Longer sequences are truncated t...
pad_sequence_to_length
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def add_noise_to_dict_values(dictionary , noise_param ) : u""" Returns a new dictionary with noise added to every key in ``dictionary``. The noise is uniformly distributed within ``noise_param`` percent of the value for every value in the dictionary. """ ne...
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is uniformly distributed within ``noise_param`` percent of the value for every value in the dictionary.
add_noise_to_dict_values
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def namespace_match(pattern , namespace ): u""" Matches a namespace pattern against a namespace string. For example, ``*tags`` matches ``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not ``stemmed_tokens``. """ if pattern[0] == u'*' and namespace.endswith(pa...
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches ``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not ``stemmed_tokens``.
namespace_match
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def prepare_environment(params ): u""" Sets random seeds for reproducible experiments. This may not work as expected if you use this from within a python project in which you have already imported Pytorch. If you use the scripts/run_model.py entry point to training models with this library, y...
Sets random seeds for reproducible experiments. This may not work as expected if you use this from within a python project in which you have already imported Pytorch. If you use the scripts/run_model.py entry point to training models with this library, your experiments should be reasonably reproducible...
prepare_environment
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def prepare_global_logging(serialization_dir , file_friendly_logging ) : u""" This function configures 3 global logging attributes - streaming stdout and stderr to a file as well as the terminal, setting the formatting for the python logging library and setting the interval frequency for...
This function configures 3 global logging attributes - streaming stdout and stderr to a file as well as the terminal, setting the formatting for the python logging library and setting the interval frequency for the Tqdm progress bar. Note that this function does not set the logging level, which is set...
prepare_global_logging
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def get_spacy_model(spacy_model_name , pos_tags , parse , ner ) : u""" In order to avoid loading spacy models a whole bunch of times, we'll save references to them, keyed by the options we used to create the spacy model, so any particular configuration only gets loade...
In order to avoid loading spacy models a whole bunch of times, we'll save references to them, keyed by the options we used to create the spacy model, so any particular configuration only gets loaded once.
get_spacy_model
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def import_submodules(package_name ) : u""" Import all submodules under the given package. Primarily useful so that people using AllenNLP as a library can specify their own custom packages and have their custom classes get loaded and registered. """ importlib.invalidate_caches() ...
Import all submodules under the given package. Primarily useful so that people using AllenNLP as a library can specify their own custom packages and have their custom classes get loaded and registered.
import_submodules
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def peak_memory_mb() : u""" Get peak memory usage for this process, as measured by max-resident-set size: https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size Only works on OSX and Linux, returns 0.0 otherwise. """ if resource is No...
Get peak memory usage for this process, as measured by max-resident-set size: https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size Only works on OSX and Linux, returns 0.0 otherwise.
peak_memory_mb
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def gpu_memory_mb() : u""" Get the current GPU memory usage. Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4 Returns ------- ``Dict[int, int]`` Keys are device ids as integers. Values are memory usage as integers in MB. R...
Get the current GPU memory usage. Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4 Returns ------- ``Dict[int, int]`` Keys are device ids as integers. Values are memory usage as integers in MB. Returns an empty ``dict`` if GPUs are not availa...
gpu_memory_mb
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def ensure_list(iterable ) : u""" An Iterable may be a list or a generator. This ensures we get a list without making an unnecessary copy. """ if isinstance(iterable, list): return iterable else: return list(iterable)
An Iterable may be a list or a generator. This ensures we get a list without making an unnecessary copy.
ensure_list
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/common/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py
MIT
def __init__(self, instances ) : u""" A Batch just takes an iterable of instances in its constructor and hangs onto them in a list. """ super(Batch, self).__init__() self.instances = ensure_list(instances) self._check_types()
A Batch just takes an iterable of instances in its constructor and hangs onto them in a list.
__init__
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/data/dataset.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset.py
MIT
def _check_types(self) : u""" Check that all the instances have the same types. """ all_instance_fields_and_types = [dict((k, v.__class__.__name__) for k, v in x.fields.items()) ...
Check that all the instances have the same types.
_check_types
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/data/dataset.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset.py
MIT
def get_padding_lengths(self) : u""" Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance`` has multiple ``Fields``, and each ``Field`` could have multiple things that need padding. We look at all fields in all instances, and...
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance`` has multiple ``Fields``, and each ``Field`` could have multiple things that need padding. We look at all fields in all instances, and find the max values for each (field_name, padding_key) pair, re...
get_padding_lengths
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/data/dataset.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset.py
MIT