spark-nlp 6.1.2rc1__py2.py3-none-any.whl → 6.1.3rc1__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,329 @@
1
+ # Copyright 2017-2023 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 the AutoGGUFReranker."""
15
+ from typing import List, Dict
16
+
17
+ from sparknlp.common import *
18
+
19
+
20
+ class AutoGGUFReranker(AnnotatorModel, HasBatchedAnnotate, HasLlamaCppProperties):
21
+ """
22
+ Annotator that uses the llama.cpp library to rerank text documents based on their relevance
23
+ to a given query using GGUF-format reranking models.
24
+
25
+ This annotator is specifically designed for text reranking tasks, where multiple documents
26
+ or text passages are ranked according to their relevance to a query. It uses specialized
27
+ reranking models in GGUF format that output relevance scores for each input document.
28
+
29
+ The reranker takes a query (set via :meth:`.setQuery`) and a list of documents, then returns the
30
+ same documents with added metadata containing relevance scores. The documents are processed
31
+ in batches and each receives a ``relevance_score`` in its metadata indicating how relevant
32
+ it is to the provided query.
33
+
34
+ For settable parameters, and their explanations, see the parameters of this class and refer to
35
+ the llama.cpp documentation of
36
+ `server.cpp <https://github.com/ggerganov/llama.cpp/tree/7d5e8777ae1d21af99d4f95be10db4870720da91/examples/server>`__
37
+ for more information.
38
+
39
+ If the parameters are not set, the annotator will default to use the parameters provided by
40
+ the model.
41
+
42
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
43
+ object:
44
+
45
+ >>> reranker = AutoGGUFReranker.pretrained() \\
46
+ ... .setInputCols(["document"]) \\
47
+ ... .setOutputCol("reranked_documents") \\
48
+ ... .setQuery("A man is eating pasta.")
49
+
50
+ The default model is ``"bge-reranker-v2-m3-Q4_K_M"``, if no name is provided.
51
+
52
+ For extended examples of usage, see the
53
+ `AutoGGUFRerankerTest <https://github.com/JohnSnowLabs/spark-nlp/tree/master/src/test/scala/com/johnsnowlabs/nlp/annotators/seq2seq/AutoGGUFRerankerTest.scala>`__
54
+ and the
55
+ `example notebook <https://github.com/JohnSnowLabs/spark-nlp/tree/master/examples/python/llama.cpp/llama.cpp_in_Spark_NLP_AutoGGUFReranker.ipynb>`__.
56
+
57
+ For available pretrained models please see the `Models Hub <https://sparknlp.org/models>`__.
58
+
59
+ ====================== ======================
60
+ Input Annotation types Output Annotation type
61
+ ====================== ======================
62
+ ``DOCUMENT`` ``DOCUMENT``
63
+ ====================== ======================
64
+
65
+ Parameters
66
+ ----------
67
+ query
68
+ The query to be used for reranking. If not set, the input text will be used as the query.
69
+ nThreads
70
+ Set the number of threads to use during generation
71
+ nThreadsDraft
72
+ Set the number of threads to use during draft generation
73
+ nThreadsBatch
74
+ Set the number of threads to use during batch and prompt processing
75
+ nThreadsBatchDraft
76
+ Set the number of threads to use during batch and prompt processing
77
+ nCtx
78
+ Set the size of the prompt context
79
+ nBatch
80
+ Set the logical batch size for prompt processing (must be >=32 to use BLAS)
81
+ nUbatch
82
+ Set the physical batch size for prompt processing (must be >=32 to use BLAS)
83
+ nGpuLayers
84
+ Set the number of layers to store in VRAM (-1 - use default)
85
+ nGpuLayersDraft
86
+ Set the number of layers to store in VRAM for the draft model (-1 - use default)
87
+ gpuSplitMode
88
+ Set how to split the model across GPUs
89
+ mainGpu
90
+ Set the main GPU that is used for scratch and small tensors.
91
+ tensorSplit
92
+ Set how split tensors should be distributed across GPUs
93
+ grpAttnN
94
+ Set the group-attention factor
95
+ grpAttnW
96
+ Set the group-attention width
97
+ ropeFreqBase
98
+ Set the RoPE base frequency, used by NTK-aware scaling
99
+ ropeFreqScale
100
+ Set the RoPE frequency scaling factor, expands context by a factor of 1/N
101
+ yarnExtFactor
102
+ Set the YaRN extrapolation mix factor
103
+ yarnAttnFactor
104
+ Set the YaRN scale sqrt(t) or attention magnitude
105
+ yarnBetaFast
106
+ Set the YaRN low correction dim or beta
107
+ yarnBetaSlow
108
+ Set the YaRN high correction dim or alpha
109
+ yarnOrigCtx
110
+ Set the YaRN original context size of model
111
+ defragmentationThreshold
112
+ Set the KV cache defragmentation threshold
113
+ numaStrategy
114
+ Set optimization strategies that help on some NUMA systems (if available)
115
+ ropeScalingType
116
+ Set the RoPE frequency scaling method, defaults to linear unless specified by the model
117
+ poolingType
118
+ Set the pooling type for embeddings, use model default if unspecified
119
+ modelDraft
120
+ Set the draft model for speculative decoding
121
+ modelAlias
122
+ Set a model alias
123
+ lookupCacheStaticFilePath
124
+ Set path to static lookup cache to use for lookup decoding (not updated by generation)
125
+ lookupCacheDynamicFilePath
126
+ Set path to dynamic lookup cache to use for lookup decoding (updated by generation)
127
+ flashAttention
128
+ Whether to enable Flash Attention
129
+ inputPrefixBos
130
+ Whether to add prefix BOS to user inputs, preceding the `--in-prefix` string
131
+ useMmap
132
+ Whether to use memory-map model (faster load but may increase pageouts if not using mlock)
133
+ useMlock
134
+ Whether to force the system to keep model in RAM rather than swapping or compressing
135
+ noKvOffload
136
+ Whether to disable KV offload
137
+ systemPrompt
138
+ Set a system prompt to use
139
+ chatTemplate
140
+ The chat template to use
141
+ inputPrefix
142
+ Set the prompt to start generation with
143
+ inputSuffix
144
+ Set a suffix for infilling
145
+ cachePrompt
146
+ Whether to remember the prompt to avoid reprocessing it
147
+ nPredict
148
+ Set the number of tokens to predict
149
+ topK
150
+ Set top-k sampling
151
+ topP
152
+ Set top-p sampling
153
+ minP
154
+ Set min-p sampling
155
+ tfsZ
156
+ Set tail free sampling, parameter z
157
+ typicalP
158
+ Set locally typical sampling, parameter p
159
+ temperature
160
+ Set the temperature
161
+ dynatempRange
162
+ Set the dynamic temperature range
163
+ dynatempExponent
164
+ Set the dynamic temperature exponent
165
+ repeatLastN
166
+ Set the last n tokens to consider for penalties
167
+ repeatPenalty
168
+ Set the penalty of repeated sequences of tokens
169
+ frequencyPenalty
170
+ Set the repetition alpha frequency penalty
171
+ presencePenalty
172
+ Set the repetition alpha presence penalty
173
+ miroStat
174
+ Set MiroStat sampling strategies.
175
+ mirostatTau
176
+ Set the MiroStat target entropy, parameter tau
177
+ mirostatEta
178
+ Set the MiroStat learning rate, parameter eta
179
+ penalizeNl
180
+ Whether to penalize newline tokens
181
+ nKeep
182
+ Set the number of tokens to keep from the initial prompt
183
+ seed
184
+ Set the RNG seed
185
+ nProbs
186
+ Set the amount top tokens probabilities to output if greater than 0.
187
+ minKeep
188
+ Set the amount of tokens the samplers should return at least (0 = disabled)
189
+ grammar
190
+ Set BNF-like grammar to constrain generations
191
+ penaltyPrompt
192
+ Override which part of the prompt is penalized for repetition.
193
+ ignoreEos
194
+ Set whether to ignore end of stream token and continue generating (implies --logit-bias 2-inf)
195
+ disableTokenIds
196
+ Set the token ids to disable in the completion
197
+ stopStrings
198
+ Set strings upon seeing which token generation is stopped
199
+ samplers
200
+ Set which samplers to use for token generation in the given order
201
+ useChatTemplate
202
+ Set whether or not generate should apply a chat template
203
+
204
+ Notes
205
+ -----
206
+ This annotator is designed for reranking tasks and requires setting a query using ``setQuery``.
207
+ The query represents the search intent against which documents will be ranked. Each input
208
+ document receives a relevance score in the output metadata.
209
+
210
+ To use GPU inference with this annotator, make sure to use the Spark NLP GPU package and set
211
+ the number of GPU layers with the `setNGpuLayers` method.
212
+
213
+ When using larger models, we recommend adjusting GPU usage with `setNCtx` and `setNGpuLayers`
214
+ according to your hardware to avoid out-of-memory errors.
215
+
216
+ Examples
217
+ --------
218
+ >>> import sparknlp
219
+ >>> from sparknlp.base import *
220
+ >>> from sparknlp.annotator import *
221
+ >>> from pyspark.ml import Pipeline
222
+ >>> document = DocumentAssembler() \\
223
+ ... .setInputCol("text") \\
224
+ ... .setOutputCol("document")
225
+ >>> reranker = AutoGGUFReranker.pretrained("bge-reranker-v2-m3-Q4_K_M") \\
226
+ ... .setInputCols(["document"]) \\
227
+ ... .setOutputCol("reranked_documents") \\
228
+ ... .setBatchSize(4) \\
229
+ ... .setQuery("A man is eating pasta.")
230
+ >>> pipeline = Pipeline().setStages([document, reranker])
231
+ >>> data = spark.createDataFrame([
232
+ ... ["A man is eating food."],
233
+ ... ["A man is eating a piece of bread."],
234
+ ... ["The girl is carrying a baby."],
235
+ ... ["A man is riding a horse."]
236
+ ... ]).toDF("text")
237
+ >>> result = pipeline.fit(data).transform(data)
238
+ >>> result.select("reranked_documents").show(truncate = False)
239
+ # Each document will have a relevance_score in metadata showing how relevant it is to the query
240
+ """
241
+
242
+ name = "AutoGGUFReranker"
243
+ inputAnnotatorTypes = [AnnotatorType.DOCUMENT]
244
+ outputAnnotatorType = AnnotatorType.DOCUMENT
245
+
246
+ query = Param(Params._dummy(), "query",
247
+ "The query to be used for reranking. If not set, the input text will be used as the query.",
248
+ typeConverter=TypeConverters.toString)
249
+ @keyword_only
250
+ def __init__(self, classname="com.johnsnowlabs.nlp.annotators.seq2seq.AutoGGUFReranker", java_model=None):
251
+ super(AutoGGUFReranker, self).__init__(
252
+ classname=classname,
253
+ java_model=java_model
254
+ )
255
+ self._setDefault(
256
+ useChatTemplate=True,
257
+ nCtx=4096,
258
+ nBatch=512,
259
+ nGpuLayers=99,
260
+ systemPrompt="You are a helpful assistant.",
261
+ query=""
262
+ )
263
+
264
+ def setQuery(self, value: str):
265
+ """Set the query to be used for reranking.
266
+
267
+ Parameters
268
+ ----------
269
+ value : str
270
+ The query text that documents will be ranked against.
271
+
272
+ Returns
273
+ -------
274
+ AutoGGUFReranker
275
+ This instance for method chaining.
276
+ """
277
+ return self._set(query=value)
278
+
279
+ def getQuery(self):
280
+ """Get the current query used for reranking.
281
+
282
+ Returns
283
+ -------
284
+ str
285
+ The current query string.
286
+ """
287
+ return self._call_java("getQuery")
288
+
289
+ @staticmethod
290
+ def loadSavedModel(folder, spark_session):
291
+ """Loads a locally saved model.
292
+
293
+ Parameters
294
+ ----------
295
+ folder : str
296
+ Folder of the saved model
297
+ spark_session : pyspark.sql.SparkSession
298
+ The current SparkSession
299
+
300
+ Returns
301
+ -------
302
+ AutoGGUFReranker
303
+ The restored model
304
+ """
305
+ from sparknlp.internal import _AutoGGUFRerankerLoader
306
+ jModel = _AutoGGUFRerankerLoader(folder, spark_session._jsparkSession)._java_obj
307
+ return AutoGGUFReranker(java_model=jModel)
308
+
309
+ @staticmethod
310
+ def pretrained(name="bge-reranker-v2-m3-Q4_K_M", lang="en", remote_loc=None):
311
+ """Downloads and loads a pretrained model.
312
+
313
+ Parameters
314
+ ----------
315
+ name : str, optional
316
+ Name of the pretrained model, by default "bge-reranker-v2-m3-Q4_K_M"
317
+ lang : str, optional
318
+ Language of the pretrained model, by default "en"
319
+ remote_loc : str, optional
320
+ Optional remote address of the resource, by default None. Will use
321
+ Spark NLPs repositories otherwise.
322
+
323
+ Returns
324
+ -------
325
+ AutoGGUFReranker
326
+ The restored model
327
+ """
328
+ from sparknlp.pretrained import ResourceDownloader
329
+ return ResourceDownloader.downloadModel(AutoGGUFReranker, name, lang, remote_loc)
@@ -0,0 +1,76 @@
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 Token2Chunk."""
15
+
16
+
17
+ from sparknlp.common import *
18
+
19
+
20
+ class Token2Chunk(AnnotatorModel):
21
+ """Converts ``TOKEN`` type Annotations to ``CHUNK`` type.
22
+
23
+ This can be useful if a entities have been already extracted as ``TOKEN``
24
+ and following annotators require ``CHUNK`` types.
25
+
26
+ ====================== ======================
27
+ Input Annotation types Output Annotation type
28
+ ====================== ======================
29
+ ``TOKEN`` ``CHUNK``
30
+ ====================== ======================
31
+
32
+ Parameters
33
+ ----------
34
+ None
35
+
36
+ Examples
37
+ --------
38
+ >>> import sparknlp
39
+ >>> from sparknlp.base import *
40
+ >>> from sparknlp.annotator import *
41
+ >>> from pyspark.ml import Pipeline
42
+ >>> documentAssembler = DocumentAssembler() \\
43
+ ... .setInputCol("text") \\
44
+ ... .setOutputCol("document")
45
+ >>> tokenizer = Tokenizer() \\
46
+ ... .setInputCols(["document"]) \\
47
+ ... .setOutputCol("token")
48
+ >>> token2chunk = Token2Chunk() \\
49
+ ... .setInputCols(["token"]) \\
50
+ ... .setOutputCol("chunk")
51
+ >>> pipeline = Pipeline().setStages([
52
+ ... documentAssembler,
53
+ ... tokenizer,
54
+ ... token2chunk
55
+ ... ])
56
+ >>> data = spark.createDataFrame([["One Two Three Four"]]).toDF("text")
57
+ >>> result = pipeline.fit(data).transform(data)
58
+ >>> result.selectExpr("explode(chunk) as result").show(truncate=False)
59
+ +------------------------------------------+
60
+ |result |
61
+ +------------------------------------------+
62
+ |[chunk, 0, 2, One, [sentence -> 0], []] |
63
+ |[chunk, 4, 6, Two, [sentence -> 0], []] |
64
+ |[chunk, 8, 12, Three, [sentence -> 0], []]|
65
+ |[chunk, 14, 17, Four, [sentence -> 0], []]|
66
+ +------------------------------------------+
67
+ """
68
+ name = "Token2Chunk"
69
+
70
+ inputAnnotatorTypes = [AnnotatorType.TOKEN]
71
+
72
+ outputAnnotatorType = AnnotatorType.CHUNK
73
+
74
+ def __init__(self):
75
+ super(Token2Chunk, self).__init__(classname="com.johnsnowlabs.nlp.annotators.Token2Chunk")
76
+
@@ -1191,4 +1191,9 @@ class _Phi4Loader(ExtendedJavaWrapper):
1191
1191
  path,
1192
1192
  jspark,
1193
1193
  use_openvino,
1194
- )
1194
+ )
1195
+
1196
+ class _AutoGGUFRerankerLoader(ExtendedJavaWrapper):
1197
+ def __init__(self, path, jspark):
1198
+ super(_AutoGGUFRerankerLoader, self).__init__(
1199
+ "com.johnsnowlabs.nlp.annotators.seq2seq.AutoGGUFReranker.loadSavedModel", path, jspark)
@@ -0,0 +1,110 @@
1
+ # Copyright 2017-2025 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
+ from pyspark import keyword_only
15
+ from pyspark.ml.param import TypeConverters, Params, Param
16
+
17
+ from sparknlp.common import AnnotatorType
18
+ from sparknlp.internal import AnnotatorTransformer
19
+ from sparknlp.partition.partition_properties import *
20
+
21
+ class Reader2Image(
22
+ AnnotatorTransformer,
23
+ HasHTMLReaderProperties
24
+ ):
25
+ name = "Reader2Image"
26
+ outputAnnotatorType = AnnotatorType.IMAGE
27
+
28
+ contentPath = Param(
29
+ Params._dummy(),
30
+ "contentPath",
31
+ "contentPath path to files to read",
32
+ typeConverter=TypeConverters.toString
33
+ )
34
+
35
+ outputCol = Param(
36
+ Params._dummy(),
37
+ "outputCol",
38
+ "output column name",
39
+ typeConverter=TypeConverters.toString
40
+ )
41
+
42
+ contentType = Param(
43
+ Params._dummy(),
44
+ "contentType",
45
+ "Set the content type to load following MIME specification",
46
+ typeConverter=TypeConverters.toString
47
+ )
48
+
49
+ explodeDocs = Param(
50
+ Params._dummy(),
51
+ "explodeDocs",
52
+ "whether to explode the documents into separate rows",
53
+ typeConverter=TypeConverters.toBoolean
54
+ )
55
+
56
+ @keyword_only
57
+ def __init__(self):
58
+ super(Reader2Image, self).__init__(classname="com.johnsnowlabs.reader.Reader2Image")
59
+ self._setDefault(
60
+ outputCol="document",
61
+ explodeDocs=True,
62
+ contentType=""
63
+ )
64
+
65
+ @keyword_only
66
+ def setParams(self):
67
+ kwargs = self._input_kwargs
68
+ return self._set(**kwargs)
69
+
70
+ def setContentPath(self, value):
71
+ """Sets content path.
72
+
73
+ Parameters
74
+ ----------
75
+ value : str
76
+ contentPath path to files to read
77
+ """
78
+ return self._set(contentPath=value)
79
+
80
+ def setContentType(self, value):
81
+ """
82
+ Set the content type to load following MIME specification
83
+
84
+ Parameters
85
+ ----------
86
+ value : str
87
+ content type to load following MIME specification
88
+ """
89
+ return self._set(contentType=value)
90
+
91
+ def setExplodeDocs(self, value):
92
+ """Sets whether to explode the documents into separate rows.
93
+
94
+
95
+ Parameters
96
+ ----------
97
+ value : boolean
98
+ Whether to explode the documents into separate rows
99
+ """
100
+ return self._set(explodeDocs=value)
101
+
102
+ def setOutputCol(self, value):
103
+ """Sets output column name.
104
+
105
+ Parameters
106
+ ----------
107
+ value : str
108
+ Name of the Output Column
109
+ """
110
+ return self._set(outputCol=value)