sparknlp.annotator.cv.janus_for_multimodal#

Module Contents#

Classes#

JanusForMultiModal

JanusForMultiModal can load Janus Vision models for visual question answering.

class JanusForMultiModal(classname='com.johnsnowlabs.nlp.annotators.cv.JanusForMultiModal', java_model=None)[source]#

JanusForMultiModal can load Janus Vision models for visual question answering. The model consists of a vision encoder, a text encoder, and a text decoder. The vision encoder encodes the input image, the text encoder processes the input question alongside the image encoding, and the text decoder generates the answer to the question.

Janus is a novel autoregressive framework that unifies multimodal understanding and generation. It decouples visual encoding into separate pathways while utilizing a single, unified transformer architecture for processing. This decoupling alleviates conflicts between the visual encoder’s roles in understanding and generation, enhancing the framework’s flexibility.

Janus surpasses previous unified models and matches or exceeds the performance of task-specific models. It uses the DeepSeek-LLM-1.3b-base trained on approximately 500B text tokens. For multimodal understanding, it employs the SigLIP-L vision encoder supporting 384 x 384 image input, and for image generation, it uses a tokenizer with a downsample rate of 16.

Pretrained models can be loaded with pretrained() of the companion object:

>>> visualQAClassifier = JanusForMultiModal.pretrained() \
...     .setInputCols(["image_assembler"]) \
...     .setOutputCol("answer")

The default model is β€œjanus_1_3b_int4”, if no name is provided. For available pretrained models, refer to the Models Hub.

Models from the HuggingFace 🧧 Transformers library are also compatible with Spark NLP πŸš€. To check compatibility and learn how to import them, see Import Transformers into Spark NLP πŸš€. For extended examples, refer to the JanusForMultiModal Test Suite.

Input Annotation types

Output Annotation type

IMAGE

DOCUMENT

Parameters:
batchSizeint, optional

Batch size. Larger values allow faster processing but require more memory, by default 2.

configProtoBytesbytes, optional

ConfigProto from TensorFlow, serialized into a byte array.

maxSentenceLengthint, optional

Maximum sentence length to process, by default 50.

Examples

>>> import sparknlp
>>> from sparknlp.base import *
>>> from sparknlp.annotator import *
>>> from pyspark.ml import Pipeline
>>> from pyspark.sql.functions import lit
>>> image_df = SparkSessionForTest.spark.read.format("image").load(path=images_path)
>>> test_df = image_df.withColumn(
...     "text",
...     lit("User: <image_placeholder>Describe image in details\n\nAssistant:")
... )
>>> imageAssembler = ImageAssembler() \
...     .setInputCol("image") \
...     .setOutputCol("image_assembler")
>>> visualQAClassifier = JanusForMultiModal.pretrained() \
...     .setInputCols("image_assembler") \
...     .setOutputCol("answer")
>>> pipeline = Pipeline().setStages([
...     imageAssembler,
...     visualQAClassifier
... ])
>>> result = pipeline.fit(test_df).transform(test_df)
>>> result.select("image_assembler.origin", "answer.result").show(truncate=False)
+--------------------------------------+----------------------------------------------------------------------+
|origin                                |result                                                                |
+--------------------------------------+----------------------------------------------------------------------+
|[file:///content/images/cat_image.jpg]|[The unusual aspect of this picture is the presence of two cats lying on a pink couch]|
+--------------------------------------+----------------------------------------------------------------------+
name = 'JanusForMultiModal'[source]#
inputAnnotatorTypes[source]#
outputAnnotatorType = 'document'[source]#
configProtoBytes[source]#
minOutputLength[source]#
maxOutputLength[source]#
doSample[source]#
temperature[source]#
topK[source]#
topP[source]#
repetitionPenalty[source]#
noRepeatNgramSize[source]#
ignoreTokenIds[source]#
beamSize[source]#
imageGenerateMode[source]#
numOfParallelImages[source]#
setMaxSentenceSize(value)[source]#

Sets Maximum sentence length that the annotator will process, by default 50. Parameters β€”β€”β€”- value : int

Maximum sentence length that the annotator will process

setIgnoreTokenIds(value)[source]#

A list of token ids which are ignored in the decoder’s output. Parameters β€”β€”β€”- value : List[int]

The words to be filtered out

setConfigProtoBytes(b)[source]#

Sets configProto from tensorflow, serialized into byte array. Parameters β€”β€”β€”- b : List[int]

ConfigProto from tensorflow, serialized into byte array

setMinOutputLength(value)[source]#

Sets minimum length of the sequence to be generated. Parameters β€”β€”β€”- value : int

Minimum length of the sequence to be generated

setMaxOutputLength(value)[source]#

Sets maximum length of output text. Parameters β€”β€”β€”- value : int

Maximum length of output text

setDoSample(value)[source]#

Sets whether or not to use sampling, use greedy decoding otherwise. Parameters β€”β€”β€”- value : bool

Whether or not to use sampling; use greedy decoding otherwise

setTemperature(value)[source]#

Sets the value used to module the next token probabilities. Parameters β€”β€”β€”- value : float

The value used to module the next token probabilities

setTopK(value)[source]#

Sets the number of highest probability vocabulary tokens to keep for top-k-filtering. Parameters β€”β€”β€”- value : int

Number of highest probability vocabulary tokens to keep

setTopP(value)[source]#

Sets the top cumulative probability for vocabulary tokens. If set to float < 1, only the most probable tokens with probabilities that add up to topP or higher are kept for generation. Parameters β€”β€”β€”- value : float

Cumulative probability for vocabulary tokens

setRepetitionPenalty(value)[source]#

Sets the parameter for repetition penalty. 1.0 means no penalty. Parameters β€”β€”β€”- value : float

The repetition penalty

References#

See Ctrl: A Conditional Transformer Language Model For Controllable Generation for more details.

setNoRepeatNgramSize(value)[source]#

Sets size of n-grams that can only occur once. If set to int > 0, all ngrams of that size can only occur once. Parameters β€”β€”β€”- value : int

N-gram size can only occur once

setBeamSize(value)[source]#

Sets the number of beam size for beam search, by default 4. Parameters β€”β€”β€”- value : int

Number of beam size for beam search

setImageGenerateMode(value)[source]#

Sets the image generation mode. Parameters β€”β€”β€”- value : bool

Image generation mode

setNumOfParallelImages(value)[source]#

Sets the number of parallel images to generate. Parameters β€”β€”β€”- value : int

Number of parallel images to generate

static loadSavedModel(folder, spark_session, use_openvino=False)[source]#

Loads a locally saved model. Parameters β€”β€”β€”- folder : str

Folder of the saved model

spark_sessionpyspark.sql.SparkSession

The current SparkSession

Returns#

CLIPForZeroShotClassification

The restored model

static pretrained(name='janus_1_3b_int4', lang='en', remote_loc=None)[source]#

Downloads and loads a pretrained model. Parameters β€”β€”β€”- name : str, optional

Name of the pretrained model, by default β€œjanus_1_3b_int4”

langstr, optional

Language of the pretrained model, by default β€œen”

remote_locstr, optional

Optional remote address of the resource, by default None. Will use Spark NLPs repositories otherwise.

Returns#

CLIPForZeroShotClassification

The restored model