2019-03-08 10:42:26 +00:00
|
|
|
cimport numpy as np
|
2021-12-20 16:11:31 +00:00
|
|
|
from libc.stdint cimport uint32_t, uint64_t
|
2019-03-08 10:42:26 +00:00
|
|
|
from cython.operator cimport dereference as deref
|
|
|
|
from libcpp.set cimport set as cppset
|
2021-10-27 12:08:31 +00:00
|
|
|
from murmurhash.mrmr cimport hash128_x64
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2018-03-28 14:02:59 +00:00
|
|
|
import functools
|
2017-06-05 10:32:08 +00:00
|
|
|
import numpy
|
2021-10-27 12:08:31 +00:00
|
|
|
from typing import cast
|
|
|
|
import warnings
|
|
|
|
from enum import Enum
|
💫 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 00:28:22 +00:00
|
|
|
import srsly
|
2022-01-18 16:14:35 +00:00
|
|
|
from thinc.api import Ops, get_array_module, get_current_ops
|
2021-10-27 12:08:31 +00:00
|
|
|
from thinc.backends import get_array_ops
|
|
|
|
from thinc.types import Floats2d
|
2017-06-05 10:32:08 +00:00
|
|
|
|
2018-12-10 15:09:49 +00:00
|
|
|
from .strings cimport StringStore
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2018-12-10 15:09:49 +00:00
|
|
|
from .strings import get_string_id
|
2021-10-27 12:08:31 +00:00
|
|
|
from .errors import Errors, Warnings
|
2017-10-27 17:45:19 +00:00
|
|
|
from . import util
|
2017-06-05 10:32:08 +00:00
|
|
|
|
|
|
|
|
2018-03-10 21:53:42 +00:00
|
|
|
def unpickle_vectors(bytes_data):
|
|
|
|
return Vectors().from_bytes(bytes_data)
|
2017-10-31 17:25:08 +00:00
|
|
|
|
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
class Mode(str, Enum):
|
|
|
|
default = "default"
|
|
|
|
floret = "floret"
|
2018-03-28 14:02:59 +00:00
|
|
|
|
|
|
|
@classmethod
|
2021-10-27 12:08:31 +00:00
|
|
|
def values(cls):
|
|
|
|
return list(cls.__members__.keys())
|
2018-03-28 14:02:59 +00:00
|
|
|
|
|
|
|
|
2017-06-05 10:32:08 +00:00
|
|
|
cdef class Vectors:
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Store, save and load word vectors.
|
2017-10-01 22:05:54 +00:00
|
|
|
|
2017-10-01 20:10:33 +00:00
|
|
|
Vectors data is kept in the vectors.data attribute, which should be an
|
2017-10-27 17:45:19 +00:00
|
|
|
instance of numpy.ndarray (for CPU vectors) or cupy.ndarray
|
2021-10-27 12:08:31 +00:00
|
|
|
(for GPU vectors).
|
|
|
|
|
|
|
|
In the default mode, `vectors.key2row` is a dictionary mapping word hashes
|
|
|
|
to rows in the vectors.data table. Multiple keys can be mapped to the same
|
|
|
|
vector, and not all of the rows in the table need to be assigned - so
|
|
|
|
len(list(vectors.keys())) may be greater or smaller than vectors.shape[0].
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
In floret mode, the floret settings (minn, maxn, etc.) are used to
|
|
|
|
calculate the vector from the rows corresponding to the key's ngrams.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
cdef public object strings
|
2018-03-28 14:02:59 +00:00
|
|
|
cdef public object name
|
2021-10-27 12:08:31 +00:00
|
|
|
cdef readonly object mode
|
2017-06-05 10:32:08 +00:00
|
|
|
cdef public object data
|
2017-08-19 02:33:03 +00:00
|
|
|
cdef public object key2row
|
2018-03-31 11:28:25 +00:00
|
|
|
cdef cppset[int] _unset
|
2021-10-27 12:08:31 +00:00
|
|
|
cdef readonly uint32_t minn
|
|
|
|
cdef readonly uint32_t maxn
|
|
|
|
cdef readonly uint32_t hash_count
|
|
|
|
cdef readonly uint32_t hash_seed
|
|
|
|
cdef readonly unicode bow
|
|
|
|
cdef readonly unicode eow
|
|
|
|
|
|
|
|
def __init__(self, *, strings=None, shape=None, data=None, keys=None, name=None, mode=Mode.default, minn=0, maxn=0, hash_count=1, hash_seed=0, bow="<", eow=">"):
|
2017-10-31 17:25:08 +00:00
|
|
|
"""Create a new vector store.
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
strings (StringStore): The string store.
|
2017-10-31 17:25:08 +00:00
|
|
|
shape (tuple): Size of the table, as (# entries, # columns)
|
2021-04-19 08:30:03 +00:00
|
|
|
data (numpy.ndarray or cupy.ndarray): The vector data.
|
2017-10-31 22:23:34 +00:00
|
|
|
keys (iterable): A sequence of keys, aligned with the data.
|
2020-05-24 15:20:58 +00:00
|
|
|
name (str): A name to identify the vectors table.
|
2021-10-27 12:08:31 +00:00
|
|
|
mode (str): Vectors mode: "default" or "floret" (default: "default").
|
|
|
|
minn (int): The floret char ngram minn (default: 0).
|
|
|
|
maxn (int): The floret char ngram maxn (default: 0).
|
|
|
|
hash_count (int): The floret hash count (1-4, default: 1).
|
|
|
|
hash_seed (int): The floret hash seed (default: 0).
|
|
|
|
bow (str): The floret BOW string (default: "<").
|
|
|
|
eow (str): The floret EOW string (default: ">").
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#init
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
self.strings = strings
|
|
|
|
if self.strings is None:
|
|
|
|
self.strings = StringStore()
|
2018-03-28 14:02:59 +00:00
|
|
|
self.name = name
|
2021-10-27 12:08:31 +00:00
|
|
|
if mode not in Mode.values():
|
|
|
|
raise ValueError(
|
|
|
|
Errors.E202.format(
|
|
|
|
name="vectors",
|
|
|
|
mode=mode,
|
|
|
|
modes=str(Mode.values())
|
|
|
|
)
|
|
|
|
)
|
|
|
|
self.mode = Mode(mode).value
|
2019-12-22 00:53:56 +00:00
|
|
|
self.key2row = {}
|
2021-10-27 12:08:31 +00:00
|
|
|
self.minn = minn
|
|
|
|
self.maxn = maxn
|
|
|
|
self.hash_count = hash_count
|
|
|
|
self.hash_seed = hash_seed
|
|
|
|
self.bow = bow
|
|
|
|
self.eow = eow
|
|
|
|
if self.mode == Mode.default:
|
|
|
|
if data is None:
|
|
|
|
if shape is None:
|
|
|
|
shape = (0,0)
|
|
|
|
ops = get_current_ops()
|
|
|
|
data = ops.xp.zeros(shape, dtype="f")
|
|
|
|
self._unset = cppset[int]({i for i in range(data.shape[0])})
|
|
|
|
else:
|
|
|
|
self._unset = cppset[int]()
|
|
|
|
self.data = data
|
|
|
|
if keys is not None:
|
|
|
|
for i, key in enumerate(keys):
|
|
|
|
self.add(key, row=i)
|
|
|
|
elif self.mode == Mode.floret:
|
|
|
|
if maxn < minn:
|
|
|
|
raise ValueError(Errors.E863)
|
|
|
|
if hash_count < 1 or hash_count >= 5:
|
|
|
|
raise ValueError(Errors.E862)
|
|
|
|
if data is None:
|
|
|
|
raise ValueError(Errors.E864)
|
|
|
|
if keys is not None:
|
|
|
|
raise ValueError(Errors.E861)
|
|
|
|
self.data = data
|
2018-03-31 11:28:25 +00:00
|
|
|
self._unset = cppset[int]()
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2017-10-31 17:25:08 +00: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 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#shape
|
2017-10-31 17:25:08 +00:00
|
|
|
"""
|
|
|
|
return self.data.shape
|
|
|
|
|
|
|
|
@property
|
|
|
|
def size(self):
|
2019-03-08 10:42:26 +00:00
|
|
|
"""The vector size i,e. rows * dims.
|
|
|
|
|
|
|
|
RETURNS (int): The vector size.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#size
|
2019-03-08 10:42:26 +00:00
|
|
|
"""
|
2022-01-18 16:14:35 +00:00
|
|
|
return self.data.size
|
2017-10-31 17:25:08 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_full(self):
|
2019-03-08 10:42:26 +00:00
|
|
|
"""Whether the vectors table is full.
|
|
|
|
|
|
|
|
RETURNS (bool): `True` if no slots are available for new keys.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#is_full
|
2019-03-08 10:42:26 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.floret:
|
|
|
|
return True
|
2018-03-31 11:28:25 +00:00
|
|
|
return self._unset.size() == 0
|
2017-06-05 10:32:08 +00:00
|
|
|
|
2017-10-31 18:30:52 +00:00
|
|
|
@property
|
|
|
|
def n_keys(self):
|
2019-03-08 10:42:26 +00:00
|
|
|
"""Get the number of keys in the table. Note that this is the number
|
|
|
|
of all keys, not just unique vectors.
|
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
RETURNS (int): The number of keys in the table for default vectors.
|
|
|
|
For floret vectors, return -1.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#n_keys
|
2019-03-08 10:42:26 +00:00
|
|
|
"""
|
2017-10-31 18:30:52 +00:00
|
|
|
return len(self.key2row)
|
|
|
|
|
2017-06-05 10:32:08 +00:00
|
|
|
def __reduce__(self):
|
2018-03-10 21:53:42 +00:00
|
|
|
return (unpickle_vectors, (self.to_bytes(),))
|
2017-06-05 10:32:08 +00:00
|
|
|
|
|
|
|
def __getitem__(self, key):
|
2017-10-31 17:25:08 +00:00
|
|
|
"""Get a vector by key. If the key is not found, a KeyError is raised.
|
2017-10-01 20:10:33 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
key (str/int): The key to get the vector for.
|
2017-10-31 17:25:08 +00:00
|
|
|
RETURNS (ndarray): The vector for the key.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#getitem
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.default:
|
|
|
|
i = self.key2row.get(get_string_id(key), None)
|
|
|
|
if i is None:
|
|
|
|
raise KeyError(Errors.E058.format(key=key))
|
|
|
|
else:
|
|
|
|
return self.data[i]
|
|
|
|
elif self.mode == Mode.floret:
|
|
|
|
return self.get_batch([key])[0]
|
|
|
|
raise KeyError(Errors.E058.format(key=key))
|
2017-06-05 10:32:08 +00:00
|
|
|
|
|
|
|
def __setitem__(self, key, vector):
|
2017-10-31 17:25:08 +00:00
|
|
|
"""Set a vector for the given key.
|
2017-10-27 17:45:19 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
key (str/int): The key to set the vector for.
|
2017-10-31 22:23:34 +00:00
|
|
|
vector (ndarray): The vector to set.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#setitem
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.floret:
|
|
|
|
warnings.warn(Warnings.W115.format(method="Vectors.__setitem__"))
|
|
|
|
return
|
|
|
|
key = get_string_id(key)
|
2017-08-19 02:33:03 +00:00
|
|
|
i = self.key2row[key]
|
2017-06-05 10:32:08 +00:00
|
|
|
self.data[i] = vector
|
2018-03-31 11:28:25 +00:00
|
|
|
if self._unset.count(i):
|
|
|
|
self._unset.erase(self._unset.find(i))
|
2017-06-05 10:32:08 +00:00
|
|
|
|
|
|
|
def __iter__(self):
|
2017-10-31 22:23:34 +00:00
|
|
|
"""Iterate over the keys in the table.
|
2017-10-27 17:45:19 +00:00
|
|
|
|
2017-10-31 22:23:34 +00:00
|
|
|
YIELDS (int): A key in the table.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#iter
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2017-10-31 17:25:08 +00:00
|
|
|
yield from self.key2row
|
2017-06-05 10:32:08 +00:00
|
|
|
|
|
|
|
def __len__(self):
|
2017-10-31 17:25:08 +00:00
|
|
|
"""Return the number of vectors in the table.
|
2017-10-27 17:45:19 +00:00
|
|
|
|
|
|
|
RETURNS (int): The number of vectors in the data.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#len
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2017-10-31 17:25:08 +00:00
|
|
|
return self.data.shape[0]
|
2017-08-19 17:52:25 +00:00
|
|
|
|
|
|
|
def __contains__(self, key):
|
2017-10-31 17:25:08 +00:00
|
|
|
"""Check whether a key has been mapped to a vector entry in the table.
|
2017-10-27 17:45:19 +00:00
|
|
|
|
2017-10-31 17:25:08 +00:00
|
|
|
key (int): The key to check.
|
2017-10-27 17:45:19 +00:00
|
|
|
RETURNS (bool): Whether the key has a vector entry.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#contains
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.floret:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return key in self.key2row
|
2017-08-19 17:52:25 +00:00
|
|
|
|
2017-10-31 17:25:08 +00:00
|
|
|
def resize(self, shape, inplace=False):
|
2017-10-31 22:23:34 +00:00
|
|
|
"""Resize the underlying vectors array. If inplace=True, the memory
|
2017-10-31 17:25:08 +00: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-10-31 22:23:34 +00:00
|
|
|
`(key, row)` tuples.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
|
|
|
shape (tuple): A `(rows, dims)` tuple.
|
|
|
|
inplace (bool): Reallocate the memory.
|
|
|
|
RETURNS (list): The removed items as a list of `(key, row)` tuples.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#resize
|
2017-10-31 22:23:34 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.floret:
|
|
|
|
warnings.warn(Warnings.W115.format(method="Vectors.resize"))
|
|
|
|
return -1
|
2020-03-29 11:51:20 +00:00
|
|
|
xp = get_array_module(self.data)
|
2017-10-31 17:25:08 +00:00
|
|
|
if inplace:
|
2020-04-02 08:43:13 +00:00
|
|
|
if shape[1] != self.data.shape[1]:
|
|
|
|
raise ValueError(Errors.E193.format(new_dim=shape[1], curr_dim=self.data.shape[1]))
|
2020-03-29 11:51:20 +00:00
|
|
|
if xp == numpy:
|
|
|
|
self.data.resize(shape, refcheck=False)
|
|
|
|
else:
|
|
|
|
raise ValueError(Errors.E192)
|
2017-10-31 17:25:08 +00:00
|
|
|
else:
|
2020-03-29 11:51:20 +00:00
|
|
|
resized_array = xp.zeros(shape, dtype=self.data.dtype)
|
|
|
|
copy_shape = (min(shape[0], self.data.shape[0]), min(shape[1], self.data.shape[1]))
|
|
|
|
resized_array[:copy_shape[0], :copy_shape[1]] = self.data[:copy_shape[0], :copy_shape[1]]
|
|
|
|
self.data = resized_array
|
2020-05-19 14:41:26 +00:00
|
|
|
self._sync_unset()
|
2017-10-31 17:25:08 +00:00
|
|
|
removed_items = []
|
2021-12-16 08:17:33 +00:00
|
|
|
for key, row in self.key2row.copy().items():
|
2017-10-31 17:25:08 +00:00
|
|
|
if row >= shape[0]:
|
|
|
|
self.key2row.pop(key)
|
|
|
|
removed_items.append((key, row))
|
|
|
|
return removed_items
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2017-10-31 17:25:08 +00:00
|
|
|
def keys(self):
|
2019-03-08 10:42:26 +00:00
|
|
|
"""RETURNS (iterable): A sequence of keys in the table."""
|
2017-10-31 22:23:34 +00:00
|
|
|
return self.key2row.keys()
|
|
|
|
|
2017-10-31 17:25:08 +00:00
|
|
|
def values(self):
|
2017-10-31 22:23:34 +00:00
|
|
|
"""Iterate over vectors that have been assigned to at least one key.
|
2017-10-31 17:25:08 +00:00
|
|
|
|
|
|
|
Note that some vectors may be unassigned, so the number of vectors
|
2017-10-31 22:23:34 +00:00
|
|
|
returned may be less than the length of the vectors table.
|
|
|
|
|
|
|
|
YIELDS (ndarray): A vector in the table.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#values
|
2017-10-31 22:23:34 +00:00
|
|
|
"""
|
2017-10-31 17:25:08 +00:00
|
|
|
for row, vector in enumerate(range(self.data.shape[0])):
|
2018-03-31 11:28:25 +00:00
|
|
|
if not self._unset.count(row):
|
2017-10-31 17:25:08 +00:00
|
|
|
yield vector
|
|
|
|
|
|
|
|
def items(self):
|
|
|
|
"""Iterate over `(key, vector)` pairs.
|
|
|
|
|
|
|
|
YIELDS (tuple): A key/vector pair.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#items
|
2017-10-31 17:25:08 +00:00
|
|
|
"""
|
|
|
|
for key, row in self.key2row.items():
|
|
|
|
yield key, self.data[row]
|
|
|
|
|
2017-10-31 23:34:55 +00:00
|
|
|
def find(self, *, key=None, keys=None, row=None, rows=None):
|
2017-10-31 23:42:39 +00:00
|
|
|
"""Look up one or more keys by row, or vice versa.
|
2017-10-31 23:34:55 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
key (Union[int, str]): Find the row that the given key points to.
|
2017-10-31 23:34:55 +00:00
|
|
|
Returns int, -1 if missing.
|
2021-10-27 12:08:31 +00:00
|
|
|
keys (Iterable[Union[int, str]]): Find rows that the keys point to.
|
2017-10-31 23:34:55 +00:00
|
|
|
Returns ndarray.
|
2019-03-16 16:10:57 +00:00
|
|
|
row (int): Find the first key that points to the row.
|
2017-10-31 23:34:55 +00:00
|
|
|
Returns int.
|
2021-10-27 12:08:31 +00:00
|
|
|
rows (Iterable[int]): Find the keys that point to the rows.
|
2017-10-31 23:34:55 +00:00
|
|
|
Returns ndarray.
|
2017-10-31 23:42:39 +00:00
|
|
|
RETURNS: The requested key, keys, row or rows.
|
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.floret:
|
|
|
|
raise ValueError(
|
|
|
|
Errors.E858.format(
|
|
|
|
mode=self.mode,
|
|
|
|
alternative="Use Vectors[key] instead.",
|
|
|
|
)
|
|
|
|
)
|
2017-10-31 23:34:55 +00:00
|
|
|
if sum(arg is None for arg in (key, keys, row, rows)) != 3:
|
2019-03-08 10:42:26 +00:00
|
|
|
bad_kwargs = {"key": key, "keys": keys, "row": row, "rows": rows}
|
2018-04-03 13:50:31 +00:00
|
|
|
raise ValueError(Errors.E059.format(kwargs=bad_kwargs))
|
2017-10-31 17:25:08 +00:00
|
|
|
xp = get_array_module(self.data)
|
2017-10-31 23:34:55 +00:00
|
|
|
if key is not None:
|
2018-12-10 15:09:49 +00:00
|
|
|
key = get_string_id(key)
|
2017-10-31 23:34:55 +00:00
|
|
|
return self.key2row.get(key, -1)
|
|
|
|
elif keys is not None:
|
2018-12-10 15:09:49 +00:00
|
|
|
keys = [get_string_id(key) for key in keys]
|
2017-10-31 23:34:55 +00:00
|
|
|
rows = [self.key2row.get(key, -1.) for key in keys]
|
2019-03-08 10:42:26 +00:00
|
|
|
return xp.asarray(rows, dtype="i")
|
2017-10-31 23:34:55 +00:00
|
|
|
else:
|
2019-11-21 15:58:32 +00:00
|
|
|
row2key = {row: key for key, row in self.key2row.items()}
|
2017-10-31 23:34:55 +00:00
|
|
|
if row is not None:
|
2019-11-21 15:58:32 +00:00
|
|
|
return row2key[row]
|
2017-10-31 23:34:55 +00:00
|
|
|
else:
|
2019-11-21 15:58:32 +00:00
|
|
|
results = [row2key[row] for row in rows]
|
|
|
|
return xp.asarray(results, dtype="uint64")
|
2017-10-31 17:25:08 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
def _get_ngram_hashes(self, unicode s):
|
|
|
|
"""Calculate up to 4 32-bit hash values with MurmurHash3_x64_128 using
|
|
|
|
the floret hash settings.
|
|
|
|
key (str): The string key.
|
|
|
|
RETURNS: A list of the integer hashes.
|
|
|
|
"""
|
2021-12-20 16:11:31 +00:00
|
|
|
# MurmurHash3_x64_128 returns an array of 2 uint64_t values.
|
|
|
|
cdef uint64_t[2] out
|
2021-10-27 12:08:31 +00:00
|
|
|
chars = s.encode("utf8")
|
|
|
|
cdef char* utf8_string = chars
|
|
|
|
hash128_x64(utf8_string, len(chars), self.hash_seed, &out)
|
2021-12-20 16:11:31 +00:00
|
|
|
rows = [
|
|
|
|
out[0] & 0xffffffffu,
|
|
|
|
out[0] >> 32,
|
|
|
|
out[1] & 0xffffffffu,
|
|
|
|
out[1] >> 32,
|
|
|
|
]
|
|
|
|
return rows[:min(self.hash_count, 4)]
|
2021-10-27 12:08:31 +00:00
|
|
|
|
|
|
|
def _get_ngrams(self, unicode key):
|
|
|
|
"""Get all padded ngram strings using the ngram settings.
|
|
|
|
key (str): The string key.
|
|
|
|
RETURNS: A list of the ngram strings for the padded key.
|
|
|
|
"""
|
|
|
|
key = self.bow + key + self.eow
|
|
|
|
ngrams = [key] + [
|
|
|
|
key[start:start+ngram_size]
|
|
|
|
for ngram_size in range(self.minn, self.maxn + 1)
|
|
|
|
for start in range(0, len(key) - ngram_size + 1)
|
|
|
|
]
|
|
|
|
return ngrams
|
|
|
|
|
|
|
|
def get_batch(self, keys):
|
|
|
|
"""Get the vectors for the provided keys efficiently as a batch.
|
|
|
|
keys (Iterable[Union[int, str]]): The keys.
|
|
|
|
RETURNS: The requested vectors from the vector table.
|
|
|
|
"""
|
|
|
|
ops = get_array_ops(self.data)
|
|
|
|
if self.mode == Mode.default:
|
|
|
|
rows = self.find(keys=keys)
|
|
|
|
vecs = self.data[rows]
|
|
|
|
elif self.mode == Mode.floret:
|
|
|
|
keys = [self.strings.as_string(key) for key in keys]
|
|
|
|
if sum(len(key) for key in keys) == 0:
|
|
|
|
return ops.xp.zeros((len(keys), self.data.shape[1]))
|
|
|
|
unique_keys = tuple(set(keys))
|
|
|
|
row_index = {key: i for i, key in enumerate(unique_keys)}
|
|
|
|
rows = [row_index[key] for key in keys]
|
|
|
|
indices = []
|
|
|
|
lengths = []
|
|
|
|
for key in unique_keys:
|
|
|
|
if key == "":
|
|
|
|
ngram_rows = []
|
|
|
|
else:
|
|
|
|
ngram_rows = [
|
|
|
|
h % self.data.shape[0]
|
|
|
|
for ngram in self._get_ngrams(key)
|
|
|
|
for h in self._get_ngram_hashes(ngram)
|
|
|
|
]
|
|
|
|
indices.extend(ngram_rows)
|
|
|
|
lengths.append(len(ngram_rows))
|
|
|
|
indices = ops.asarray(indices, dtype="int32")
|
|
|
|
lengths = ops.asarray(lengths, dtype="int32")
|
|
|
|
vecs = ops.reduce_mean(cast(Floats2d, self.data[indices]), lengths)
|
|
|
|
vecs = vecs[rows]
|
|
|
|
return ops.as_contig(vecs)
|
|
|
|
|
2017-10-30 09:03:08 +00: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 17:45:19 +00:00
|
|
|
|
2017-10-31 23:18:08 +00: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 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#add
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.floret:
|
|
|
|
warnings.warn(Warnings.W115.format(method="Vectors.add"))
|
|
|
|
return -1
|
2020-02-16 16:19:41 +00:00
|
|
|
# use int for all keys and rows in key2row for more efficient access
|
|
|
|
# and serialization
|
|
|
|
key = int(get_string_id(key))
|
|
|
|
if row is not None:
|
|
|
|
row = int(row)
|
2017-10-31 01:00:26 +00:00
|
|
|
if row is None and key in self.key2row:
|
|
|
|
row = self.key2row[key]
|
|
|
|
elif row is None:
|
2017-10-31 17:25:08 +00:00
|
|
|
if self.is_full:
|
2018-04-03 13:50:31 +00:00
|
|
|
raise ValueError(Errors.E060.format(rows=self.data.shape[0],
|
|
|
|
cols=self.data.shape[1]))
|
2018-03-31 11:28:25 +00:00
|
|
|
row = deref(self._unset.begin())
|
2020-05-13 20:08:28 +00:00
|
|
|
if row < self.data.shape[0]:
|
|
|
|
self.key2row[key] = row
|
|
|
|
else:
|
|
|
|
raise ValueError(Errors.E197.format(row=row, key=key))
|
2017-08-19 17:52:25 +00:00
|
|
|
if vector is not None:
|
2021-04-19 08:30:03 +00:00
|
|
|
xp = get_array_module(self.data)
|
|
|
|
vector = xp.asarray(vector)
|
2017-10-30 09:03:08 +00:00
|
|
|
self.data[row] = vector
|
2020-05-19 14:41:26 +00:00
|
|
|
if self._unset.count(row):
|
|
|
|
self._unset.erase(self._unset.find(row))
|
2017-10-30 09:03:08 +00:00
|
|
|
return row
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2019-10-03 12:09:44 +00: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 17:25:08 +00:00
|
|
|
to it, by cosine.
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2017-10-31 23:18:08 +00: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 12:09:44 +00: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-10-31 23:18:08 +00:00
|
|
|
tuple.
|
|
|
|
"""
|
2021-10-27 12:08:31 +00:00
|
|
|
if self.mode == Mode.floret:
|
|
|
|
raise ValueError(Errors.E858.format(
|
|
|
|
mode=self.mode,
|
|
|
|
alternative="",
|
|
|
|
))
|
2021-04-19 08:30:03 +00:00
|
|
|
xp = get_array_module(self.data)
|
2020-05-19 14:41:26 +00:00
|
|
|
filled = sorted(list({row for row in self.key2row.values()}))
|
|
|
|
if len(filled) < n:
|
|
|
|
raise ValueError(Errors.E198.format(n=n, n_rows=len(filled)))
|
2021-04-19 08:30:03 +00:00
|
|
|
filled = xp.asarray(filled)
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2020-05-19 14:41:26 +00:00
|
|
|
norms = xp.linalg.norm(self.data[filled], axis=1, keepdims=True)
|
2019-10-21 10:04:46 +00:00
|
|
|
norms[norms == 0] = 1
|
2020-05-19 14:41:26 +00:00
|
|
|
vectors = self.data[filled] / norms
|
2017-10-31 22:23:34 +00:00
|
|
|
|
2019-10-03 12:09:44 +00:00
|
|
|
best_rows = xp.zeros((queries.shape[0], n), dtype='i')
|
|
|
|
scores = xp.zeros((queries.shape[0], n), dtype='f')
|
2017-10-31 17:25:08 +00: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 10:04:46 +00:00
|
|
|
batch_norms = xp.linalg.norm(batch, axis=1, keepdims=True)
|
|
|
|
batch_norms[batch_norms == 0] = 1
|
|
|
|
batch /= batch_norms
|
2017-10-31 17:25:08 +00: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 12:09:44 +00: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-16 21:18:55 +00: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 12:09:44 +00:00
|
|
|
scores[i:i+batch_size] = scores[sorted_index]
|
|
|
|
best_rows[i:i+batch_size] = best_rows[sorted_index]
|
2019-12-22 00:53:56 +00:00
|
|
|
|
2020-05-19 14:41:26 +00:00
|
|
|
for i, j in numpy.ndindex(best_rows.shape):
|
|
|
|
best_rows[i, j] = filled[best_rows[i, j]]
|
2019-10-22 18:10:42 +00: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 01:06:58 +00:00
|
|
|
row2key = {row: key for key, row in self.key2row.items()}
|
2021-04-19 08:30:03 +00:00
|
|
|
|
|
|
|
numpy_rows = get_current_ops().to_numpy(best_rows)
|
2018-12-10 15:19:18 +00:00
|
|
|
keys = xp.asarray(
|
2021-04-19 08:30:03 +00:00
|
|
|
[[row2key[row] for row in numpy_rows[i] if row in row2key]
|
2019-10-03 12:09:44 +00:00
|
|
|
for i in range(len(queries)) ], dtype="uint64")
|
2017-10-31 23:18:08 +00:00
|
|
|
return (keys, best_rows, scores)
|
2017-06-05 10:32:08 +00:00
|
|
|
|
2022-01-18 16:14:35 +00:00
|
|
|
def to_ops(self, ops: Ops):
|
|
|
|
self.data = ops.asarray(self.data)
|
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
def _get_cfg(self):
|
|
|
|
if self.mode == Mode.default:
|
|
|
|
return {
|
|
|
|
"mode": Mode(self.mode).value,
|
|
|
|
}
|
|
|
|
elif self.mode == Mode.floret:
|
|
|
|
return {
|
|
|
|
"mode": Mode(self.mode).value,
|
|
|
|
"minn": self.minn,
|
|
|
|
"maxn": self.maxn,
|
|
|
|
"hash_count": self.hash_count,
|
|
|
|
"hash_seed": self.hash_seed,
|
|
|
|
"bow": self.bow,
|
|
|
|
"eow": self.eow,
|
|
|
|
}
|
|
|
|
|
|
|
|
def _set_cfg(self, cfg):
|
|
|
|
self.mode = Mode(cfg.get("mode", Mode.default)).value
|
|
|
|
self.minn = cfg.get("minn", 0)
|
|
|
|
self.maxn = cfg.get("maxn", 0)
|
|
|
|
self.hash_count = cfg.get("hash_count", 0)
|
|
|
|
self.hash_seed = cfg.get("hash_seed", 0)
|
|
|
|
self.bow = cfg.get("bow", "<")
|
|
|
|
self.eow = cfg.get("eow", ">")
|
|
|
|
|
|
|
|
def to_disk(self, path, *, exclude=tuple()):
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Save the current state to a directory.
|
|
|
|
|
2020-05-24 15:20:58 +00:00
|
|
|
path (str / Path): A path to a directory, which will be created if
|
2019-03-10 18:16:45 +00:00
|
|
|
it doesn't exists.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#to_disk
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2017-09-16 17:45:09 +00:00
|
|
|
xp = get_array_module(self.data)
|
|
|
|
if xp is numpy:
|
2019-03-08 10:42:26 +00:00
|
|
|
save_array = lambda arr, file_: xp.save(file_, arr, allow_pickle=False)
|
2017-09-16 17:45:09 +00:00
|
|
|
else:
|
|
|
|
save_array = lambda arr, file_: xp.save(file_, arr)
|
2020-04-06 18:30:41 +00:00
|
|
|
|
|
|
|
def save_vectors(path):
|
|
|
|
# the source of numpy.save indicates that the file object is closed after use.
|
|
|
|
# but it seems that somehow this does not happen, as ResourceWarnings are raised here.
|
|
|
|
# in order to not rely on this, wrap in context manager.
|
|
|
|
with path.open("wb") as _file:
|
|
|
|
save_array(self.data, _file)
|
|
|
|
|
2019-12-22 00:53:56 +00:00
|
|
|
serializers = {
|
2021-10-27 12:08:31 +00:00
|
|
|
"strings": lambda p: self.strings.to_disk(p.with_suffix(".json")),
|
2020-06-20 13:52:00 +00:00
|
|
|
"vectors": lambda p: save_vectors(p),
|
2021-10-27 12:08:31 +00:00
|
|
|
"key2row": lambda p: srsly.write_msgpack(p, self.key2row),
|
|
|
|
"vectors.cfg": lambda p: srsly.write_json(p, self._get_cfg()),
|
2019-12-22 00:53:56 +00:00
|
|
|
}
|
2021-10-27 12:08:31 +00:00
|
|
|
return util.to_disk(path, serializers, exclude)
|
2017-08-18 18:45:48 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
def from_disk(self, path, *, exclude=tuple()):
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Loads state from a directory. Modifies the object in place and
|
|
|
|
returns it.
|
|
|
|
|
2020-05-24 15:20:58 +00:00
|
|
|
path (str / Path): Directory path, string or Path-like object.
|
2017-10-27 17:45:19 +00:00
|
|
|
RETURNS (Vectors): The modified object.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#from_disk
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2017-10-31 18:58:35 +00:00
|
|
|
def load_key2row(path):
|
2017-08-19 20:07:00 +00: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 00:28:22 +00:00
|
|
|
self.key2row = srsly.read_msgpack(path)
|
2017-10-31 18:58:35 +00:00
|
|
|
for key, row in self.key2row.items():
|
2018-03-31 11:28:25 +00:00
|
|
|
if self._unset.count(row):
|
|
|
|
self._unset.erase(self._unset.find(row))
|
2017-10-31 18:58:35 +00: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 16:42:11 +00:00
|
|
|
|
|
|
|
def load_vectors(path):
|
2020-01-29 16:06:46 +00:00
|
|
|
ops = get_current_ops()
|
2017-08-19 20:07:00 +00:00
|
|
|
if path.exists():
|
2020-01-29 16:06:46 +00:00
|
|
|
self.data = ops.xp.load(str(path))
|
2017-08-18 18:45:48 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
def load_settings(path):
|
|
|
|
if path.exists():
|
|
|
|
self._set_cfg(srsly.read_json(path))
|
|
|
|
|
2019-12-22 00:53:56 +00:00
|
|
|
serializers = {
|
2021-10-27 12:08:31 +00:00
|
|
|
"strings": lambda p: self.strings.from_disk(p.with_suffix(".json")),
|
2019-12-22 00:53:56 +00:00
|
|
|
"vectors": load_vectors,
|
2020-06-20 13:52:00 +00:00
|
|
|
"keys": load_keys,
|
|
|
|
"key2row": load_key2row,
|
2021-10-27 12:08:31 +00:00
|
|
|
"vectors.cfg": load_settings,
|
2019-12-22 00:53:56 +00:00
|
|
|
}
|
2017-08-18 18:45:48 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
util.from_disk(path, serializers, exclude)
|
2020-05-19 14:41:26 +00:00
|
|
|
self._sync_unset()
|
2017-08-19 16:42:11 +00:00
|
|
|
return self
|
2017-06-05 10:32:08 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
def to_bytes(self, *, exclude=tuple()):
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Serialize the current state to a binary string.
|
|
|
|
|
2019-03-10 18:16:45 +00:00
|
|
|
exclude (list): String names of serialization fields to exclude.
|
2017-10-27 17:45:19 +00:00
|
|
|
RETURNS (bytes): The serialized form of the `Vectors` object.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#to_bytes
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2017-06-05 10:32:08 +00:00
|
|
|
def serialize_weights():
|
2019-03-08 10:42:26 +00:00
|
|
|
if hasattr(self.data, "to_bytes"):
|
2017-08-18 18:45:48 +00:00
|
|
|
return self.data.to_bytes()
|
2017-06-05 10:32:08 +00: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 00:28:22 +00:00
|
|
|
return srsly.msgpack_dumps(self.data)
|
2019-03-10 18:16:45 +00:00
|
|
|
|
2019-12-22 00:53:56 +00:00
|
|
|
serializers = {
|
2021-10-27 12:08:31 +00:00
|
|
|
"strings": lambda: self.strings.to_bytes(),
|
2019-12-22 00:53:56 +00:00
|
|
|
"key2row": lambda: srsly.msgpack_dumps(self.key2row),
|
2021-10-27 12:08:31 +00:00
|
|
|
"vectors": serialize_weights,
|
|
|
|
"vectors.cfg": lambda: srsly.json_dumps(self._get_cfg()),
|
2019-12-22 00:53:56 +00:00
|
|
|
}
|
2021-10-27 12:08:31 +00:00
|
|
|
return util.to_bytes(serializers, exclude)
|
2017-06-05 10:32:08 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
def from_bytes(self, data, *, exclude=tuple()):
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Load state from a binary string.
|
|
|
|
|
|
|
|
data (bytes): The data to load from.
|
2019-03-10 18:16:45 +00:00
|
|
|
exclude (list): String names of serialization fields to exclude.
|
2017-10-27 17:45:19 +00:00
|
|
|
RETURNS (Vectors): The `Vectors` object.
|
2019-03-08 10:42:26 +00:00
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/vectors#from_bytes
|
2017-10-27 17:45:19 +00:00
|
|
|
"""
|
2017-06-05 10:32:08 +00:00
|
|
|
def deserialize_weights(b):
|
2019-03-08 10:42:26 +00:00
|
|
|
if hasattr(self.data, "from_bytes"):
|
2017-08-18 18:45:48 +00:00
|
|
|
self.data.from_bytes()
|
2017-06-05 10:32:08 +00:00
|
|
|
else:
|
2021-04-19 08:30:03 +00:00
|
|
|
xp = get_array_module(self.data)
|
|
|
|
self.data = xp.asarray(srsly.msgpack_loads(b))
|
2017-06-05 10:32:08 +00:00
|
|
|
|
2019-12-22 00:53:56 +00:00
|
|
|
deserializers = {
|
2021-10-27 12:08:31 +00:00
|
|
|
"strings": lambda b: self.strings.from_bytes(b),
|
2019-12-22 00:53:56 +00:00
|
|
|
"key2row": lambda b: self.key2row.update(srsly.msgpack_loads(b)),
|
2021-10-27 12:08:31 +00:00
|
|
|
"vectors": deserialize_weights,
|
|
|
|
"vectors.cfg": lambda b: self._set_cfg(srsly.json_loads(b))
|
2019-12-22 00:53:56 +00:00
|
|
|
}
|
2021-10-27 12:08:31 +00:00
|
|
|
util.from_bytes(data, deserializers, exclude)
|
2020-05-19 14:41:26 +00:00
|
|
|
self._sync_unset()
|
2017-08-19 16:42:11 +00:00
|
|
|
return self
|
2020-05-19 14:41:26 +00:00
|
|
|
|
2021-10-27 12:08:31 +00:00
|
|
|
def clear(self):
|
|
|
|
"""Clear all entries in the vector table.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/vectors#clear
|
|
|
|
"""
|
|
|
|
if self.mode == Mode.floret:
|
|
|
|
raise ValueError(Errors.E859)
|
|
|
|
self.key2row = {}
|
|
|
|
self._sync_unset()
|
|
|
|
|
2020-05-19 14:41:26 +00:00
|
|
|
def _sync_unset(self):
|
|
|
|
filled = {row for row in self.key2row.values()}
|
|
|
|
self._unset = cppset[int]({row for row in range(self.data.shape[0]) if row not in filled})
|