spark-nlp 5.3.2__py2.py3-none-any.whl → 5.4.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of spark-nlp might be problematic. Click here for more details.
- com/johnsnowlabs/ml/__init__.py +0 -0
- com/johnsnowlabs/ml/ai/__init__.py +10 -0
- {spark_nlp-5.3.2.dist-info → spark_nlp-5.4.0.dist-info}/METADATA +50 -60
- {spark_nlp-5.3.2.dist-info → spark_nlp-5.4.0.dist-info}/RECORD +28 -22
- sparknlp/__init__.py +3 -2
- sparknlp/annotator/classifier_dl/__init__.py +1 -0
- sparknlp/annotator/classifier_dl/mpnet_for_token_classification.py +173 -0
- sparknlp/annotator/classifier_dl/xlm_roberta_for_token_classification.py +3 -3
- sparknlp/annotator/embeddings/__init__.py +1 -0
- sparknlp/annotator/embeddings/bert_embeddings.py +4 -2
- sparknlp/annotator/embeddings/bert_sentence_embeddings.py +4 -2
- sparknlp/annotator/embeddings/bge_embeddings.py +2 -0
- sparknlp/annotator/embeddings/e5_embeddings.py +6 -2
- sparknlp/annotator/embeddings/mpnet_embeddings.py +2 -0
- sparknlp/annotator/embeddings/roberta_embeddings.py +4 -2
- sparknlp/annotator/embeddings/uae_embeddings.py +211 -0
- sparknlp/annotator/embeddings/xlm_roberta_embeddings.py +4 -2
- sparknlp/annotator/openai/openai_embeddings.py +43 -69
- sparknlp/annotator/seq2seq/__init__.py +2 -0
- sparknlp/annotator/seq2seq/llama2_transformer.py +2 -2
- sparknlp/annotator/seq2seq/m2m100_transformer.py +2 -2
- sparknlp/annotator/seq2seq/mistral_transformer.py +349 -0
- sparknlp/annotator/seq2seq/phi2_transformer.py +326 -0
- sparknlp/internal/__init__.py +443 -148
- sparknlp/pretrained/resource_downloader.py +2 -3
- {spark_nlp-5.3.2.dist-info → spark_nlp-5.4.0.dist-info}/.uuid +0 -0
- {spark_nlp-5.3.2.dist-info → spark_nlp-5.4.0.dist-info}/WHEEL +0 -0
- {spark_nlp-5.3.2.dist-info → spark_nlp-5.4.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# Copyright 2017-2022 John Snow Labs
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Contains classes for MPNetForTokenClassification."""
|
|
15
|
+
|
|
16
|
+
from sparknlp.common import *
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MPNetForTokenClassification(AnnotatorModel,
|
|
20
|
+
HasCaseSensitiveProperties,
|
|
21
|
+
HasBatchedAnnotate,
|
|
22
|
+
HasEngine,
|
|
23
|
+
HasMaxSentenceLengthLimit):
|
|
24
|
+
"""MPNetForTokenClassification can load XLM-RoBERTa Models with a token
|
|
25
|
+
classification head on top (a linear layer on top of the hidden-states
|
|
26
|
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
|
27
|
+
|
|
28
|
+
Pretrained models can be loaded with :meth:`.pretrained` of the companion
|
|
29
|
+
object:
|
|
30
|
+
|
|
31
|
+
>>> token_classifier = MPNetForTokenClassification.pretrained() \\
|
|
32
|
+
... .setInputCols(["token", "document"]) \\
|
|
33
|
+
... .setOutputCol("label")
|
|
34
|
+
The default model is ``"mpnet_base_token_classifier"``, if no
|
|
35
|
+
name is provided.
|
|
36
|
+
|
|
37
|
+
For available pretrained models please see the `Models Hub
|
|
38
|
+
<https://sparknlp.org/models?task=Named+Entity+Recognition>`__.
|
|
39
|
+
To see which models are compatible and how to import them see
|
|
40
|
+
`Import Transformers into Spark NLP 🚀
|
|
41
|
+
<https://github.com/JohnSnowLabs/spark-nlp/discussions/5669>`_.
|
|
42
|
+
|
|
43
|
+
====================== ======================
|
|
44
|
+
Input Annotation types Output Annotation type
|
|
45
|
+
====================== ======================
|
|
46
|
+
``DOCUMENT, TOKEN`` ``NAMED_ENTITY``
|
|
47
|
+
====================== ======================
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
batchSize
|
|
52
|
+
Batch size. Large values allows faster processing but requires more
|
|
53
|
+
memory, by default 8
|
|
54
|
+
caseSensitive
|
|
55
|
+
Whether to ignore case in tokens for embeddings matching, by default
|
|
56
|
+
True
|
|
57
|
+
configProtoBytes
|
|
58
|
+
ConfigProto from tensorflow, serialized into byte array.
|
|
59
|
+
maxSentenceLength
|
|
60
|
+
Max sentence length to process, by default 128
|
|
61
|
+
|
|
62
|
+
Examples
|
|
63
|
+
--------
|
|
64
|
+
>>> import sparknlp
|
|
65
|
+
>>> from sparknlp.base import *
|
|
66
|
+
>>> from sparknlp.annotator import *
|
|
67
|
+
>>> from pyspark.ml import Pipeline
|
|
68
|
+
>>> documentAssembler = DocumentAssembler() \\
|
|
69
|
+
... .setInputCol("text") \\
|
|
70
|
+
... .setOutputCol("document")
|
|
71
|
+
>>> tokenizer = Tokenizer() \\
|
|
72
|
+
... .setInputCols(["document"]) \\
|
|
73
|
+
... .setOutputCol("token")
|
|
74
|
+
>>> tokenClassifier = MPNetForTokenClassification.pretrained() \\
|
|
75
|
+
... .setInputCols(["token", "document"]) \\
|
|
76
|
+
... .setOutputCol("label") \\
|
|
77
|
+
... .setCaseSensitive(True)
|
|
78
|
+
>>> pipeline = Pipeline().setStages([
|
|
79
|
+
... documentAssembler,
|
|
80
|
+
... tokenizer,
|
|
81
|
+
... tokenClassifier
|
|
82
|
+
... ])
|
|
83
|
+
>>> data = spark.createDataFrame([["John Lenon was born in London and lived in Paris. My name is Sarah and I live in London"]]).toDF("text")
|
|
84
|
+
>>> result = pipeline.fit(data).transform(data)
|
|
85
|
+
>>> result.select("label.result").show(truncate=False)
|
|
86
|
+
+------------------------------------------------------------------------------------+
|
|
87
|
+
|result |
|
|
88
|
+
+------------------------------------------------------------------------------------+
|
|
89
|
+
|[B-PER, I-PER, O, O, O, B-LOC, O, O, O, B-LOC, O, O, O, O, B-PER, O, O, O, O, B-LOC]|
|
|
90
|
+
+------------------------------------------------------------------------------------+
|
|
91
|
+
"""
|
|
92
|
+
name = "MPNetForTokenClassification"
|
|
93
|
+
|
|
94
|
+
inputAnnotatorTypes = [AnnotatorType.DOCUMENT, AnnotatorType.TOKEN]
|
|
95
|
+
|
|
96
|
+
outputAnnotatorType = AnnotatorType.NAMED_ENTITY
|
|
97
|
+
|
|
98
|
+
configProtoBytes = Param(Params._dummy(),
|
|
99
|
+
"configProtoBytes",
|
|
100
|
+
"ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()",
|
|
101
|
+
TypeConverters.toListInt)
|
|
102
|
+
|
|
103
|
+
def getClasses(self):
|
|
104
|
+
"""
|
|
105
|
+
Returns labels used to train this model
|
|
106
|
+
"""
|
|
107
|
+
return self._call_java("getClasses")
|
|
108
|
+
|
|
109
|
+
def setConfigProtoBytes(self, b):
|
|
110
|
+
"""Sets configProto from tensorflow, serialized into byte array.
|
|
111
|
+
|
|
112
|
+
Parameters
|
|
113
|
+
----------
|
|
114
|
+
b : List[int]
|
|
115
|
+
ConfigProto from tensorflow, serialized into byte array
|
|
116
|
+
"""
|
|
117
|
+
return self._set(configProtoBytes=b)
|
|
118
|
+
|
|
119
|
+
@keyword_only
|
|
120
|
+
def __init__(self, classname="com.johnsnowlabs.nlp.annotators.classifier.dl.MPNetForTokenClassification",
|
|
121
|
+
java_model=None):
|
|
122
|
+
super(MPNetForTokenClassification, self).__init__(
|
|
123
|
+
classname=classname,
|
|
124
|
+
java_model=java_model
|
|
125
|
+
)
|
|
126
|
+
self._setDefault(
|
|
127
|
+
batchSize=8,
|
|
128
|
+
maxSentenceLength=128,
|
|
129
|
+
caseSensitive=True
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def loadSavedModel(folder, spark_session):
|
|
134
|
+
"""Loads a locally saved model.
|
|
135
|
+
|
|
136
|
+
Parameters
|
|
137
|
+
----------
|
|
138
|
+
folder : str
|
|
139
|
+
Folder of the saved model
|
|
140
|
+
spark_session : pyspark.sql.SparkSession
|
|
141
|
+
The current SparkSession
|
|
142
|
+
|
|
143
|
+
Returns
|
|
144
|
+
-------
|
|
145
|
+
XlmRoBertaForTokenClassification
|
|
146
|
+
The restored model
|
|
147
|
+
"""
|
|
148
|
+
from sparknlp.internal import _MPNetForTokenClassifierLoader
|
|
149
|
+
jModel = _MPNetForTokenClassifierLoader(folder, spark_session._jsparkSession)._java_obj
|
|
150
|
+
return MPNetForTokenClassification(java_model=jModel)
|
|
151
|
+
|
|
152
|
+
@staticmethod
|
|
153
|
+
def pretrained(name="mpnet_base_token_classifier", lang="en", remote_loc=None):
|
|
154
|
+
"""Downloads and loads a pretrained model.
|
|
155
|
+
|
|
156
|
+
Parameters
|
|
157
|
+
----------
|
|
158
|
+
name : str, optional
|
|
159
|
+
Name of the pretrained model, by default
|
|
160
|
+
"mpnet_base_token_classifier"
|
|
161
|
+
lang : str, optional
|
|
162
|
+
Language of the pretrained model, by default "en"
|
|
163
|
+
remote_loc : str, optional
|
|
164
|
+
Optional remote address of the resource, by default None. Will use
|
|
165
|
+
Spark NLPs repositories otherwise.
|
|
166
|
+
|
|
167
|
+
Returns
|
|
168
|
+
-------
|
|
169
|
+
XlmRoBertaForTokenClassification
|
|
170
|
+
The restored model
|
|
171
|
+
"""
|
|
172
|
+
from sparknlp.pretrained import ResourceDownloader
|
|
173
|
+
return ResourceDownloader.downloadModel(MPNetForTokenClassification, name, lang, remote_loc)
|
|
@@ -31,7 +31,7 @@ class XlmRoBertaForTokenClassification(AnnotatorModel,
|
|
|
31
31
|
>>> token_classifier = XlmRoBertaForTokenClassification.pretrained() \\
|
|
32
32
|
... .setInputCols(["token", "document"]) \\
|
|
33
33
|
... .setOutputCol("label")
|
|
34
|
-
The default model is ``"
|
|
34
|
+
The default model is ``"mpnet_base_token_classifier"``, if no
|
|
35
35
|
name is provided.
|
|
36
36
|
|
|
37
37
|
For available pretrained models please see the `Models Hub
|
|
@@ -150,14 +150,14 @@ class XlmRoBertaForTokenClassification(AnnotatorModel,
|
|
|
150
150
|
return XlmRoBertaForTokenClassification(java_model=jModel)
|
|
151
151
|
|
|
152
152
|
@staticmethod
|
|
153
|
-
def pretrained(name="
|
|
153
|
+
def pretrained(name="mpnet_base_token_classifier", lang="en", remote_loc=None):
|
|
154
154
|
"""Downloads and loads a pretrained model.
|
|
155
155
|
|
|
156
156
|
Parameters
|
|
157
157
|
----------
|
|
158
158
|
name : str, optional
|
|
159
159
|
Name of the pretrained model, by default
|
|
160
|
-
"
|
|
160
|
+
"mpnet_base_token_classifier"
|
|
161
161
|
lang : str, optional
|
|
162
162
|
Language of the pretrained model, by default "en"
|
|
163
163
|
remote_loc : str, optional
|
|
@@ -36,3 +36,4 @@ from sparknlp.annotator.embeddings.xlm_roberta_embeddings import *
|
|
|
36
36
|
from sparknlp.annotator.embeddings.xlm_roberta_sentence_embeddings import *
|
|
37
37
|
from sparknlp.annotator.embeddings.xlnet_embeddings import *
|
|
38
38
|
from sparknlp.annotator.embeddings.bge_embeddings import *
|
|
39
|
+
from sparknlp.annotator.embeddings.uae_embeddings import *
|
|
@@ -164,7 +164,7 @@ class BertEmbeddings(AnnotatorModel,
|
|
|
164
164
|
)
|
|
165
165
|
|
|
166
166
|
@staticmethod
|
|
167
|
-
def loadSavedModel(folder, spark_session):
|
|
167
|
+
def loadSavedModel(folder, spark_session, use_openvino=False):
|
|
168
168
|
"""Loads a locally saved model.
|
|
169
169
|
|
|
170
170
|
Parameters
|
|
@@ -173,6 +173,8 @@ class BertEmbeddings(AnnotatorModel,
|
|
|
173
173
|
Folder of the saved model
|
|
174
174
|
spark_session : pyspark.sql.SparkSession
|
|
175
175
|
The current SparkSession
|
|
176
|
+
use_openvino: bool
|
|
177
|
+
Use OpenVINO backend
|
|
176
178
|
|
|
177
179
|
Returns
|
|
178
180
|
-------
|
|
@@ -180,7 +182,7 @@ class BertEmbeddings(AnnotatorModel,
|
|
|
180
182
|
The restored model
|
|
181
183
|
"""
|
|
182
184
|
from sparknlp.internal import _BertLoader
|
|
183
|
-
jModel = _BertLoader(folder, spark_session._jsparkSession)._java_obj
|
|
185
|
+
jModel = _BertLoader(folder, spark_session._jsparkSession, use_openvino)._java_obj
|
|
184
186
|
return BertEmbeddings(java_model=jModel)
|
|
185
187
|
|
|
186
188
|
@staticmethod
|
|
@@ -180,7 +180,7 @@ class BertSentenceEmbeddings(AnnotatorModel,
|
|
|
180
180
|
)
|
|
181
181
|
|
|
182
182
|
@staticmethod
|
|
183
|
-
def loadSavedModel(folder, spark_session):
|
|
183
|
+
def loadSavedModel(folder, spark_session, use_openvino=False):
|
|
184
184
|
"""Loads a locally saved model.
|
|
185
185
|
|
|
186
186
|
Parameters
|
|
@@ -189,6 +189,8 @@ class BertSentenceEmbeddings(AnnotatorModel,
|
|
|
189
189
|
Folder of the saved model
|
|
190
190
|
spark_session : pyspark.sql.SparkSession
|
|
191
191
|
The current SparkSession
|
|
192
|
+
use_openvino: bool
|
|
193
|
+
Use OpenVINO backend
|
|
192
194
|
|
|
193
195
|
Returns
|
|
194
196
|
-------
|
|
@@ -196,7 +198,7 @@ class BertSentenceEmbeddings(AnnotatorModel,
|
|
|
196
198
|
The restored model
|
|
197
199
|
"""
|
|
198
200
|
from sparknlp.internal import _BertSentenceLoader
|
|
199
|
-
jModel = _BertSentenceLoader(folder, spark_session._jsparkSession)._java_obj
|
|
201
|
+
jModel = _BertSentenceLoader(folder, spark_session._jsparkSession, use_openvino)._java_obj
|
|
200
202
|
return BertSentenceEmbeddings(java_model=jModel)
|
|
201
203
|
|
|
202
204
|
@staticmethod
|
|
@@ -26,6 +26,8 @@ class BGEEmbeddings(AnnotatorModel,
|
|
|
26
26
|
|
|
27
27
|
BGE, or BAAI General Embeddings, a model that can map any text to a low-dimensional dense
|
|
28
28
|
vector which can be used for tasks like retrieval, classification, clustering, or semantic search.
|
|
29
|
+
|
|
30
|
+
Note that this annotator is only supported for Spark Versions 3.4 and up.
|
|
29
31
|
|
|
30
32
|
Pretrained models can be loaded with `pretrained` of the companion object:
|
|
31
33
|
|
|
@@ -25,6 +25,8 @@ class E5Embeddings(AnnotatorModel,
|
|
|
25
25
|
"""Sentence embeddings using E5.
|
|
26
26
|
|
|
27
27
|
E5, a weakly supervised text embedding model that can generate text embeddings tailored to any task (e.g., classification, retrieval, clustering, text evaluation, etc.)
|
|
28
|
+
Note that this annotator is only supported for Spark Versions 3.4 and up.
|
|
29
|
+
|
|
28
30
|
Pretrained models can be loaded with :meth:`.pretrained` of the companion
|
|
29
31
|
object:
|
|
30
32
|
|
|
@@ -149,7 +151,7 @@ class E5Embeddings(AnnotatorModel,
|
|
|
149
151
|
)
|
|
150
152
|
|
|
151
153
|
@staticmethod
|
|
152
|
-
def loadSavedModel(folder, spark_session):
|
|
154
|
+
def loadSavedModel(folder, spark_session, use_openvino=False):
|
|
153
155
|
"""Loads a locally saved model.
|
|
154
156
|
|
|
155
157
|
Parameters
|
|
@@ -158,6 +160,8 @@ class E5Embeddings(AnnotatorModel,
|
|
|
158
160
|
Folder of the saved model
|
|
159
161
|
spark_session : pyspark.sql.SparkSession
|
|
160
162
|
The current SparkSession
|
|
163
|
+
use_openvino : bool
|
|
164
|
+
Use OpenVINO backend
|
|
161
165
|
|
|
162
166
|
Returns
|
|
163
167
|
-------
|
|
@@ -165,7 +169,7 @@ class E5Embeddings(AnnotatorModel,
|
|
|
165
169
|
The restored model
|
|
166
170
|
"""
|
|
167
171
|
from sparknlp.internal import _E5Loader
|
|
168
|
-
jModel = _E5Loader(folder, spark_session._jsparkSession)._java_obj
|
|
172
|
+
jModel = _E5Loader(folder, spark_session._jsparkSession, use_openvino)._java_obj
|
|
169
173
|
return E5Embeddings(java_model=jModel)
|
|
170
174
|
|
|
171
175
|
@staticmethod
|
|
@@ -28,6 +28,8 @@ class MPNetEmbeddings(AnnotatorModel,
|
|
|
28
28
|
to inherit the advantages of masked language modeling and permuted language modeling for
|
|
29
29
|
natural language understanding.
|
|
30
30
|
|
|
31
|
+
Note that this annotator is only supported for Spark Versions 3.4 and up.
|
|
32
|
+
|
|
31
33
|
Pretrained models can be loaded with :meth:`.pretrained` of the companion
|
|
32
34
|
object:
|
|
33
35
|
|
|
@@ -181,7 +181,7 @@ class RoBertaEmbeddings(AnnotatorModel,
|
|
|
181
181
|
)
|
|
182
182
|
|
|
183
183
|
@staticmethod
|
|
184
|
-
def loadSavedModel(folder, spark_session):
|
|
184
|
+
def loadSavedModel(folder, spark_session, use_openvino=False):
|
|
185
185
|
"""Loads a locally saved model.
|
|
186
186
|
|
|
187
187
|
Parameters
|
|
@@ -190,6 +190,8 @@ class RoBertaEmbeddings(AnnotatorModel,
|
|
|
190
190
|
Folder of the saved model
|
|
191
191
|
spark_session : pyspark.sql.SparkSession
|
|
192
192
|
The current SparkSession
|
|
193
|
+
use_openvino: bool
|
|
194
|
+
Use OpenVINO backend
|
|
193
195
|
|
|
194
196
|
Returns
|
|
195
197
|
-------
|
|
@@ -197,7 +199,7 @@ class RoBertaEmbeddings(AnnotatorModel,
|
|
|
197
199
|
The restored model
|
|
198
200
|
"""
|
|
199
201
|
from sparknlp.internal import _RoBertaLoader
|
|
200
|
-
jModel = _RoBertaLoader(folder, spark_session._jsparkSession)._java_obj
|
|
202
|
+
jModel = _RoBertaLoader(folder, spark_session._jsparkSession, use_openvino)._java_obj
|
|
201
203
|
return RoBertaEmbeddings(java_model=jModel)
|
|
202
204
|
|
|
203
205
|
@staticmethod
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# Copyright 2017-2022 John Snow Labs
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Contains classes for UAEEmbeddings."""
|
|
15
|
+
|
|
16
|
+
from sparknlp.common import *
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class UAEEmbeddings(AnnotatorModel,
|
|
20
|
+
HasEmbeddingsProperties,
|
|
21
|
+
HasCaseSensitiveProperties,
|
|
22
|
+
HasStorageRef,
|
|
23
|
+
HasBatchedAnnotate,
|
|
24
|
+
HasMaxSentenceLengthLimit):
|
|
25
|
+
"""Sentence embeddings using Universal AnglE Embedding (UAE).
|
|
26
|
+
|
|
27
|
+
UAE is a novel angle-optimized text embedding model, designed to improve semantic textual
|
|
28
|
+
similarity tasks, which are crucial for Large Language Model (LLM) applications. By
|
|
29
|
+
introducing angle optimization in a complex space, AnglE effectively mitigates saturation of
|
|
30
|
+
the cosine similarity function.
|
|
31
|
+
|
|
32
|
+
Pretrained models can be loaded with :meth:`.pretrained` of the companion
|
|
33
|
+
object:
|
|
34
|
+
|
|
35
|
+
>>> embeddings = UAEEmbeddings.pretrained() \\
|
|
36
|
+
... .setInputCols(["document"]) \\
|
|
37
|
+
... .setOutputCol("UAE_embeddings")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
The default model is ``"uae_large_v1"``, if no name is provided.
|
|
41
|
+
|
|
42
|
+
For available pretrained models please see the
|
|
43
|
+
`Models Hub <https://sparknlp.org/models?q=UAE>`__.
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
====================== ======================
|
|
47
|
+
Input Annotation types Output Annotation type
|
|
48
|
+
====================== ======================
|
|
49
|
+
``DOCUMENT`` ``SENTENCE_EMBEDDINGS``
|
|
50
|
+
====================== ======================
|
|
51
|
+
|
|
52
|
+
Parameters
|
|
53
|
+
----------
|
|
54
|
+
batchSize
|
|
55
|
+
Size of every batch , by default 8
|
|
56
|
+
dimension
|
|
57
|
+
Number of embedding dimensions, by default 768
|
|
58
|
+
caseSensitive
|
|
59
|
+
Whether to ignore case in tokens for embeddings matching, by default False
|
|
60
|
+
maxSentenceLength
|
|
61
|
+
Max sentence length to process, by default 512
|
|
62
|
+
configProtoBytes
|
|
63
|
+
ConfigProto from tensorflow, serialized into byte array.
|
|
64
|
+
|
|
65
|
+
References
|
|
66
|
+
----------
|
|
67
|
+
|
|
68
|
+
`AnglE-optimized Text Embeddings <https://arxiv.org/abs/2309.12871>`__
|
|
69
|
+
`UAE Github Repository <https://github.com/baochi0212/uae-embedding>`__
|
|
70
|
+
|
|
71
|
+
**Paper abstract**
|
|
72
|
+
|
|
73
|
+
*High-quality text embedding is pivotal in improving semantic textual similarity (STS) tasks,
|
|
74
|
+
which are crucial components in Large Language Model (LLM) applications. However, a common
|
|
75
|
+
challenge existing text embedding models face is the problem of vanishing gradients, primarily
|
|
76
|
+
due to their reliance on the cosine function in the optimization objective, which has
|
|
77
|
+
saturation zones. To address this issue, this paper proposes a novel angle-optimized text
|
|
78
|
+
embedding model called AnglE. The core idea of AnglE is to introduce angle optimization in a
|
|
79
|
+
complex space. This novel approach effectively mitigates the adverse effects of the saturation
|
|
80
|
+
zone in the cosine function, which can impede gradient and hinder optimization processes. To
|
|
81
|
+
set up a comprehensive STS evaluation, we experimented on existing short-text STS datasets and
|
|
82
|
+
a newly collected long-text STS dataset from GitHub Issues. Furthermore, we examine
|
|
83
|
+
domain-specific STS scenarios with limited labeled data and explore how AnglE works with
|
|
84
|
+
LLM-annotated data. Extensive experiments were conducted on various tasks including short-text
|
|
85
|
+
STS, long-text STS, and domain-specific STS tasks. The results show that AnglE outperforms the
|
|
86
|
+
state-of-the-art (SOTA) STS models that ignore the cosine saturation zone. These findings
|
|
87
|
+
demonstrate the ability of AnglE to generate high-quality text embeddings and the usefulness
|
|
88
|
+
of angle optimization in STS.*
|
|
89
|
+
|
|
90
|
+
Examples
|
|
91
|
+
--------
|
|
92
|
+
>>> import sparknlp
|
|
93
|
+
>>> from sparknlp.base import *
|
|
94
|
+
>>> from sparknlp.annotator import *
|
|
95
|
+
>>> from pyspark.ml import Pipeline
|
|
96
|
+
>>> documentAssembler = DocumentAssembler() \\
|
|
97
|
+
... .setInputCol("text") \\
|
|
98
|
+
... .setOutputCol("document")
|
|
99
|
+
>>> embeddings = UAEEmbeddings.pretrained() \\
|
|
100
|
+
... .setInputCols(["document"]) \\
|
|
101
|
+
... .setOutputCol("embeddings")
|
|
102
|
+
>>> embeddingsFinisher = EmbeddingsFinisher() \\
|
|
103
|
+
... .setInputCols("embeddings") \\
|
|
104
|
+
... .setOutputCols("finished_embeddings") \\
|
|
105
|
+
... .setOutputAsVector(True)
|
|
106
|
+
>>> pipeline = Pipeline().setStages([
|
|
107
|
+
... documentAssembler,
|
|
108
|
+
... embeddings,
|
|
109
|
+
... embeddingsFinisher
|
|
110
|
+
... ])
|
|
111
|
+
>>> data = spark.createDataFrame([["hello world", "hello moon"]]).toDF("text")
|
|
112
|
+
>>> result = pipeline.fit(data).transform(data)
|
|
113
|
+
>>> result.selectExpr("explode(finished_embeddings) as result").show(5, 80)
|
|
114
|
+
+--------------------------------------------------------------------------------+
|
|
115
|
+
| result|
|
|
116
|
+
+--------------------------------------------------------------------------------+
|
|
117
|
+
|[0.50387806, 0.5861606, 0.35129607, -0.76046336, -0.32446072, -0.117674336, 0...|
|
|
118
|
+
|[0.6660665, 0.961762, 0.24854276, -0.1018044, -0.6569202, 0.027635604, 0.1915...|
|
|
119
|
+
+--------------------------------------------------------------------------------+
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
name = "UAEEmbeddings"
|
|
123
|
+
|
|
124
|
+
inputAnnotatorTypes = [AnnotatorType.DOCUMENT]
|
|
125
|
+
|
|
126
|
+
outputAnnotatorType = AnnotatorType.SENTENCE_EMBEDDINGS
|
|
127
|
+
poolingStrategy = Param(Params._dummy(),
|
|
128
|
+
"poolingStrategy",
|
|
129
|
+
"Pooling strategy to use for sentence embeddings",
|
|
130
|
+
TypeConverters.toString)
|
|
131
|
+
|
|
132
|
+
def setPoolingStrategy(self, value):
|
|
133
|
+
"""Pooling strategy to use for sentence embeddings.
|
|
134
|
+
|
|
135
|
+
Available pooling strategies for sentence embeddings are:
|
|
136
|
+
- `"cls"`: leading `[CLS]` token
|
|
137
|
+
- `"cls_avg"`: leading `[CLS]` token + mean of all other tokens
|
|
138
|
+
- `"last"`: embeddings of the last token in the sequence
|
|
139
|
+
- `"avg"`: mean of all tokens
|
|
140
|
+
- `"max"`: max of all embedding features of the entire token sequence
|
|
141
|
+
- `"int"`: An integer number, which represents the index of the token to use as the
|
|
142
|
+
embedding
|
|
143
|
+
|
|
144
|
+
Parameters
|
|
145
|
+
----------
|
|
146
|
+
value : str
|
|
147
|
+
Pooling strategy to use for sentence embeddings
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
valid_strategies = {"cls", "cls_avg", "last", "avg", "max"}
|
|
151
|
+
if value in valid_strategies or value.isdigit():
|
|
152
|
+
return self._set(poolingStrategy=value)
|
|
153
|
+
else:
|
|
154
|
+
raise ValueError(f"Invalid pooling strategy: {value}. "
|
|
155
|
+
f"Valid strategies are: {', '.join(self.valid_strategies)} or an integer.")
|
|
156
|
+
|
|
157
|
+
@keyword_only
|
|
158
|
+
def __init__(self, classname="com.johnsnowlabs.nlp.embeddings.UAEEmbeddings", java_model=None):
|
|
159
|
+
super(UAEEmbeddings, self).__init__(
|
|
160
|
+
classname=classname,
|
|
161
|
+
java_model=java_model
|
|
162
|
+
)
|
|
163
|
+
self._setDefault(
|
|
164
|
+
dimension=1024,
|
|
165
|
+
batchSize=8,
|
|
166
|
+
maxSentenceLength=512,
|
|
167
|
+
caseSensitive=False,
|
|
168
|
+
poolingStrategy="cls"
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
@staticmethod
|
|
172
|
+
def loadSavedModel(folder, spark_session):
|
|
173
|
+
"""Loads a locally saved model.
|
|
174
|
+
|
|
175
|
+
Parameters
|
|
176
|
+
----------
|
|
177
|
+
folder : str
|
|
178
|
+
Folder of the saved model
|
|
179
|
+
spark_session : pyspark.sql.SparkSession
|
|
180
|
+
The current SparkSession
|
|
181
|
+
|
|
182
|
+
Returns
|
|
183
|
+
-------
|
|
184
|
+
UAEEmbeddings
|
|
185
|
+
The restored model
|
|
186
|
+
"""
|
|
187
|
+
from sparknlp.internal import _UAEEmbeddingsLoader
|
|
188
|
+
jModel = _UAEEmbeddingsLoader(folder, spark_session._jsparkSession)._java_obj
|
|
189
|
+
return UAEEmbeddings(java_model=jModel)
|
|
190
|
+
|
|
191
|
+
@staticmethod
|
|
192
|
+
def pretrained(name="uae_large_v1", lang="en", remote_loc=None):
|
|
193
|
+
"""Downloads and loads a pretrained model.
|
|
194
|
+
|
|
195
|
+
Parameters
|
|
196
|
+
----------
|
|
197
|
+
name : str, optional
|
|
198
|
+
Name of the pretrained model, by default "UAE_small"
|
|
199
|
+
lang : str, optional
|
|
200
|
+
Language of the pretrained model, by default "en"
|
|
201
|
+
remote_loc : str, optional
|
|
202
|
+
Optional remote address of the resource, by default None. Will use
|
|
203
|
+
Spark NLPs repositories otherwise.
|
|
204
|
+
|
|
205
|
+
Returns
|
|
206
|
+
-------
|
|
207
|
+
UAEEmbeddings
|
|
208
|
+
The restored model
|
|
209
|
+
"""
|
|
210
|
+
from sparknlp.pretrained import ResourceDownloader
|
|
211
|
+
return ResourceDownloader.downloadModel(UAEEmbeddings, name, lang, remote_loc)
|
|
@@ -181,7 +181,7 @@ class XlmRoBertaEmbeddings(AnnotatorModel,
|
|
|
181
181
|
)
|
|
182
182
|
|
|
183
183
|
@staticmethod
|
|
184
|
-
def loadSavedModel(folder, spark_session):
|
|
184
|
+
def loadSavedModel(folder, spark_session, use_openvino=False):
|
|
185
185
|
"""Loads a locally saved model.
|
|
186
186
|
|
|
187
187
|
Parameters
|
|
@@ -190,6 +190,8 @@ class XlmRoBertaEmbeddings(AnnotatorModel,
|
|
|
190
190
|
Folder of the saved model
|
|
191
191
|
spark_session : pyspark.sql.SparkSession
|
|
192
192
|
The current SparkSession
|
|
193
|
+
use_openvino: bool
|
|
194
|
+
Use OpenVINO backend
|
|
193
195
|
|
|
194
196
|
Returns
|
|
195
197
|
-------
|
|
@@ -197,7 +199,7 @@ class XlmRoBertaEmbeddings(AnnotatorModel,
|
|
|
197
199
|
The restored model
|
|
198
200
|
"""
|
|
199
201
|
from sparknlp.internal import _XlmRoBertaLoader
|
|
200
|
-
jModel = _XlmRoBertaLoader(folder, spark_session._jsparkSession)._java_obj
|
|
202
|
+
jModel = _XlmRoBertaLoader(folder, spark_session._jsparkSession, use_openvino)._java_obj
|
|
201
203
|
return XlmRoBertaEmbeddings(java_model=jModel)
|
|
202
204
|
|
|
203
205
|
@staticmethod
|