-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path__init__.py
3244 lines (3009 loc) · 138 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import bisect
import difflib
import gc
import http.client
import hashlib
import heapq
import lz4.frame
import math
import mmap
import operator
import os
import re
import sys
import tempfile
import threading
import time
import xxhash
import numpy as np
import uuid
from annoy import AnnoyIndex
from copy import deepcopy
from fasteners import InterProcessLock
from itertools import cycle, islice, chain, product, tee
from numbers import Number
from time import sleep
from pymagnitude.converter_shared import DEFAULT_NGRAM_END
from pymagnitude.converter_shared import BOW, EOW
from pymagnitude.converter_shared import CONVERTER_VERSION
from pymagnitude.converter_shared import fast_md5_file
from pymagnitude.converter_shared import char_ngrams
from pymagnitude.converter_shared import norm_matrix
from pymagnitude.converter_shared import unroll_elmo
from pymagnitude.converter_shared import KeyList
from pymagnitude.third_party.repoze.lru import lru_cache
try:
from itertools import imap
except ImportError:
imap = map
try:
from itertools import izip
except ImportError:
izip = zip
try:
unicode
except NameError:
unicode = str
try:
from http.client import CannotSendRequest, ResponseNotReady
except BaseException:
from httplib import CannotSendRequest, ResponseNotReady
try:
from urllib.request import urlretrieve
except BaseException:
from urllib import urlretrieve
try:
from urllib.parse import urlparse
except BaseException:
from urlparse import urlparse
try:
xrange
except NameError:
xrange = range
# Import AllenNLP
sys.path.append(os.path.dirname(__file__) + '/third_party/')
sys.path.append(os.path.dirname(__file__) + '/third_party_mock/')
from pymagnitude.third_party.allennlp.commands.elmo import ElmoEmbedder
# Import SQLite
try:
sys.path.append(os.path.dirname(__file__) + '/third_party/')
sys.path.append(os.path.dirname(__file__) + '/third_party/internal/')
from pymagnitude.third_party.internal.pysqlite2 import dbapi2 as sqlite3
db = sqlite3.connect(':memory:')
db.close()
_SQLITE_LIB = 'internal'
except Exception:
import sqlite3
_SQLITE_LIB = 'system'
# Import SQLite (APSW)
try:
import pymagnitude.third_party.internal.apsw as apsw
db = apsw.Connection(':memory:')
db.close()
_APSW_LIB = 'internal'
except Exception:
_APSW_LIB = 'none'
DEFAULT_LRU_CACHE_SIZE = 1000
def _sqlite_try_max_variable_number(num):
""" Tests whether SQLite can handle num variables """
db = sqlite3.connect(':memory:')
try:
db.cursor().execute(
"SELECT 1 IN (" + ",".join(["?"] * num) + ")",
([0] * num)
).fetchall()
return num
except BaseException:
return -1
finally:
db.close()
# Log function
def _log(*args):
args = list(args)
args[0] = "[Magnitude] " + args[0]
if not _log.disable_message:
print("[Magnitude] Magnitude is logging messages for slow "
"operations to standard error. To turn this"
" off pass log=False to the Magnitude "
"constructor.", file=sys.stderr)
_log.disable_message = True
print(*args, file=sys.stderr)
_log.disable_message = False
class Magnitude(object):
SQLITE_LIB = _SQLITE_LIB
APSW_LIB = _APSW_LIB
NGRAM_BEG = 1
NGRAM_END = DEFAULT_NGRAM_END
BOW = BOW
EOW = EOW
RARE_CHAR = u"\uF002".encode('utf-8')
FTS_SPECIAL = set('*^')
MMAP_THREAD_LOCK = {}
OOV_RNG_LOCK = threading.Lock()
SQLITE_MAX_VARIABLE_NUMBER = max(max((_sqlite_try_max_variable_number(n)
for n in [99, 999, 9999, 99999])), 1)
MAX_KEY_LENGTH_FOR_STEM = 150
MAX_KEY_LENGTH_FOR_OOV_SIM = 1000
ENGLISH_PREFIXES = ['counter', 'electro', 'circum', 'contra', 'contro',
'crypto', 'deuter', 'franco', 'hetero', 'megalo',
'preter', 'pseudo', 'after', 'under', 'amphi',
'anglo', 'astro', 'extra', 'hydro', 'hyper', 'infra',
'inter', 'intra', 'micro', 'multi', 'ortho', 'paleo',
'photo', 'proto', 'quasi', 'retro', 'socio', 'super',
'supra', 'trans', 'ultra', 'anti', 'back', 'down',
'fore', 'hind', 'midi', 'mini', 'over', 'post',
'self', 'step', 'with', 'afro', 'ambi', 'ante',
'anti', 'arch', 'auto', 'cryo', 'demi', 'demo',
'euro', 'gyro', 'hemi', 'homo', 'hypo', 'ideo',
'idio', 'indo', 'macr', 'maxi', 'mega', 'meta',
'mono', 'mult', 'omni', 'para', 'peri', 'pleo',
'poly', 'post', 'pros', 'pyro', 'semi', 'tele',
'vice', 'dis', 'dis', 'mid', 'mis', 'off', 'out',
'pre', 'pro', 'twi', 'ana', 'apo', 'bio', 'cis',
'con', 'com', 'col', 'cor', 'dia', 'dis', 'dif',
'duo', 'eco', 'epi', 'geo', 'im ', 'iso', 'mal',
'mon', 'neo', 'non', 'pan', 'ped', 'per', 'pod',
'pre', 'pro', 'pro', 'sub', 'sup', 'sur', 'syn',
'syl', 'sym', 'tri', 'uni', 'be', 'by', 'co', 'de',
'en', 'em', 'ex', 'on', 're', 'un', 'un', 'up', 'an',
'an', 'ap', 'bi', 'co', 'de', 'di', 'di', 'du', 'en',
'el', 'em', 'ep', 'ex', 'in', 'in', 'il', 'ir', 'sy',
'a', 'a', 'a']
ENGLISH_PREFIXES = sorted(
chain.from_iterable([(p + '-', p) for p in ENGLISH_PREFIXES]),
key=lambda x: len(x), reverse=True)
ENGLISH_SUFFIXES = ['ification', 'ologist', 'ology', 'ology', 'able',
'ible', 'hood', 'ness', 'less', 'ment', 'tion',
'logy', 'like', 'ise', 'ize', 'ful', 'ess', 'ism',
'ist', 'ish', 'ity', 'ant', 'oid', 'ory', 'ing', 'fy',
'ly', 'al']
ENGLISH_SUFFIXES = sorted(
chain.from_iterable([('-' + s, s) for s in ENGLISH_SUFFIXES]),
key=lambda x: len(x), reverse=True)
def __new__(cls, *args, **kwargs):
""" Returns a concatenated magnitude object, if Magnitude parameters """
if len(args) > 0 and isinstance(args[0], Magnitude):
obj = object.__new__(ConcatenatedMagnitude, *args, **kwargs)
obj.__init__(*args, **kwargs)
else:
obj = object.__new__(cls)
return obj
"""A Magnitude class that interfaces with the underlying SQLite
data store to provide efficient access.
Attributes:
path: The file path or URL to the magnitude file
stream: Stream the URL instead of downloading it
stream_options: Options to control the behavior of the streaming
lazy_loading: -1 = pre-load into memory, 0 = lazy loads with unbounded
in-memory cache, >0 lazy loads with an LRU cache of that
size
blocking: Even when lazy_loading is -1, the constructor will not block
it will instead pre-load into memory in a background thread,
if blocking is set to True, it will block until everything
is pre-loaded into memory
normalized: Returns unit normalized vectors
use_numpy: Returns a NumPy array if True or a list if False
case_insensitive: Searches for keys with case-insensitive search
pad_to_length: Pads to a certain length if examples are shorter than
that length or truncates if longer than that length.
truncate_left: if something needs to be truncated to the padding,
truncate off the left side
pad_left: Pads to the left.
placeholders: Extra empty dimensions to add to the vectors.
ngram_oov: Use character n-grams for generating out-of-vocabulary
vectors.
supress_warnings: Supress warnings generated
batch_size: Controls the maximum vector size used in memory directly
eager: Start loading non-critical resources in the background in
anticipation they will be used.
language: A ISO 639-1 Language Code (default: English 'en')
dtype: The dtype to use when use_numpy is True.
devices: A list of GPU device ids.
temp_dir: The directory Magnitude will use as its temporary directory
log: Enable log messages from Magnitude
_number_of_values: When the path is set to None and Magnitude is being
used to solely featurize keys directly into vectors,
_number_of_values should be set to the
approximate upper-bound of the number of keys
that will be looked up with query(). If you don't know
the exact number, be conservative and pick a large
number, while keeping in mind the bigger
_number_of_values is, the more memory it will consume.
_namespace: an optional namespace that will be prepended to each query
if provided
"""
def __init__(self, path, stream=False, stream_options=None,
lazy_loading=0, blocking=False, normalized=None,
use_numpy=True, case_insensitive=False,
pad_to_length=None, truncate_left=False,
pad_left=False, placeholders=0, ngram_oov=None,
supress_warnings=False, batch_size=3000000,
eager=None, language='en', dtype=np.float32,
devices=[], temp_dir=tempfile.gettempdir(),
log=None, _namespace=None,
_number_of_values=1000000):
"""Initializes a new Magnitude object."""
self.sqlite_lib = Magnitude.SQLITE_LIB
self.apsw_lib = Magnitude.APSW_LIB
self.closed = False
self.uid = str(uuid.uuid4()).replace("-", "")
self.stream = stream
self.stream_options = stream_options or {}
if self.stream:
if self.apsw_lib != 'internal':
raise RuntimeError(
"""You are trying to stream a model, but the
installation of Magnitude has partially failed so this
component will not work. Please try re-installing or create
a GitHub issue to further debug.""")
self.driver = apsw
self.http_vfs = HTTPVFS(options=self.stream_options)
download_vfs_options = deepcopy(self.stream_options)
download_vfs_options.update({
'sequential_cache_max_read': 500 * (1024 ** 2),
})
self.http_download_vfs = HTTPVFS(vfsname='http_download',
options=download_vfs_options)
else:
self.driver = sqlite3
self.fd = None
if path is None:
self.memory_db = True
self.path = ":memory:"
else:
self.memory_db = False
self.path = (
os.path.expanduser(path)
if not self.stream else MagnitudeUtils.download_model(
path, _download=False, _local=True))
self._all_conns = []
self.lazy_loading = lazy_loading
self.use_numpy = use_numpy
self.case_insensitive = case_insensitive
self.pad_to_length = pad_to_length
self.truncate_left = truncate_left
self.pad_left = pad_left
self.placeholders = placeholders
self.supress_warnings = supress_warnings
self.batch_size = batch_size
if eager is None:
self.eager = not(self.stream)
else:
self.eager = eager
self.language = language and language.lower()
self.dtype = dtype
if isinstance(devices, list):
self.devices = devices
else:
self.devices = [devices]
self.temp_dir = temp_dir
if log is None:
self.log = True if self.stream else log
else:
self.log = log
self._namespace = _namespace
self._number_of_values = _number_of_values
# Define conns and cursors store
self._conns = {}
self._cursors = {}
self._threads = []
# Convert the input file if not .magnitude
if self.path.endswith('.bin') or \
self.path.endswith('.txt') or \
self.path.endswith('.vec') or \
self.path.endswith('.hdf5'):
if not supress_warnings:
sys.stdout.write(
"""WARNING: You are attempting to directly use a `.bin`,
`.txt`, `.vec`, or `.hdf5` file with Magnitude. The file is being
converted to the `.magnitude` format (which is slow) so
that it can be used with this library. This will happen on
every run / re-boot of your computer. If you want to make
this faster pre-convert your vector model to the
`.magnitude` format with the built-in command utility:
`python -m pymagnitude.converter -i input_file -o output_file`
Refer to the README for more information.
You can pass `supress_warnings=True` to the constructor to
hide this message.""") # noqa
sys.stdout.flush()
from pymagnitude.converter_shared import convert as convert_vector_file # noqa
self.path = convert_vector_file(self.path)
# If the path doesn't exist locally, try a remote download
if not self.stream and not os.path.isfile(
self.path) and not self.memory_db:
self.path = MagnitudeUtils.download_model(
self.path, log=self.log, _local=True)
# Open a read-only file descriptor against the file
if not self.memory_db and not self.stream:
self.fd = os.open(self.path, os.O_RDONLY)
# Get metadata about the vectors
self.length = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='size'") \
.fetchall()[0][0]
version_query = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='version'") \
.fetchall()
self.version = version_query[0][0] if len(version_query) > 0 else 1
elmo_query = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='elmo'") \
.fetchall()
self.elmo = len(elmo_query) > 0 and elmo_query[0][0]
if ngram_oov is None:
self.ngram_oov = not(self._is_lm())
else:
self.ngram_oov = ngram_oov
if normalized is None:
self.normalized = not(self._is_lm())
else:
self.normalized = normalized
if not self.normalized:
try:
self._db().execute(
"SELECT magnitude FROM magnitude LIMIT 1")\
.fetchall()
except BaseException:
raise RuntimeError(
"""You are trying to access non-unit-normalized vectors.
However, your .magnitude file version does not support
this. Please re-download a newer .magnitude file for
this model or re-convert it if it is a custom model.""")
if CONVERTER_VERSION < self.version:
raise RuntimeError(
"""The `.magnitude` file you are using was built with a
newer version of Magnitude than your version of Magnitude.
Please update the Magnitude library as it is incompatible
with this particular `.magnitude` file.""") # noqa
self.emb_dim = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='dim'") \
.fetchall()[0][0]
self.precision = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='precision'") \
.fetchall()[0][0]
subword_query = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='subword'") \
.fetchall()
self.subword = len(subword_query) > 0 and subword_query[0][0]
if self.subword:
self.subword_start = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='subword_start'")\
.fetchall()[0][0]
self.subword_end = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='subword_end'") \
.fetchall()[0][0]
approx_query = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='approx'") \
.fetchall()
self.approx = len(approx_query) > 0 and approx_query[0][0]
if self.approx:
self.approx_trees = self._db().execute(
"SELECT value FROM magnitude_format WHERE key='approx_trees'")\
.fetchall()[0][0]
self.dim = self.emb_dim + self.placeholders
self.highest_entropy_dimensions = [row[0] for row in self._db().execute(
"SELECT value FROM magnitude_format WHERE key='entropy'")
.fetchall()]
duplicate_keys_query = self._db().execute(
"""SELECT value FROM magnitude_format
WHERE key='max_duplicate_keys'""").fetchall()
self.max_duplicate_keys = len(
duplicate_keys_query) > 0 and duplicate_keys_query[0][0]
if len(duplicate_keys_query) == 0:
duplicate_keys_query = self._db().execute("""
SELECT MAX(key_count)
FROM (
SELECT COUNT(key)
AS key_count
FROM magnitude
GROUP BY key
);
""").fetchall()
self.max_duplicate_keys = (
duplicate_keys_query[0][0] if duplicate_keys_query[0][0] is not None else 1) # noqa
# Iterate to pre-load
def _preload_memory():
if not self.eager: # So that it doesn't loop over the vectors twice
for key, vector in self._iter(put_cache=True, downloader=True):
pass
# Start creating mmap in background
self.setup_for_mmap = False
self._all_vectors = None
self._approx_index = None
self._elmo_embedder = None
if self.eager:
mmap_thread = threading.Thread(target=self.get_vectors_mmap,
args=(False,))
self._threads.append(mmap_thread)
mmap_thread.daemon = True
mmap_thread.start()
if self.approx:
approx_mmap_thread = threading.Thread(
target=self.get_approx_index, args=(False,))
self._threads.append(approx_mmap_thread)
approx_mmap_thread.daemon = True
approx_mmap_thread.start()
if self.elmo:
elmo_thread = threading.Thread(
target=self.get_elmo_embedder, args=(False,))
self._threads.append(elmo_thread)
elmo_thread.daemon = True
elmo_thread.start()
# Create cached methods
if self.lazy_loading <= 0:
@lru_cache(None, real_func=self._vector_for_key, remove_self=True)
def _vector_for_key_cached(*args, **kwargs):
return self._vector_for_key(*args, **kwargs)
@lru_cache(
None,
real_func=self._out_of_vocab_vector,
remove_self=True)
def _out_of_vocab_vector_cached(*args, **kwargs):
return self._out_of_vocab_vector(*args, **kwargs)
@lru_cache(None, real_func=self._key_for_index, remove_self=True)
def _key_for_index_cached(*args, **kwargs):
return self._key_for_index(*args, **kwargs)
self._vector_for_key_cached = _vector_for_key_cached
self._out_of_vocab_vector_cached = _out_of_vocab_vector_cached
self._key_for_index_cached = _key_for_index_cached
if self.lazy_loading == -1:
if blocking:
_preload_memory()
else:
preload_thread = threading.Thread(target=_preload_memory)
self._threads.append(preload_thread)
preload_thread.daemon = True
preload_thread.start()
elif self.lazy_loading > 0:
@lru_cache(
self.lazy_loading,
real_func=self._vector_for_key,
remove_self=True)
def _vector_for_key_cached(*args, **kwargs):
return self._vector_for_key(*args, **kwargs)
@lru_cache(
self.lazy_loading,
real_func=self._out_of_vocab_vector,
remove_self=True)
def _out_of_vocab_vector_cached(*args, **kwargs):
return self._out_of_vocab_vector(*args, **kwargs)
@lru_cache(
self.lazy_loading,
real_func=self._key_for_index,
remove_self=True)
def _key_for_index_cached(*args, **kwargs):
return self._key_for_index(*args, **kwargs)
self._vector_for_key_cached = _vector_for_key_cached
self._out_of_vocab_vector_cached = _out_of_vocab_vector_cached
self._key_for_index_cached = _key_for_index_cached
if self.eager and blocking:
self.get_vectors_mmap() # Wait for mmap to be available
if self.approx:
self.get_approx_index() # Wait for approx mmap to be available
if self.elmo:
self.get_elmo_embedder() # Wait for approx mmap to be available
def _setup_for_mmap(self):
# Setup variables for get_vectors_mmap()
self._all_vectors = None
self._approx_index = None
self._elmo_embedder = None
if not self.memory_db:
self.db_hash = fast_md5_file(self.path, stream=self.stream)
else:
self.db_hash = self.uid
self.md5 = hashlib.md5(",".join(
[self.path, self.db_hash, str(self.length),
str(self.dim), str(self.precision), str(self.case_insensitive)
]).encode('utf-8')).hexdigest()
self.path_to_mmap = os.path.join(self.temp_dir,
self.md5 + '.magmmap')
self.path_to_approx_mmap = os.path.join(self.temp_dir,
self.md5 + '.approx.magmmap')
self.path_to_elmo_w_mmap = os.path.join(self.temp_dir,
self.md5 + '.elmo.hdf5.magmmap')
self.path_to_elmo_o_mmap = os.path.join(self.temp_dir,
self.md5 + '.elmo.json.magmmap')
if self.path_to_mmap not in Magnitude.MMAP_THREAD_LOCK:
Magnitude.MMAP_THREAD_LOCK[self.path_to_mmap] = threading.Lock()
if self.path_to_approx_mmap not in Magnitude.MMAP_THREAD_LOCK:
Magnitude.MMAP_THREAD_LOCK[self.path_to_approx_mmap] = \
threading.Lock()
if self.path_to_elmo_w_mmap not in Magnitude.MMAP_THREAD_LOCK:
Magnitude.MMAP_THREAD_LOCK[self.path_to_elmo_w_mmap] = \
threading.Lock()
if self.path_to_elmo_o_mmap not in Magnitude.MMAP_THREAD_LOCK:
Magnitude.MMAP_THREAD_LOCK[self.path_to_elmo_o_mmap] = \
threading.Lock()
self.MMAP_THREAD_LOCK = Magnitude.MMAP_THREAD_LOCK[self.path_to_mmap]
self.MMAP_PROCESS_LOCK = InterProcessLock(self.path_to_mmap + '.lock')
self.APPROX_MMAP_THREAD_LOCK = \
Magnitude.MMAP_THREAD_LOCK[self.path_to_approx_mmap]
self.APPROX_MMAP_PROCESS_LOCK = \
InterProcessLock(self.path_to_approx_mmap + '.lock')
self.ELMO_W_MMAP_THREAD_LOCK = \
Magnitude.MMAP_THREAD_LOCK[self.path_to_elmo_w_mmap]
self.ELMO_W_MMAP_PROCESS_LOCK = \
InterProcessLock(self.path_to_elmo_w_mmap + '.lock')
self.ELMO_O_MMAP_THREAD_LOCK = \
Magnitude.MMAP_THREAD_LOCK[self.path_to_elmo_o_mmap]
self.ELMO_O_MMAP_PROCESS_LOCK = \
InterProcessLock(self.path_to_elmo_o_mmap + '.lock')
self.setup_for_mmap = True
def sqlite3_connect(self, downloader, *args, **kwargs):
"""Returns a sqlite3 connection."""
if (self.driver != sqlite3):
if 'check_same_thread' in kwargs:
del kwargs['check_same_thread']
if self.stream:
if downloader:
kwargs['vfs'] = self.http_download_vfs.vfsname
else:
kwargs['vfs'] = self.http_vfs.vfsname
kwargs['flags'] = self.driver.SQLITE_OPEN_READONLY
return self.driver.Connection(*args, **kwargs)
else:
return self.driver.connect(*args, **kwargs)
def _db(self, force_new=False, downloader=False):
"""Returns a cursor to the database. Each thread gets its
own cursor.
"""
identifier = threading.current_thread().ident
conn_exists = identifier in self._cursors
if not conn_exists or force_new:
if self.fd:
if os.name == 'nt':
conn = self.sqlite3_connect(downloader, self.path,
check_same_thread=False)
else:
conn = self.sqlite3_connect(downloader,
'/dev/fd/%d' % self.fd,
check_same_thread=False)
elif self.stream:
conn = self.sqlite3_connect(downloader,
self.path, check_same_thread=False)
else:
conn = self.sqlite3_connect(downloader,
self.path, check_same_thread=False)
self._create_empty_db(conn.cursor())
self._all_conns.append(conn)
if not conn_exists:
self._conns[identifier] = conn
self._cursors[identifier] = conn.cursor()
elif force_new:
return conn.cursor()
return self._cursors[identifier]
def _create_empty_db(self, db):
# Calculates the number of dimensions needed to prevent hashing from
# creating a collision error of a certain value for the number of
# expected feature values being hashed
collision_error_allowed = .001
number_of_dims = max(math.ceil(math.log(
((self._number_of_values ** 2) / (-2 * math.log(-collision_error_allowed + 1))), 100)), 2) # noqa
db.execute("DROP TABLE IF EXISTS `magnitude`;")
db.execute("""
CREATE TABLE `magnitude` (
key TEXT COLLATE NOCASE,
magnitude REAL
);
""")
db.execute("""
CREATE TABLE `magnitude_format` (
key TEXT COLLATE NOCASE,
value INTEGER
);
""")
insert_format_query = """
INSERT INTO `magnitude_format`(
key,
value
)
VALUES (
?, ?
);
"""
db.execute(insert_format_query, ('size', 0))
db.execute(insert_format_query, ('dim', number_of_dims))
db.execute(insert_format_query, ('precision', 0))
def _padding_vector(self):
"""Generates a padding vector."""
if self.use_numpy:
return np.zeros((self.dim,), dtype=self.dtype)
else:
return [0.0] * self.dim
def _key_t(self, key):
"""Transforms a key to lower case depending on case
sensitivity.
"""
if self.case_insensitive and (isinstance(key, str) or
isinstance(key, unicode)):
return key.lower()
return key
def _string_dist(self, a, b):
length = max(len(a), len(b))
return length - difflib.SequenceMatcher(None, a, b).ratio() * length
def _key_shrunk_2(self, key):
"""Shrinks more than two characters to two characters
"""
return re.sub(r"([^<])\1{2,}", r"\1\1", key)
def _key_shrunk_1(self, key):
"""Shrinks more than one character to a single character
"""
return re.sub(r"([^<])\1+", r"\1", key)
def _oov_key_t(self, key):
"""Transforms a key for out-of-vocabulary lookup.
"""
is_str = isinstance(key, str) or isinstance(key, unicode)
if is_str:
key = Magnitude.BOW + self._key_t(key) + Magnitude.EOW
return is_str, self._key_shrunk_2(key)
return is_str, key
def _oov_english_stem_english_ixes(self, key):
"""Strips away common English prefixes and suffixes."""
key_lower = key.lower()
start_idx = 0
end_idx = 0
for p in Magnitude.ENGLISH_PREFIXES:
if key_lower[:len(p)] == p:
start_idx = len(p)
break
for s in Magnitude.ENGLISH_SUFFIXES:
if key_lower[-len(s):] == s:
end_idx = len(s)
break
start_idx = start_idx if max(start_idx, end_idx) == start_idx else 0
end_idx = end_idx if max(start_idx, end_idx) == end_idx else 0
stripped_key = key[start_idx:len(key) - end_idx]
if len(stripped_key) < 4:
return key
elif stripped_key != key:
return self._oov_english_stem_english_ixes(stripped_key)
else:
return stripped_key
def _oov_stem(self, key):
"""Strips away common prefixes and suffixes."""
if len(key) <= Magnitude.MAX_KEY_LENGTH_FOR_STEM:
if self.language == 'en':
return self._oov_english_stem_english_ixes(key)
return key
def _db_query_similar_keys_vector(
self, key, orig_key, topn=3, normalized=None):
"""Finds similar keys in the database and gets the mean vector."""
normalized = normalized if normalized is not None else self.normalized
def _sql_escape_single(s):
return s.replace("'", "''")
def _sql_escape_fts(s):
return ''.join("\\" + c if c in Magnitude.FTS_SPECIAL
else c for c in s).replace('"', '""')
exact_search_query = """
SELECT *
FROM `magnitude`
WHERE key = ?
ORDER BY key = ? COLLATE NOCASE DESC
LIMIT ?;
"""
if self.subword and len(key) < Magnitude.MAX_KEY_LENGTH_FOR_OOV_SIM:
current_subword_start = self.subword_end
BOW_length = len(Magnitude.BOW) # noqa: N806
EOW_length = len(Magnitude.EOW) # noqa: N806
BOWEOW_length = BOW_length + EOW_length # noqa: N806
true_key_len = len(key) - BOWEOW_length
key_shrunk_stemmed = self._oov_stem(self._key_shrunk_1(orig_key))
key_shrunk = self._key_shrunk_1(orig_key)
key_stemmed = self._oov_stem(orig_key)
beginning_and_end_clause = ""
exact_matches = []
if true_key_len <= 6:
beginning_and_end_clause = """
magnitude.key LIKE '{0}%'
AND LENGTH(magnitude.key) <= {2} DESC,
magnitude.key LIKE '%{1}'
AND LENGTH(magnitude.key) <= {2} DESC,"""
beginning_and_end_clause = beginning_and_end_clause.format(
_sql_escape_single(key[BOW_length:BOW_length + 1]),
_sql_escape_single(key[-EOW_length - 1:-EOW_length]),
str(true_key_len))
if key != orig_key:
exact_matches.append((key_shrunk, self._key_shrunk_2(orig_key)))
if key_stemmed != orig_key:
exact_matches.append((key_stemmed,))
if key_shrunk_stemmed != orig_key:
exact_matches.append((key_shrunk_stemmed,))
if len(exact_matches) > 0:
for exact_match in exact_matches:
results = []
split_results = []
limits = np.array_split(list(range(topn)), len(exact_match))
for i, e in enumerate(exact_match):
limit = len(limits[i])
split_results.extend(self._db().execute(
exact_search_query, (e, e, limit)).fetchall())
results.extend(self._db().execute(
exact_search_query, (e, e, topn)).fetchall())
if len(split_results) >= topn:
results = split_results
if len(results) > 0:
break
else:
results = []
if len(results) == 0:
search_query = """
SELECT magnitude.*
FROM magnitude_subword, magnitude
WHERE char_ngrams MATCH ?
AND magnitude.rowid = magnitude_subword.rowid
ORDER BY
(
(
LENGTH(offsets(magnitude_subword)) -
LENGTH(
REPLACE(offsets(magnitude_subword), ' ', '')
)
)
+
1
) DESC,
""" + beginning_and_end_clause + """
LENGTH(magnitude.key) ASC
LIMIT ?;
""" # noqa
while (len(results) < topn and
current_subword_start >= self.subword_start):
ngrams = list(char_ngrams(
key, current_subword_start, current_subword_start))
ngram_limit_map = {
6: 4,
5: 8,
4: 12,
}
while current_subword_start in ngram_limit_map and len(
ngrams) > ngram_limit_map[current_subword_start]:
# Reduce the search parameter space by sampling every
# other ngram
ngrams = ngrams[:-1][::2] + ngrams[-1:]
params = (' OR '.join('"{0}"'.format(_sql_escape_fts(n))
for n in ngrams), topn)
results = self._db().execute(search_query,
params).fetchall()
small_typo = len(results) > 0 and self._string_dist(
results[0][0].lower(), orig_key.lower()) <= 4
if key_shrunk_stemmed != orig_key and key_shrunk_stemmed != key_shrunk and not small_typo: # noqa
ngrams = list(
char_ngrams(
self._oov_key_t(key_shrunk_stemmed)[1],
current_subword_start,
self.subword_end))
params = (' OR '.join('"{0}"'.format(_sql_escape_fts(n))
for n in ngrams), topn)
results = self._db().execute(search_query,
params).fetchall()
current_subword_start -= 1
else:
# As a backup do a search with 'NOCASE'
results = self._db().execute(exact_search_query,
(orig_key, orig_key, topn)).fetchall()
final_results = []
for result in results:
result_key, vec = self._db_full_result_to_vec(
result, normalized=normalized)
final_results.append(vec)
if len(final_results) > 0:
mean_vector = np.mean(final_results, axis=0)
return mean_vector / np.linalg.norm(mean_vector)
else:
return self._padding_vector()
def _seed(self, val):
"""Returns a unique seed for val and the (optional) namespace."""
if self._namespace:
return xxhash.xxh32(
self._namespace.encode('utf-8') +
Magnitude.RARE_CHAR +
val.encode('utf-8')).intdigest()
else:
return xxhash.xxh32(val.encode('utf-8')).intdigest()
def _is_lm(self):
"""Check if using a language model"""
return self.elmo
def _process_lm_output(self, q, normalized):
"""Process the output from a language model"""
zero_d = not(isinstance(q, list))
one_d = not(zero_d) and (len(q) == 0 or not(isinstance(q[0], list)))
if self.elmo:
if zero_d:
r_val = np.concatenate(self.get_elmo_embedder().embed_batch(
[[q]])[0], axis=1).flatten()
elif one_d:
r_val = np.concatenate(self.get_elmo_embedder().embed_batch(
[q])[0], axis=1)
else:
r_val = [np.concatenate(row, axis=1)
for row in self.get_elmo_embedder().embed_batch(q)]
if normalized:
if zero_d:
r_val = r_val / np.linalg.norm(r_val)
elif one_d:
r_val = norm_matrix(r_val)
else:
r_val = [norm_matrix(row) for row in r_val]
if self.placeholders > 0 or self.ngram_oov:
shape_p = list(r_val.shape) if zero_d or one_d else \
([len(r_val)] + list(max((row.shape for row in r_val))))
shape_p[-1] = self.dim
if self.placeholders > 0:
if zero_d or one_d:
r_val_p = np.zeros(shape_p, dtype=self.dtype)
else:
r_val_p = [np.zeros(shape_p[1:], dtype=self.dtype)
for row in r_val]
else:
r_val_p = r_val
if self.ngram_oov:
if zero_d:
lookup = self._vectors_for_keys_cached(
[q], normalized=normalized, force=True)
elif one_d:
lookup = self._vectors_for_keys_cached(
q, normalized=normalized, force=True)
else:
lookup = [None] * len(q)
for row, sq in enumerate(q):
lookup[row] = self._vectors_for_keys_cached(
sq, normalized=normalized, force=True)
for idx in product(*[xrange(s) for s in shape_p[:-1]]):
if zero_d:
key = q
if self.ngram_oov:
vec = r_val if self.__contains__(key) else lookup[0]
else:
vec = r_val
r_val_p[:self.emb_dim] = vec[:self.emb_dim]
elif one_d:
key = q[idx[0]]
if self.ngram_oov:
vec = r_val[idx] if self.__contains__(key) else \
lookup[idx[0]]
else:
vec = r_val[idx]
r_val_p[idx][:self.emb_dim] = vec[:self.emb_dim]
elif idx[1] < len(q[idx[0]]):
key = q[idx[0]][idx[1]]
if self.ngram_oov:
vec = r_val[idx[0]][idx[1]] if self.__contains__(key) \
else lookup[idx[0]][idx[1]]
else:
vec = r_val[idx[0]][idx[1]]
r_val_p[idx[0]][idx[1]][:self.emb_dim] = vec[:self.emb_dim]
r_val = r_val_p
if self.use_numpy:
return r_val
else:
return r_val.tolist()
def _out_of_vocab_vector(self, key, normalized=None, force=False):
"""Generates a random vector based on the hash of the key."""
normalized = normalized if normalized is not None else self.normalized
orig_key = key
is_str, key = self._oov_key_t(key)
if self._is_lm() and is_str and not force:
return self._process_lm_output(key, normalized)
if not is_str:
seed = self._seed(type(key).__name__)
Magnitude.OOV_RNG_LOCK.acquire()
np.random.seed(seed=seed)
random_vector = np.random.uniform(-1, 1, (self.emb_dim,))
Magnitude.OOV_RNG_LOCK.release()
random_vector[-1] = self.dtype(key) / np.finfo(self.dtype).max
elif not self.ngram_oov or len(key) < Magnitude.NGRAM_BEG:
seed = self._seed(key)
Magnitude.OOV_RNG_LOCK.acquire()
np.random.seed(seed=seed)
random_vector = np.random.uniform(-1, 1, (self.emb_dim,))
Magnitude.OOV_RNG_LOCK.release()
else:
ngrams = char_ngrams(key, Magnitude.NGRAM_BEG,
Magnitude.NGRAM_END)
random_vectors = []
for i, ngram in enumerate(ngrams):
seed = self._seed(ngram)
Magnitude.OOV_RNG_LOCK.acquire()
np.random.seed(seed=seed)
random_vectors.append(
np.random.uniform(-1, 1, (self.emb_dim,)))
Magnitude.OOV_RNG_LOCK.release()
random_vector = np.mean(random_vectors, axis=0)
np.random.seed()
if self.placeholders > 0:
random_vector = np.pad(random_vector, [(0, self.placeholders)],
mode='constant', constant_values=0.0)
if is_str:
random_vector = random_vector / np.linalg.norm(random_vector)
final_vector = (
random_vector *
0.3 +
self._db_query_similar_keys_vector(
key,
orig_key,
normalized=normalized) *
0.7)
if normalized:
final_vector = final_vector / np.linalg.norm(final_vector)
else:
final_vector = random_vector
if self.use_numpy:
return final_vector
else: