spark-nlp 5.4.2__py2.py3-none-any.whl → 5.5.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.

@@ -0,0 +1,181 @@
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 E5Embeddings."""
15
+
16
+ from sparknlp.common import *
17
+
18
+
19
+ class NomicEmbeddings(AnnotatorModel, HasEmbeddingsProperties, HasCaseSensitiveProperties, HasStorageRef,
20
+ HasBatchedAnnotate, HasMaxSentenceLengthLimit):
21
+ """Sentence embeddings using NomicEmbeddings.
22
+
23
+ nomic-embed-text-v1 is 8192 context length text encoder that surpasses OpenAI
24
+ text-embedding-ada-002 and text-embedding-3-small performance on short and long context tasks.
25
+
26
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
27
+ object:
28
+
29
+ >>> embeddings = NomicEmbeddings.pretrained() \\
30
+ ... .setInputCols(["document"]) \\
31
+ ... .setOutputCol("nomic_embeddings")
32
+
33
+
34
+ The default model is ``"nomic_small"``, if no name is provided.
35
+
36
+ For available pretrained models please see the
37
+ `Models Hub <https://sparknlp.org/models?q=Nomic>`__.
38
+
39
+
40
+ ====================== ======================
41
+ Input Annotation types Output Annotation type
42
+ ====================== ======================
43
+ ``DOCUMENT`` ``SENTENCE_EMBEDDINGS``
44
+ ====================== ======================
45
+
46
+ Parameters
47
+ ----------
48
+ batchSize
49
+ Size of every batch , by default 8
50
+ dimension
51
+ Number of embedding dimensions, by default 768
52
+ caseSensitive
53
+ Whether to ignore case in tokens for embeddings matching, by default False
54
+ maxSentenceLength
55
+ Max sentence length to process, by default 512
56
+ configProtoBytes
57
+ ConfigProto from tensorflow, serialized into byte array.
58
+
59
+ References
60
+ ----------
61
+ `Text Embeddings by Weakly-Supervised Contrastive Pre-training <https://arxiv.org/pdf/2212.03533>`__
62
+
63
+ https://github.com/microsoft/unilm/tree/master/nomic
64
+
65
+ **Paper abstract**
66
+
67
+ *This technical report describes the training
68
+ of nomic-embed-text-v1, the first fully reproducible,
69
+ open-source, open-weights, opendata, 8192 context length
70
+ English text embedding model that outperforms both OpenAI
71
+ Ada-002 and OpenAI text-embedding-3-small
72
+ on short and long-context tasks. We release
73
+ the training code and model weights under
74
+ an Apache 2 license. In contrast with other
75
+ open-source models, we release a training data
76
+ loader with 235 million curated text pairs that
77
+ allows for the full replication of nomic-embedtext-v1.
78
+ You can find code and data to replicate the
79
+ model at https://github.com/nomicai/contrastors.*
80
+
81
+ Examples
82
+ --------
83
+ >>> import sparknlp
84
+ >>> from sparknlp.base import *
85
+ >>> from sparknlp.annotator import *
86
+ >>> from pyspark.ml import Pipeline
87
+ >>> documentAssembler = DocumentAssembler() \\
88
+ ... .setInputCol("text") \\
89
+ ... .setOutputCol("document")
90
+ >>> embeddings = NomicEmbeddings.pretrained() \\
91
+ ... .setInputCols(["document"]) \\
92
+ ... .setOutputCol("nomic_embeddings")
93
+ >>> embeddingsFinisher = EmbeddingsFinisher() \\
94
+ ... .setInputCols(["nomic_embeddings"]) \\
95
+ ... .setOutputCols("finished_embeddings") \\
96
+ ... .setOutputAsVector(True)
97
+ >>> pipeline = Pipeline().setStages([
98
+ ... documentAssembler,
99
+ ... embeddings,
100
+ ... embeddingsFinisher
101
+ ... ])
102
+ >>> data = spark.createDataFrame([["query: how much protein should a female eat",
103
+ ... "passage: As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day." + \
104
+ ... "But, as you can see from this chart, you'll need to increase that if you're expecting or training for a" + \
105
+ ... "marathon. Check out the chart below to see how much protein you should be eating each day.",
106
+ ... ]]).toDF("text")
107
+ >>> result = pipeline.fit(data).transform(data)
108
+ >>> result.selectExpr("explode(finished_embeddings) as result").show(5, 80)
109
+ +--------------------------------------------------------------------------------+
110
+ | result|
111
+ +--------------------------------------------------------------------------------+
112
+ |[[8.0190285E-4, -0.005974853, -0.072875895, 0.007944068, 0.026059335, -0.0080...|
113
+ |[[0.050514214, 0.010061974, -0.04340176, -0.020937217, 0.05170225, 0.01157857...|
114
+ +--------------------------------------------------------------------------------+
115
+ """
116
+
117
+ name = "NomicEmbeddings"
118
+
119
+ inputAnnotatorTypes = [AnnotatorType.DOCUMENT]
120
+
121
+ outputAnnotatorType = AnnotatorType.SENTENCE_EMBEDDINGS
122
+ configProtoBytes = Param(Params._dummy(), "configProtoBytes",
123
+ "ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()",
124
+ TypeConverters.toListInt)
125
+
126
+ def setConfigProtoBytes(self, b):
127
+ """Sets configProto from tensorflow, serialized into byte array.
128
+
129
+ Parameters
130
+ ----------
131
+ b : List[int]
132
+ ConfigProto from tensorflow, serialized into byte array
133
+ """
134
+ return self._set(configProtoBytes=b)
135
+
136
+ @keyword_only
137
+ def __init__(self, classname="com.johnsnowlabs.nlp.embeddings.NomicEmbeddings", java_model=None):
138
+ super(NomicEmbeddings, self).__init__(classname=classname, java_model=java_model)
139
+ self._setDefault(dimension=768, batchSize=8, maxSentenceLength=512, caseSensitive=False, )
140
+
141
+ @staticmethod
142
+ def loadSavedModel(folder, spark_session, use_openvino=False):
143
+ """Loads a locally saved model.
144
+
145
+ Parameters
146
+ ----------
147
+ folder : str
148
+ Folder of the saved model
149
+ spark_session : pyspark.sql.SparkSession
150
+ The current SparkSession
151
+
152
+ Returns
153
+ -------
154
+ NomicEmbeddings
155
+ The restored model
156
+ """
157
+ from sparknlp.internal import _NomicLoader
158
+ jModel = _NomicLoader(folder, spark_session._jsparkSession, use_openvino)._java_obj
159
+ return NomicEmbeddings(java_model=jModel)
160
+
161
+ @staticmethod
162
+ def pretrained(name="nomic_small", lang="en", remote_loc=None):
163
+ """Downloads and loads a pretrained model.
164
+
165
+ Parameters
166
+ ----------
167
+ name : str, optional
168
+ Name of the pretrained model, by default "nomic_small"
169
+ lang : str, optional
170
+ Language of the pretrained model, by default "en"
171
+ remote_loc : str, optional
172
+ Optional remote address of the resource, by default None. Will use
173
+ Spark NLPs repositories otherwise.
174
+
175
+ Returns
176
+ -------
177
+ NomicEmbeddings
178
+ The restored model
179
+ """
180
+ from sparknlp.pretrained import ResourceDownloader
181
+ return ResourceDownloader.downloadModel(NomicEmbeddings, name, lang, remote_loc)
@@ -0,0 +1,202 @@
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 SnowFlakeEmbeddings."""
15
+
16
+ from sparknlp.common import *
17
+
18
+
19
+ class SnowFlakeEmbeddings(AnnotatorModel,
20
+ HasEmbeddingsProperties,
21
+ HasCaseSensitiveProperties,
22
+ HasStorageRef,
23
+ HasBatchedAnnotate,
24
+ HasMaxSentenceLengthLimit):
25
+ """Sentence embeddings using SnowFlake.
26
+
27
+ snowflake-arctic-embed is a suite of text embedding models that focuses on creating
28
+ high-quality retrieval models optimized for performance.
29
+
30
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
31
+ object:
32
+
33
+ >>> embeddings = SnowFlakeEmbeddings.pretrained() \\
34
+ ... .setInputCols(["document"]) \\
35
+ ... .setOutputCol("SnowFlake_embeddings")
36
+
37
+
38
+ The default model is ``"snowflake_artic_m"``, if no name is provided.
39
+
40
+ For available pretrained models please see the
41
+ `Models Hub <https://sparknlp.org/models?q=SnowFlake>`__.
42
+
43
+
44
+ ====================== ======================
45
+ Input Annotation types Output Annotation type
46
+ ====================== ======================
47
+ ``DOCUMENT`` ``SENTENCE_EMBEDDINGS``
48
+ ====================== ======================
49
+
50
+ Parameters
51
+ ----------
52
+ batchSize
53
+ Size of every batch , by default 8
54
+ dimension
55
+ Number of embedding dimensions, by default 768
56
+ caseSensitive
57
+ Whether to ignore case in tokens for embeddings matching, by default False
58
+ maxSentenceLength
59
+ Max sentence length to process, by default 512
60
+ configProtoBytes
61
+ ConfigProto from tensorflow, serialized into byte array.
62
+
63
+ References
64
+ ----------
65
+
66
+ `Arctic-Embed: Scalable, Efficient, and Accurate Text Embedding Models <https://arxiv.org/abs/2405.05374>`__
67
+ `Snowflake Arctic-Embed Models <https://github.com/Snowflake-Labs/arctic-embed>`__
68
+
69
+ **Paper abstract**
70
+
71
+ *The models are trained by leveraging existing open-source text representation models, such
72
+ as bert-base-uncased, and are trained in a multi-stage pipeline to optimize their retrieval
73
+ performance. First, the models are trained with large batches of query-document pairs where
74
+ negatives are derived in-batch—pretraining leverages about 400m samples of a mix of public
75
+ datasets and proprietary web search data. Following pretraining models are further optimized
76
+ with long training on a smaller dataset (about 1m samples) of triplets of query, positive
77
+ document, and negative document derived from hard harmful mining. Mining of the negatives and
78
+ data curation is crucial to retrieval accuracy. A detailed technical report will be available
79
+ shortly. *
80
+
81
+ Examples
82
+ --------
83
+ >>> import sparknlp
84
+ >>> from sparknlp.base import *
85
+ >>> from sparknlp.annotator import *
86
+ >>> from pyspark.ml import Pipeline
87
+ >>> documentAssembler = DocumentAssembler() \\
88
+ ... .setInputCol("text") \\
89
+ ... .setOutputCol("document")
90
+ >>> embeddings = SnowFlakeEmbeddings.pretrained() \\
91
+ ... .setInputCols(["document"]) \\
92
+ ... .setOutputCol("embeddings")
93
+ >>> embeddingsFinisher = EmbeddingsFinisher() \\
94
+ ... .setInputCols("embeddings") \\
95
+ ... .setOutputCols("finished_embeddings") \\
96
+ ... .setOutputAsVector(True)
97
+ >>> pipeline = Pipeline().setStages([
98
+ ... documentAssembler,
99
+ ... embeddings,
100
+ ... embeddingsFinisher
101
+ ... ])
102
+ >>> data = spark.createDataFrame([["hello world", "hello moon"]]).toDF("text")
103
+ >>> result = pipeline.fit(data).transform(data)
104
+ >>> result.selectExpr("explode(finished_embeddings) as result").show(5, 80)
105
+ +--------------------------------------------------------------------------------+
106
+ | result|
107
+ +--------------------------------------------------------------------------------+
108
+ |[0.50387806, 0.5861606, 0.35129607, -0.76046336, -0.32446072, -0.117674336, 0...|
109
+ |[0.6660665, 0.961762, 0.24854276, -0.1018044, -0.6569202, 0.027635604, 0.1915...|
110
+ +--------------------------------------------------------------------------------+
111
+ """
112
+
113
+ name = "SnowFlakeEmbeddings"
114
+
115
+ inputAnnotatorTypes = [AnnotatorType.DOCUMENT]
116
+
117
+ outputAnnotatorType = AnnotatorType.SENTENCE_EMBEDDINGS
118
+ poolingStrategy = Param(Params._dummy(),
119
+ "poolingStrategy",
120
+ "Pooling strategy to use for sentence embeddings",
121
+ TypeConverters.toString)
122
+
123
+ def setPoolingStrategy(self, value):
124
+ """Pooling strategy to use for sentence embeddings.
125
+
126
+ Available pooling strategies for sentence embeddings are:
127
+ - `"cls"`: leading `[CLS]` token
128
+ - `"cls_avg"`: leading `[CLS]` token + mean of all other tokens
129
+ - `"last"`: embeddings of the last token in the sequence
130
+ - `"avg"`: mean of all tokens
131
+ - `"max"`: max of all embedding features of the entire token sequence
132
+ - `"int"`: An integer number, which represents the index of the token to use as the
133
+ embedding
134
+
135
+ Parameters
136
+ ----------
137
+ value : str
138
+ Pooling strategy to use for sentence embeddings
139
+ """
140
+
141
+ valid_strategies = {"cls", "cls_avg", "last", "avg", "max"}
142
+ if value in valid_strategies or value.isdigit():
143
+ return self._set(poolingStrategy=value)
144
+ else:
145
+ raise ValueError(f"Invalid pooling strategy: {value}. "
146
+ f"Valid strategies are: {', '.join(self.valid_strategies)} or an integer.")
147
+
148
+ @keyword_only
149
+ def __init__(self, classname="com.johnsnowlabs.nlp.embeddings.SnowFlakeEmbeddings", java_model=None):
150
+ super(SnowFlakeEmbeddings, self).__init__(
151
+ classname=classname,
152
+ java_model=java_model
153
+ )
154
+ self._setDefault(
155
+ dimension=1024,
156
+ batchSize=8,
157
+ maxSentenceLength=512,
158
+ caseSensitive=False,
159
+ poolingStrategy="cls"
160
+ )
161
+
162
+ @staticmethod
163
+ def loadSavedModel(folder, spark_session):
164
+ """Loads a locally saved model.
165
+
166
+ Parameters
167
+ ----------
168
+ folder : str
169
+ Folder of the saved model
170
+ spark_session : pyspark.sql.SparkSession
171
+ The current SparkSession
172
+
173
+ Returns
174
+ -------
175
+ SnowFlakeEmbeddings
176
+ The restored model
177
+ """
178
+ from sparknlp.internal import _SnowFlakeEmbeddingsLoader
179
+ jModel = _SnowFlakeEmbeddingsLoader(folder, spark_session._jsparkSession)._java_obj
180
+ return SnowFlakeEmbeddings(java_model=jModel)
181
+
182
+ @staticmethod
183
+ def pretrained(name="snowflake_artic_m", lang="en", remote_loc=None):
184
+ """Downloads and loads a pretrained model.
185
+
186
+ Parameters
187
+ ----------
188
+ name : str, optional
189
+ Name of the pretrained model, by default "snowflake_artic_m"
190
+ lang : str, optional
191
+ Language of the pretrained model, by default "en"
192
+ remote_loc : str, optional
193
+ Optional remote address of the resource, by default None. Will use
194
+ Spark NLPs repositories otherwise.
195
+
196
+ Returns
197
+ -------
198
+ SnowFlakeEmbeddings
199
+ The restored model
200
+ """
201
+ from sparknlp.pretrained import ResourceDownloader
202
+ return ResourceDownloader.downloadModel(SnowFlakeEmbeddings, name, lang, remote_loc)
@@ -21,3 +21,10 @@ from sparknlp.annotator.seq2seq.llama2_transformer import *
21
21
  from sparknlp.annotator.seq2seq.m2m100_transformer import *
22
22
  from sparknlp.annotator.seq2seq.phi2_transformer import *
23
23
  from sparknlp.annotator.seq2seq.mistral_transformer import *
24
+ from sparknlp.annotator.seq2seq.auto_gguf_model import *
25
+ from sparknlp.annotator.seq2seq.phi3_transformer import *
26
+ from sparknlp.annotator.seq2seq.nllb_transformer import *
27
+ from sparknlp.annotator.seq2seq.cpm_transformer import *
28
+ from sparknlp.annotator.seq2seq.qwen_transformer import *
29
+ from sparknlp.annotator.seq2seq.starcoder_transformer import *
30
+ from sparknlp.annotator.seq2seq.llama3_transformer import *