# Copyright 2017-2026 John Snow Labs
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes for ModernBertForTokenClassification."""
from sparknlp.common import *
[docs]class ModernBertForTokenClassification(AnnotatorModel,
HasCaseSensitiveProperties,
HasBatchedAnnotate,
HasEngine):
"""ModernBertForTokenClassification can load ModernBERT Models with a token
classification head on top (a linear layer on top of the hidden-states
output) e.g. for Named-Entity-Recognition (NER) tasks.
Models are imported with :meth:`.loadSavedModel` from a HuggingFace
``ModernBertForTokenClassification`` that was exported to ONNX. The folder
has to contain the exported ``model.onnx`` and an ``assets`` folder with the
``tokenizer.json`` of the model and a ``labels.txt`` (one label per line, in
the order of the ids of the model):
>>> token_classifier = ModernBertForTokenClassification.loadSavedModel("/path/to/export", spark) \\
... .setInputCols(["token", "document"]) \\
... .setOutputCol("label")
Every token is encoded on its own with a leading space, the way the
HuggingFace tokenizer encodes pre-tokenized input
(``is_split_into_words=True``, ``add_prefix_space=True``). The label of a
token is the label predicted for its first sub-token.
The annotator tags the tokens of its ``token`` column, usually the ones of
the Spark NLP ``Tokenizer``, and sends every sentence of its ``document``
column to the model on its own. Its tags can therefore differ from those of
a HuggingFace pipeline for the same text, which splits the words in another
way or sees the whole document at once.
For available pretrained models please see the `Models Hub
<https://sparknlp.org/models?task=Named+Entity+Recognition>`__.
To see which models are compatible and how to import them see
`Import Transformers into Spark NLP 🚀
<https://github.com/JohnSnowLabs/spark-nlp/discussions/5669>`_.
====================== ======================
Input Annotation types Output Annotation type
====================== ======================
``DOCUMENT, TOKEN`` ``NAMED_ENTITY``
====================== ======================
Parameters
----------
batchSize
Batch size. Large values allows faster processing but requires more
memory, by default 8
caseSensitive
Whether to ignore case in tokens for embeddings matching, by default
True
maxSentenceLength
Max sentence length to process, by default 512
Notes
-----
The annotator does not split long inputs into several windows. The
sub-tokens of a sentence (or of the document, if no sentence detector is
used) that exceed ``maxSentenceLength`` are truncated and their tokens do
not get a label, like in the other token classification annotators. For long
documents use a sentence detector or another way of splitting the text
upstream.
Examples
--------
>>> import sparknlp
>>> from sparknlp.base import *
>>> from sparknlp.annotator import *
>>> from pyspark.ml import Pipeline
>>> documentAssembler = DocumentAssembler() \\
... .setInputCol("text") \\
... .setOutputCol("document")
>>> tokenizer = Tokenizer() \\
... .setInputCols(["document"]) \\
... .setOutputCol("token")
>>> tokenClassifier = ModernBertForTokenClassification.loadSavedModel("/path/to/export", spark) \\
... .setInputCols(["token", "document"]) \\
... .setOutputCol("label") \\
... .setCaseSensitive(True)
>>> pipeline = Pipeline().setStages([
... documentAssembler,
... tokenizer,
... tokenClassifier
... ])
>>> data = spark.createDataFrame([["John Lenon was born in London and lived in Paris. My name is Sarah and I live in London"]]).toDF("text")
>>> result = pipeline.fit(data).transform(data)
>>> result.select("label.result").show(truncate=False)
+------------------------------------------------------------------------------------+
|result |
+------------------------------------------------------------------------------------+
|[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]|
+------------------------------------------------------------------------------------+
"""
[docs] name = "ModernBertForTokenClassification"
[docs] outputAnnotatorType = AnnotatorType.NAMED_ENTITY
[docs] maxSentenceLength = Param(Params._dummy(),
"maxSentenceLength",
"Max sentence length to process",
typeConverter=TypeConverters.toInt)
[docs] def getClasses(self):
"""
Returns labels used to train this model
"""
return self._call_java("getClasses")
[docs] def setMaxSentenceLength(self, value):
"""Sets max sentence length to process, by default 512.
Parameters
----------
value : int
Max sentence length to process
"""
return self._set(maxSentenceLength=value)
@keyword_only
def __init__(self, classname="com.johnsnowlabs.nlp.annotators.classifier.dl.ModernBertForTokenClassification",
java_model=None):
super(ModernBertForTokenClassification, self).__init__(
classname=classname,
java_model=java_model
)
self._setDefault(
batchSize=8,
maxSentenceLength=512,
caseSensitive=True
)
@staticmethod
[docs] def loadSavedModel(folder, spark_session, use_openvino=False):
"""Loads a locally saved model.
Parameters
----------
folder : str
Folder of the saved model
spark_session : pyspark.sql.SparkSession
The current SparkSession
use_openvino : bool, optional
Whether to use the OpenVINO engine, by default False
Returns
-------
ModernBertForTokenClassification
The restored model
"""
from sparknlp.internal import _ModernBertForTokenClassifierLoader
jModel = _ModernBertForTokenClassifierLoader(folder, spark_session._jsparkSession, use_openvino)._java_obj
return ModernBertForTokenClassification(java_model=jModel)
@staticmethod
[docs] def pretrained(name="modernbert_base_token_classifier", lang="en", remote_loc=None):
"""Downloads and loads a pretrained model.
Parameters
----------
name : str, optional
Name of the pretrained model, by default
"modernbert_base_token_classifier"
lang : str, optional
Language of the pretrained model, by default "en"
remote_loc : str, optional
Optional remote address of the resource, by default None. Will use
Spark NLPs repositories otherwise.
Returns
-------
ModernBertForTokenClassification
The restored model
"""
from sparknlp.pretrained import ResourceDownloader
return ResourceDownloader.downloadModel(ModernBertForTokenClassification, name, lang, remote_loc)