2019-03-08 13:42:26 +03:00
|
|
|
cimport numpy as np
|
|
|
|
from cython.operator cimport dereference as deref
|
|
|
|
from libcpp.set cimport set as cppset
|
|
|
|
|
2018-03-28 17:02:59 +03:00
|
|
|
import functools
|
2017-06-05 13:32:08 +03:00
|
|
|
import numpy
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
import srsly
|
2020-01-29 19:06:46 +03:00
|
|
|
from thinc.util import get_array_module
|
|
|
|
from thinc.backends import get_current_ops
|
2017-06-05 13:32:08 +03:00
|
|
|
|
2018-12-10 18:09:49 +03:00
|
|
|
from .strings cimport StringStore
|
2019-03-08 13:42:26 +03:00
|
|
|
|
2018-12-10 18:09:49 +03:00
|
|
|
from .strings import get_string_id
|
2018-04-03 16:50:31 +03:00
|
|
|
from .errors import Errors
|
2017-10-27 20:45:19 +03:00
|
|
|
from . import util
|
2017-06-05 13:32:08 +03:00
|
|
|
|
|
|
|
|
2018-03-11 00:53:42 +03:00
|
|
|
def unpickle_vectors(bytes_data):
|
|
|
|
return Vectors().from_bytes(bytes_data)
|
2017-10-31 20:25:08 +03:00
|
|
|
|
|
|
|
|
2018-03-28 17:02:59 +03:00
|
|
|
class GlobalRegistry(object):
|
2019-03-08 13:42:26 +03:00
|
|
|
"""Global store of vectors, to avoid repeatedly loading the data."""
|
2018-03-28 17:02:59 +03:00
|
|
|
data = {}
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def register(cls, name, data):
|
|
|
|
cls.data[name] = data
|
|
|
|
return functools.partial(cls.get, name)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get(cls, name):
|
|
|
|
return cls.data[name]
|
|
|
|
|
|
|
|
|
2017-06-05 13:32:08 +03:00
|
|
|
cdef class Vectors:
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Store, save and load word vectors.
|
2017-10-02 01:05:54 +03:00
|
|
|
|
2017-10-01 23:10:33 +03:00
|
|
|
Vectors data is kept in the vectors.data attribute, which should be an
|
2017-10-27 20:45:19 +03:00
|
|
|
instance of numpy.ndarray (for CPU vectors) or cupy.ndarray
|
|
|
|
(for GPU vectors). `vectors.key2row` is a dictionary mapping word hashes to
|
2017-10-30 12:03:08 +03:00
|
|
|
rows in the vectors.data table.
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
Multiple keys can be mapped to the same vector, and not all of the rows in
|
2019-03-08 13:42:26 +03:00
|
|
|
the table need to be assigned - so len(list(vectors.keys())) may be
|
2017-10-31 20:25:08 +03:00
|
|
|
greater or smaller than vectors.shape[0].
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2018-03-28 17:02:59 +03:00
|
|
|
cdef public object name
|
2017-06-05 13:32:08 +03:00
|
|
|
cdef public object data
|
2017-08-19 05:33:03 +03:00
|
|
|
cdef public object key2row
|
2018-03-31 14:28:25 +03:00
|
|
|
cdef cppset[int] _unset
|
2017-06-05 13:32:08 +03:00
|
|
|
|
2018-03-28 17:02:59 +03:00
|
|
|
def __init__(self, *, shape=None, data=None, keys=None, name=None):
|
2017-10-31 20:25:08 +03:00
|
|
|
"""Create a new vector store.
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
shape (tuple): Size of the table, as (# entries, # columns)
|
2017-10-27 20:45:19 +03:00
|
|
|
data (numpy.ndarray): The vector data.
|
2017-11-01 01:23:34 +03:00
|
|
|
keys (iterable): A sequence of keys, aligned with the data.
|
2019-09-26 17:21:32 +03:00
|
|
|
name (unicode): A name to identify the vectors table.
|
2017-10-27 20:45:19 +03:00
|
|
|
RETURNS (Vectors): The newly created object.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#init
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2018-03-28 17:02:59 +03:00
|
|
|
self.name = name
|
2017-10-31 20:25:08 +03:00
|
|
|
if data is None:
|
|
|
|
if shape is None:
|
|
|
|
shape = (0,0)
|
2019-03-08 13:42:26 +03:00
|
|
|
data = numpy.zeros(shape, dtype="f")
|
2017-10-31 20:25:08 +03:00
|
|
|
self.data = data
|
2019-12-22 03:53:56 +03:00
|
|
|
self.key2row = {}
|
2017-10-31 20:25:08 +03:00
|
|
|
if self.data is not None:
|
2018-03-31 14:28:25 +03:00
|
|
|
self._unset = cppset[int]({i for i in range(self.data.shape[0])})
|
2017-06-05 13:32:08 +03:00
|
|
|
else:
|
2018-03-31 14:28:25 +03:00
|
|
|
self._unset = cppset[int]()
|
2017-10-31 20:25:08 +03:00
|
|
|
if keys is not None:
|
|
|
|
for i, key in enumerate(keys):
|
|
|
|
self.add(key, row=i)
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
@property
|
|
|
|
def shape(self):
|
|
|
|
"""Get `(rows, dims)` tuples of number of rows and number of dimensions
|
|
|
|
in the vector table.
|
|
|
|
|
|
|
|
RETURNS (tuple): A `(rows, dims)` pair.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#shape
|
2017-10-31 20:25:08 +03:00
|
|
|
"""
|
|
|
|
return self.data.shape
|
|
|
|
|
|
|
|
@property
|
|
|
|
def size(self):
|
2019-03-08 13:42:26 +03:00
|
|
|
"""The vector size i,e. rows * dims.
|
|
|
|
|
|
|
|
RETURNS (int): The vector size.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#size
|
|
|
|
"""
|
2017-10-31 20:25:08 +03:00
|
|
|
return self.data.shape[0] * self.data.shape[1]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_full(self):
|
2019-03-08 13:42:26 +03:00
|
|
|
"""Whether the vectors table is full.
|
|
|
|
|
|
|
|
RETURNS (bool): `True` if no slots are available for new keys.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#is_full
|
|
|
|
"""
|
2018-03-31 14:28:25 +03:00
|
|
|
return self._unset.size() == 0
|
2017-06-05 13:32:08 +03:00
|
|
|
|
2017-10-31 21:30:52 +03:00
|
|
|
@property
|
|
|
|
def n_keys(self):
|
2019-03-08 13:42:26 +03:00
|
|
|
"""Get the number of keys in the table. Note that this is the number
|
|
|
|
of all keys, not just unique vectors.
|
|
|
|
|
|
|
|
RETURNS (int): The number of keys in the table.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#n_keys
|
|
|
|
"""
|
2017-10-31 21:30:52 +03:00
|
|
|
return len(self.key2row)
|
|
|
|
|
2017-06-05 13:32:08 +03:00
|
|
|
def __reduce__(self):
|
2018-03-11 00:53:42 +03:00
|
|
|
return (unpickle_vectors, (self.to_bytes(),))
|
2017-06-05 13:32:08 +03:00
|
|
|
|
|
|
|
def __getitem__(self, key):
|
2017-10-31 20:25:08 +03:00
|
|
|
"""Get a vector by key. If the key is not found, a KeyError is raised.
|
2017-10-01 23:10:33 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
key (int): The key to get the vector for.
|
|
|
|
RETURNS (ndarray): The vector for the key.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#getitem
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-08-19 05:33:03 +03:00
|
|
|
i = self.key2row[key]
|
2017-06-05 13:32:08 +03:00
|
|
|
if i is None:
|
2018-04-03 16:50:31 +03:00
|
|
|
raise KeyError(Errors.E058.format(key=key))
|
2017-06-05 13:32:08 +03:00
|
|
|
else:
|
|
|
|
return self.data[i]
|
|
|
|
|
|
|
|
def __setitem__(self, key, vector):
|
2017-10-31 20:25:08 +03:00
|
|
|
"""Set a vector for the given key.
|
2017-10-27 20:45:19 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
key (int): The key to set the vector for.
|
2017-11-01 01:23:34 +03:00
|
|
|
vector (ndarray): The vector to set.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#setitem
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-08-19 05:33:03 +03:00
|
|
|
i = self.key2row[key]
|
2017-06-05 13:32:08 +03:00
|
|
|
self.data[i] = vector
|
2018-03-31 14:28:25 +03:00
|
|
|
if self._unset.count(i):
|
|
|
|
self._unset.erase(self._unset.find(i))
|
2017-06-05 13:32:08 +03:00
|
|
|
|
|
|
|
def __iter__(self):
|
2017-11-01 01:23:34 +03:00
|
|
|
"""Iterate over the keys in the table.
|
2017-10-27 20:45:19 +03:00
|
|
|
|
2017-11-01 01:23:34 +03:00
|
|
|
YIELDS (int): A key in the table.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#iter
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-10-31 20:25:08 +03:00
|
|
|
yield from self.key2row
|
2017-06-05 13:32:08 +03:00
|
|
|
|
|
|
|
def __len__(self):
|
2017-10-31 20:25:08 +03:00
|
|
|
"""Return the number of vectors in the table.
|
2017-10-27 20:45:19 +03:00
|
|
|
|
|
|
|
RETURNS (int): The number of vectors in the data.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#len
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-10-31 20:25:08 +03:00
|
|
|
return self.data.shape[0]
|
2017-08-19 20:52:25 +03:00
|
|
|
|
|
|
|
def __contains__(self, key):
|
2017-10-31 20:25:08 +03:00
|
|
|
"""Check whether a key has been mapped to a vector entry in the table.
|
2017-10-27 20:45:19 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
key (int): The key to check.
|
2017-10-27 20:45:19 +03:00
|
|
|
RETURNS (bool): Whether the key has a vector entry.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#contains
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-08-19 20:52:25 +03:00
|
|
|
return key in self.key2row
|
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
def resize(self, shape, inplace=False):
|
2017-11-01 01:23:34 +03:00
|
|
|
"""Resize the underlying vectors array. If inplace=True, the memory
|
2017-10-31 20:25:08 +03:00
|
|
|
is reallocated. This may cause other references to the data to become
|
|
|
|
invalid, so only use inplace=True if you're sure that's what you want.
|
|
|
|
|
|
|
|
If the number of vectors is reduced, keys mapped to rows that have been
|
|
|
|
deleted are removed. These removed items are returned as a list of
|
2017-11-01 01:23:34 +03:00
|
|
|
`(key, row)` tuples.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
shape (tuple): A `(rows, dims)` tuple.
|
|
|
|
inplace (bool): Reallocate the memory.
|
|
|
|
RETURNS (list): The removed items as a list of `(key, row)` tuples.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#resize
|
2017-11-01 01:23:34 +03:00
|
|
|
"""
|
2017-10-31 20:25:08 +03:00
|
|
|
if inplace:
|
|
|
|
self.data.resize(shape, refcheck=False)
|
|
|
|
else:
|
|
|
|
xp = get_array_module(self.data)
|
|
|
|
self.data = xp.resize(self.data, shape)
|
|
|
|
filled = {row for row in self.key2row.values()}
|
2018-03-31 14:28:25 +03:00
|
|
|
self._unset = cppset[int]({row for row in range(shape[0]) if row not in filled})
|
2017-10-31 20:25:08 +03:00
|
|
|
removed_items = []
|
2018-01-14 16:48:51 +03:00
|
|
|
for key, row in list(self.key2row.items()):
|
2017-10-31 20:25:08 +03:00
|
|
|
if row >= shape[0]:
|
|
|
|
self.key2row.pop(key)
|
|
|
|
removed_items.append((key, row))
|
|
|
|
return removed_items
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
def keys(self):
|
2019-03-08 13:42:26 +03:00
|
|
|
"""RETURNS (iterable): A sequence of keys in the table."""
|
2017-11-01 01:23:34 +03:00
|
|
|
return self.key2row.keys()
|
|
|
|
|
2017-10-31 20:25:08 +03:00
|
|
|
def values(self):
|
2017-11-01 01:23:34 +03:00
|
|
|
"""Iterate over vectors that have been assigned to at least one key.
|
2017-10-31 20:25:08 +03:00
|
|
|
|
|
|
|
Note that some vectors may be unassigned, so the number of vectors
|
2017-11-01 01:23:34 +03:00
|
|
|
returned may be less than the length of the vectors table.
|
|
|
|
|
|
|
|
YIELDS (ndarray): A vector in the table.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#values
|
2017-11-01 01:23:34 +03:00
|
|
|
"""
|
2017-10-31 20:25:08 +03:00
|
|
|
for row, vector in enumerate(range(self.data.shape[0])):
|
2018-03-31 14:28:25 +03:00
|
|
|
if not self._unset.count(row):
|
2017-10-31 20:25:08 +03:00
|
|
|
yield vector
|
|
|
|
|
|
|
|
def items(self):
|
|
|
|
"""Iterate over `(key, vector)` pairs.
|
|
|
|
|
|
|
|
YIELDS (tuple): A key/vector pair.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#items
|
2017-10-31 20:25:08 +03:00
|
|
|
"""
|
|
|
|
for key, row in self.key2row.items():
|
|
|
|
yield key, self.data[row]
|
|
|
|
|
2017-11-01 02:34:55 +03:00
|
|
|
def find(self, *, key=None, keys=None, row=None, rows=None):
|
2017-11-01 02:42:39 +03:00
|
|
|
"""Look up one or more keys by row, or vice versa.
|
2017-11-01 02:34:55 +03:00
|
|
|
|
|
|
|
key (unicode / int): Find the row that the given key points to.
|
|
|
|
Returns int, -1 if missing.
|
2017-11-01 02:42:39 +03:00
|
|
|
keys (iterable): Find rows that the keys point to.
|
2017-11-01 02:34:55 +03:00
|
|
|
Returns ndarray.
|
2019-03-16 19:10:57 +03:00
|
|
|
row (int): Find the first key that points to the row.
|
2017-11-01 02:34:55 +03:00
|
|
|
Returns int.
|
2017-11-01 02:42:39 +03:00
|
|
|
rows (iterable): Find the keys that point to the rows.
|
2017-11-01 02:34:55 +03:00
|
|
|
Returns ndarray.
|
2017-11-01 02:42:39 +03:00
|
|
|
RETURNS: The requested key, keys, row or rows.
|
|
|
|
"""
|
2017-11-01 02:34:55 +03:00
|
|
|
if sum(arg is None for arg in (key, keys, row, rows)) != 3:
|
2019-03-08 13:42:26 +03:00
|
|
|
bad_kwargs = {"key": key, "keys": keys, "row": row, "rows": rows}
|
2018-04-03 16:50:31 +03:00
|
|
|
raise ValueError(Errors.E059.format(kwargs=bad_kwargs))
|
2017-10-31 20:25:08 +03:00
|
|
|
xp = get_array_module(self.data)
|
2017-11-01 02:34:55 +03:00
|
|
|
if key is not None:
|
2018-12-10 18:09:49 +03:00
|
|
|
key = get_string_id(key)
|
2017-11-01 02:34:55 +03:00
|
|
|
return self.key2row.get(key, -1)
|
|
|
|
elif keys is not None:
|
2018-12-10 18:09:49 +03:00
|
|
|
keys = [get_string_id(key) for key in keys]
|
2017-11-01 02:34:55 +03:00
|
|
|
rows = [self.key2row.get(key, -1.) for key in keys]
|
2019-03-08 13:42:26 +03:00
|
|
|
return xp.asarray(rows, dtype="i")
|
2017-11-01 02:34:55 +03:00
|
|
|
else:
|
2019-11-21 18:58:32 +03:00
|
|
|
row2key = {row: key for key, row in self.key2row.items()}
|
2017-11-01 02:34:55 +03:00
|
|
|
if row is not None:
|
2019-11-21 18:58:32 +03:00
|
|
|
return row2key[row]
|
2017-11-01 02:34:55 +03:00
|
|
|
else:
|
2019-11-21 18:58:32 +03:00
|
|
|
results = [row2key[row] for row in rows]
|
|
|
|
return xp.asarray(results, dtype="uint64")
|
2017-10-31 20:25:08 +03:00
|
|
|
|
2017-10-30 12:03:08 +03:00
|
|
|
def add(self, key, *, vector=None, row=None):
|
|
|
|
"""Add a key to the table. Keys can be mapped to an existing vector
|
|
|
|
by setting `row`, or a new vector can be added.
|
2017-10-27 20:45:19 +03:00
|
|
|
|
2017-11-01 02:18:08 +03:00
|
|
|
key (int): The key to add.
|
|
|
|
vector (ndarray / None): A vector to add for the key.
|
|
|
|
row (int / None): The row number of a vector to map the key to.
|
|
|
|
RETURNS (int): The row the vector was added to.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#add
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2018-12-10 18:09:49 +03:00
|
|
|
key = get_string_id(key)
|
2017-10-31 04:00:26 +03:00
|
|
|
if row is None and key in self.key2row:
|
|
|
|
row = self.key2row[key]
|
|
|
|
elif row is None:
|
2017-10-31 20:25:08 +03:00
|
|
|
if self.is_full:
|
2018-04-03 16:50:31 +03:00
|
|
|
raise ValueError(Errors.E060.format(rows=self.data.shape[0],
|
|
|
|
cols=self.data.shape[1]))
|
2018-03-31 14:28:25 +03:00
|
|
|
row = deref(self._unset.begin())
|
2017-10-31 04:00:26 +03:00
|
|
|
self.key2row[key] = row
|
2017-08-19 20:52:25 +03:00
|
|
|
if vector is not None:
|
2017-10-30 12:03:08 +03:00
|
|
|
self.data[row] = vector
|
2018-03-31 14:28:25 +03:00
|
|
|
if self._unset.count(row):
|
|
|
|
self._unset.erase(self._unset.find(row))
|
2017-10-30 12:03:08 +03:00
|
|
|
return row
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2019-10-03 15:09:44 +03:00
|
|
|
def most_similar(self, queries, *, batch_size=1024, n=1, sort=True):
|
|
|
|
"""For each of the given vectors, find the n most similar entries
|
2017-10-31 20:25:08 +03:00
|
|
|
to it, by cosine.
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2017-11-01 02:18:08 +03:00
|
|
|
Queries are by vector. Results are returned as a `(keys, best_rows,
|
|
|
|
scores)` tuple. If `queries` is large, the calculations are performed in
|
|
|
|
chunks, to avoid consuming too much memory. You can set the `batch_size`
|
|
|
|
to control the size/space trade-off during the calculations.
|
|
|
|
|
|
|
|
queries (ndarray): An array with one or more vectors.
|
|
|
|
batch_size (int): The batch size to use.
|
2019-10-03 15:09:44 +03:00
|
|
|
n (int): The number of entries to return for each query.
|
|
|
|
sort (bool): Whether to sort the n entries returned by score.
|
|
|
|
RETURNS (tuple): The most similar entries as a `(keys, best_rows, scores)`
|
2017-11-01 02:18:08 +03:00
|
|
|
tuple.
|
|
|
|
"""
|
2017-10-31 20:25:08 +03:00
|
|
|
xp = get_array_module(self.data)
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2019-10-21 13:04:46 +03:00
|
|
|
norms = xp.linalg.norm(self.data, axis=1, keepdims=True)
|
|
|
|
norms[norms == 0] = 1
|
|
|
|
vectors = self.data / norms
|
2017-11-01 01:23:34 +03:00
|
|
|
|
2019-10-03 15:09:44 +03:00
|
|
|
best_rows = xp.zeros((queries.shape[0], n), dtype='i')
|
|
|
|
scores = xp.zeros((queries.shape[0], n), dtype='f')
|
2017-10-31 20:25:08 +03:00
|
|
|
# Work in batches, to avoid memory problems.
|
|
|
|
for i in range(0, queries.shape[0], batch_size):
|
|
|
|
batch = queries[i : i+batch_size]
|
2019-10-21 13:04:46 +03:00
|
|
|
batch_norms = xp.linalg.norm(batch, axis=1, keepdims=True)
|
|
|
|
batch_norms[batch_norms == 0] = 1
|
|
|
|
batch /= batch_norms
|
2017-10-31 20:25:08 +03:00
|
|
|
# batch e.g. (1024, 300)
|
|
|
|
# vectors e.g. (10000, 300)
|
|
|
|
# sims e.g. (1024, 10000)
|
|
|
|
sims = xp.dot(batch, vectors.T)
|
2019-10-03 15:09:44 +03:00
|
|
|
best_rows[i:i+batch_size] = xp.argpartition(sims, -n, axis=1)[:,-n:]
|
|
|
|
scores[i:i+batch_size] = xp.partition(sims, -n, axis=1)[:,-n:]
|
|
|
|
|
2019-10-17 00:18:55 +03:00
|
|
|
if sort and n >= 2:
|
|
|
|
sorted_index = xp.arange(scores.shape[0])[:,None][i:i+batch_size],xp.argsort(scores[i:i+batch_size], axis=1)[:,::-1]
|
2019-10-03 15:09:44 +03:00
|
|
|
scores[i:i+batch_size] = scores[sorted_index]
|
|
|
|
best_rows[i:i+batch_size] = best_rows[sorted_index]
|
2019-12-22 03:53:56 +03:00
|
|
|
|
2017-11-01 04:06:58 +03:00
|
|
|
xp = get_array_module(self.data)
|
2019-10-22 21:10:42 +03:00
|
|
|
# Round values really close to 1 or -1
|
|
|
|
scores = xp.around(scores, decimals=4, out=scores)
|
|
|
|
# Account for numerical error we want to return in range -1, 1
|
|
|
|
scores = xp.clip(scores, a_min=-1, a_max=1, out=scores)
|
2017-11-01 04:06:58 +03:00
|
|
|
row2key = {row: key for key, row in self.key2row.items()}
|
2018-12-10 18:19:18 +03:00
|
|
|
keys = xp.asarray(
|
2019-12-22 03:53:56 +03:00
|
|
|
[[row2key[row] for row in best_rows[i] if row in row2key]
|
2019-10-03 15:09:44 +03:00
|
|
|
for i in range(len(queries)) ], dtype="uint64")
|
2017-11-01 02:18:08 +03:00
|
|
|
return (keys, best_rows, scores)
|
2017-06-05 13:32:08 +03:00
|
|
|
|
2017-09-01 17:39:22 +03:00
|
|
|
def from_glove(self, path):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Load GloVe vectors from a directory. Assumes binary format,
|
2017-09-01 17:39:22 +03:00
|
|
|
that the vocab is in a vocab.txt, and that vectors are named
|
|
|
|
vectors.{size}.[fd].bin, e.g. vectors.128.f.bin for 128d float32
|
|
|
|
vectors, vectors.300.d.bin for 300d float64 (double) vectors, etc.
|
2017-10-27 20:45:19 +03:00
|
|
|
By default GloVe outputs 64-bit vectors.
|
|
|
|
|
|
|
|
path (unicode / Path): The path to load the GloVe vectors from.
|
2017-11-01 02:18:08 +03:00
|
|
|
RETURNS: A `StringStore` object, holding the key-to-string mapping.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#from_glove
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-09-01 17:39:22 +03:00
|
|
|
path = util.ensure_path(path)
|
2017-10-31 20:25:08 +03:00
|
|
|
width = None
|
2017-09-01 17:39:22 +03:00
|
|
|
for name in path.iterdir():
|
2019-03-08 13:42:26 +03:00
|
|
|
if name.parts[-1].startswith("vectors"):
|
2017-09-01 17:39:22 +03:00
|
|
|
_, dims, dtype, _2 = name.parts[-1].split('.')
|
2017-10-31 20:25:08 +03:00
|
|
|
width = int(dims)
|
2017-09-01 17:39:22 +03:00
|
|
|
break
|
|
|
|
else:
|
2018-04-03 16:50:31 +03:00
|
|
|
raise IOError(Errors.E061.format(filename=path))
|
2019-12-22 03:53:56 +03:00
|
|
|
bin_loc = path / f"vectors.{dims}.{dtype}.bin"
|
2017-10-31 20:25:08 +03:00
|
|
|
xp = get_array_module(self.data)
|
|
|
|
self.data = None
|
2019-03-08 13:42:26 +03:00
|
|
|
with bin_loc.open("rb") as file_:
|
2017-10-31 20:25:08 +03:00
|
|
|
self.data = xp.fromfile(file_, dtype=dtype)
|
2019-03-08 13:42:26 +03:00
|
|
|
if dtype != "float32":
|
|
|
|
self.data = xp.ascontiguousarray(self.data, dtype="float32")
|
2018-01-22 21:18:26 +03:00
|
|
|
if self.data.ndim == 1:
|
|
|
|
self.data = self.data.reshape((self.data.size//width, width))
|
2017-09-01 17:39:22 +03:00
|
|
|
n = 0
|
2017-10-31 20:25:08 +03:00
|
|
|
strings = StringStore()
|
2019-03-08 13:42:26 +03:00
|
|
|
with (path / "vocab.txt").open("r") as file_:
|
2017-10-31 20:25:08 +03:00
|
|
|
for i, line in enumerate(file_):
|
|
|
|
key = strings.add(line.strip())
|
|
|
|
self.add(key, row=i)
|
|
|
|
return strings
|
2017-09-01 17:39:22 +03:00
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def to_disk(self, path, **kwargs):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Save the current state to a directory.
|
|
|
|
|
|
|
|
path (unicode / Path): A path to a directory, which will be created if
|
2019-03-10 21:16:45 +03:00
|
|
|
it doesn't exists.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#to_disk
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-09-16 20:45:09 +03:00
|
|
|
xp = get_array_module(self.data)
|
|
|
|
if xp is numpy:
|
2019-03-08 13:42:26 +03:00
|
|
|
save_array = lambda arr, file_: xp.save(file_, arr, allow_pickle=False)
|
2017-09-16 20:45:09 +03:00
|
|
|
else:
|
|
|
|
save_array = lambda arr, file_: xp.save(file_, arr)
|
2019-12-22 03:53:56 +03:00
|
|
|
serializers = {
|
|
|
|
"vectors": lambda p: save_array(self.data, p.open("wb")),
|
|
|
|
"key2row": lambda p: srsly.write_msgpack(p, self.key2row)
|
|
|
|
}
|
2019-03-10 21:16:45 +03:00
|
|
|
return util.to_disk(path, serializers, [])
|
2017-08-18 21:45:48 +03:00
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def from_disk(self, path, **kwargs):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Loads state from a directory. Modifies the object in place and
|
|
|
|
returns it.
|
|
|
|
|
|
|
|
path (unicode / Path): Directory path, string or Path-like object.
|
|
|
|
RETURNS (Vectors): The modified object.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#from_disk
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-10-31 21:58:35 +03:00
|
|
|
def load_key2row(path):
|
2017-08-19 23:07:00 +03:00
|
|
|
if path.exists():
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
self.key2row = srsly.read_msgpack(path)
|
2017-10-31 21:58:35 +03:00
|
|
|
for key, row in self.key2row.items():
|
2018-03-31 14:28:25 +03:00
|
|
|
if self._unset.count(row):
|
|
|
|
self._unset.erase(self._unset.find(row))
|
2017-10-31 21:58:35 +03:00
|
|
|
|
|
|
|
def load_keys(path):
|
|
|
|
if path.exists():
|
|
|
|
keys = numpy.load(str(path))
|
|
|
|
for i, key in enumerate(keys):
|
|
|
|
self.add(key, row=i)
|
2017-08-19 19:42:11 +03:00
|
|
|
|
|
|
|
def load_vectors(path):
|
2020-01-29 19:06:46 +03:00
|
|
|
ops = get_current_ops()
|
2017-08-19 23:07:00 +03:00
|
|
|
if path.exists():
|
2020-01-29 19:06:46 +03:00
|
|
|
self.data = ops.xp.load(str(path))
|
2017-08-18 21:45:48 +03:00
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
serializers = {
|
|
|
|
"key2row": load_key2row,
|
|
|
|
"keys": load_keys,
|
|
|
|
"vectors": load_vectors,
|
|
|
|
}
|
2019-03-10 21:16:45 +03:00
|
|
|
util.from_disk(path, serializers, [])
|
2017-08-19 19:42:11 +03:00
|
|
|
return self
|
2017-06-05 13:32:08 +03:00
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def to_bytes(self, **kwargs):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Serialize the current state to a binary string.
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude (list): String names of serialization fields to exclude.
|
2017-10-27 20:45:19 +03:00
|
|
|
RETURNS (bytes): The serialized form of the `Vectors` object.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#to_bytes
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-06-05 13:32:08 +03:00
|
|
|
def serialize_weights():
|
2019-03-08 13:42:26 +03:00
|
|
|
if hasattr(self.data, "to_bytes"):
|
2017-08-18 21:45:48 +03:00
|
|
|
return self.data.to_bytes()
|
2017-06-05 13:32:08 +03:00
|
|
|
else:
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
return srsly.msgpack_dumps(self.data)
|
2019-03-10 21:16:45 +03:00
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
serializers = {
|
|
|
|
"key2row": lambda: srsly.msgpack_dumps(self.key2row),
|
|
|
|
"vectors": serialize_weights
|
|
|
|
}
|
2019-03-10 21:16:45 +03:00
|
|
|
return util.to_bytes(serializers, [])
|
2017-06-05 13:32:08 +03:00
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def from_bytes(self, data, **kwargs):
|
2017-10-27 20:45:19 +03:00
|
|
|
"""Load state from a binary string.
|
|
|
|
|
|
|
|
data (bytes): The data to load from.
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude (list): String names of serialization fields to exclude.
|
2017-10-27 20:45:19 +03:00
|
|
|
RETURNS (Vectors): The `Vectors` object.
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#from_bytes
|
2017-10-27 20:45:19 +03:00
|
|
|
"""
|
2017-06-05 13:32:08 +03:00
|
|
|
def deserialize_weights(b):
|
2019-03-08 13:42:26 +03:00
|
|
|
if hasattr(self.data, "from_bytes"):
|
2017-08-18 21:45:48 +03:00
|
|
|
self.data.from_bytes()
|
2017-06-05 13:32:08 +03:00
|
|
|
else:
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
self.data = srsly.msgpack_loads(b)
|
2017-06-05 13:32:08 +03:00
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
deserializers = {
|
|
|
|
"key2row": lambda b: self.key2row.update(srsly.msgpack_loads(b)),
|
|
|
|
"vectors": deserialize_weights
|
|
|
|
}
|
2019-03-10 21:16:45 +03:00
|
|
|
util.from_bytes(data, deserializers, [])
|
2017-08-19 19:42:11 +03:00
|
|
|
return self
|