Packages

class UAEEmbeddings extends AnnotatorModel[UAEEmbeddings] with HasBatchedAnnotate[UAEEmbeddings] with WriteTensorflowModel with WriteOnnxModel with WriteOpenvinoModel with HasEmbeddingsProperties with HasStorageRef with HasCaseSensitiveProperties with HasEngine

Sentence embeddings using Universal AnglE Embedding (UAE).

UAE is a novel angle-optimized text embedding model, designed to improve semantic textual similarity tasks, which are crucial for Large Language Model (LLM) applications. By introducing angle optimization in a complex space, AnglE effectively mitigates saturation of the cosine similarity function.

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

val embeddings = UAEEmbeddings.pretrained()
  .setInputCols("document")
  .setOutputCol("UAE_embeddings")

The default model is "uae_large_v1", if no name is provided.

For available pretrained models please see the Models Hub.

For extended examples of usage, see UAEEmbeddingsTestSpec.

Sources :

AnglE-optimized Text Embeddings

UAE Github Repository

Paper abstract

High-quality text embedding is pivotal in improving semantic textual similarity (STS) tasks, which are crucial components in Large Language Model (LLM) applications. However, a common challenge existing text embedding models face is the problem of vanishing gradients, primarily due to their reliance on the cosine function in the optimization objective, which has saturation zones. To address this issue, this paper proposes a novel angle-optimized text embedding model called AnglE. The core idea of AnglE is to introduce angle optimization in a complex space. This novel approach effectively mitigates the adverse effects of the saturation zone in the cosine function, which can impede gradient and hinder optimization processes. To set up a comprehensive STS evaluation, we experimented on existing short-text STS datasets and a newly collected long-text STS dataset from GitHub Issues. Furthermore, we examine domain-specific STS scenarios with limited labeled data and explore how AnglE works with LLM-annotated data. Extensive experiments were conducted on various tasks including short-text STS, long-text STS, and domain-specific STS tasks. The results show that AnglE outperforms the state-of-the-art (SOTA) STS models that ignore the cosine saturation zone. These findings demonstrate the ability of AnglE to generate high-quality text embeddings and the usefulness of angle optimization in STS.

Example

import spark.implicits._
import com.johnsnowlabs.nlp.base.DocumentAssembler
import com.johnsnowlabs.nlp.annotators.Tokenizer
import com.johnsnowlabs.nlp.embeddings.UAEEmbeddings
import com.johnsnowlabs.nlp.EmbeddingsFinisher
import org.apache.spark.ml.Pipeline

val documentAssembler = new DocumentAssembler()
  .setInputCol("text")
  .setOutputCol("document")

val embeddings = UAEEmbeddings.pretrained()
  .setInputCols("document")
  .setOutputCol("UAE_embeddings")

val embeddingsFinisher = new EmbeddingsFinisher()
  .setInputCols("UAE_embeddings")
  .setOutputCols("finished_embeddings")
  .setOutputAsVector(true)

val pipeline = new Pipeline().setStages(Array(
  documentAssembler,
  embeddings,
  embeddingsFinisher
))

val data = Seq("hello world", "hello moon").toDF("text")
val result = pipeline.fit(data).transform(data)

result.selectExpr("explode(finished_embeddings) as result").show(5, 80)
+--------------------------------------------------------------------------------+
|                                                                          result|
+--------------------------------------------------------------------------------+
|[0.50387806, 0.5861606, 0.35129607, -0.76046336, -0.32446072, -0.117674336, 0...|
|[0.6660665, 0.961762, 0.24854276, -0.1018044, -0.6569202, 0.027635604, 0.1915...|
+--------------------------------------------------------------------------------+
See also

Annotators Main Page for a list of transformer based embeddings

Ordering
  1. Grouped
  2. Alphabetic
  3. By Inheritance
Inherited
  1. UAEEmbeddings
  2. HasEngine
  3. HasCaseSensitiveProperties
  4. HasStorageRef
  5. HasEmbeddingsProperties
  6. HasProtectedParams
  7. WriteOpenvinoModel
  8. WriteOnnxModel
  9. WriteTensorflowModel
  10. HasBatchedAnnotate
  11. AnnotatorModel
  12. CanBeLazy
  13. RawAnnotator
  14. HasOutputAnnotationCol
  15. HasInputAnnotationCols
  16. HasOutputAnnotatorType
  17. ParamsAndFeaturesWritable
  18. HasFeatures
  19. DefaultParamsWritable
  20. MLWritable
  21. Model
  22. Transformer
  23. PipelineStage
  24. Logging
  25. Params
  26. Serializable
  27. Serializable
  28. Identifiable
  29. AnyRef
  30. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Parameters

A list of (hyper-)parameter keys this annotator can take. Users can set and get the parameter values through setters and getters, respectively.

  1. val batchSize: IntParam

    Size of every batch (Default depends on model).

    Size of every batch (Default depends on model).

    Definition Classes
    HasBatchedAnnotate
  2. val caseSensitive: BooleanParam

    Whether to ignore case in index lookups (Default depends on model)

    Whether to ignore case in index lookups (Default depends on model)

    Definition Classes
    HasCaseSensitiveProperties
  3. val configProtoBytes: IntArrayParam

    ConfigProto from tensorflow, serialized into byte array.

    ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()

  4. val dimension: ProtectedParam[Int]

    Number of embedding dimensions (Default depends on model)

    Number of embedding dimensions (Default depends on model)

    Definition Classes
    HasEmbeddingsProperties
  5. val engine: Param[String]

    This param is set internally once via loadSavedModel.

    This param is set internally once via loadSavedModel. That's why there is no setter

    Definition Classes
    HasEngine
  6. val maxSentenceLength: IntParam

    Max sentence length to process (Default: 128)

  7. val poolingStrategy: Param[String]

    Pooling strategy to use for sentence embeddings.

    Pooling strategy to use for sentence embeddings.

    Available pooling strategies for sentence embeddings are:

    • "cls": leading [CLS] token
    • "cls_avg": leading [CLS] token + mean of all other tokens
    • "last": embeddings of the last token in the sequence
    • "avg": mean of all tokens
    • "max": max of all embedding values for the token sequence
    • "all": return all token embeddings
    • "int": An integer number, which represents the index of the token to use as the embedding
  8. val signatures: MapFeature[String, String]

    It contains TF model signatures for the laded saved model

  9. val storageRef: Param[String]

    Unique identifier for storage (Default: this.uid)

    Unique identifier for storage (Default: this.uid)

    Definition Classes
    HasStorageRef
  10. val vocabulary: MapFeature[String, Int]

    Vocabulary used to encode the words to ids with WordPieceEncoder

Members

  1. implicit class ProtectedParam[T] extends Param[T]
    Definition Classes
    HasProtectedParams
  2. type AnnotatorType = String
    Definition Classes
    HasOutputAnnotatorType
  1. def batchAnnotate(batchedAnnotations: Seq[Array[Annotation]]): Seq[Seq[Annotation]]

    takes a document and annotations and produces new annotations of this annotator's annotation type

    takes a document and annotations and produces new annotations of this annotator's annotation type

    batchedAnnotations

    Annotations that correspond to inputAnnotationCols generated by previous annotators if any

    returns

    any number of annotations processed for every input annotation. Not necessary one to one relationship

    Definition Classes
    UAEEmbeddingsHasBatchedAnnotate
  2. def batchProcess(rows: Iterator[_]): Iterator[Row]
    Definition Classes
    HasBatchedAnnotate
  3. final def clear(param: Param[_]): UAEEmbeddings.this.type
    Definition Classes
    Params
  4. def copy(extra: ParamMap): UAEEmbeddings

    requirement for annotators copies

    requirement for annotators copies

    Definition Classes
    RawAnnotator → Model → Transformer → PipelineStage → Params
  5. def createDatabaseConnection(database: Name): RocksDBConnection
    Definition Classes
    HasStorageRef
  6. def explainParam(param: Param[_]): String
    Definition Classes
    Params
  7. def explainParams(): String
    Definition Classes
    Params
  8. final def extractParamMap(): ParamMap
    Definition Classes
    Params
  9. final def extractParamMap(extra: ParamMap): ParamMap
    Definition Classes
    Params
  10. val features: ArrayBuffer[Feature[_, _, _]]
    Definition Classes
    HasFeatures
  11. final def get[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  12. final def getDefault[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  13. def getInputCols: Array[String]

    returns

    input annotations columns currently used

    Definition Classes
    HasInputAnnotationCols
  14. def getLazyAnnotator: Boolean
    Definition Classes
    CanBeLazy
  15. final def getOrDefault[T](param: Param[T]): T
    Definition Classes
    Params
  16. final def getOutputCol: String

    Gets annotation column name going to generate

    Gets annotation column name going to generate

    Definition Classes
    HasOutputAnnotationCol
  17. def getParam(paramName: String): Param[Any]
    Definition Classes
    Params
  18. def getPoolingStrategy: String
  19. def getStorageRef: String
    Definition Classes
    HasStorageRef
  20. final def hasDefault[T](param: Param[T]): Boolean
    Definition Classes
    Params
  21. def hasParam(paramName: String): Boolean
    Definition Classes
    Params
  22. def hasParent: Boolean
    Definition Classes
    Model
  23. val inputAnnotatorTypes: Array[String]

    Annotator reference id.

    Annotator reference id. Used to identify elements in metadata or to refer to this annotator type

    Definition Classes
    UAEEmbeddingsHasInputAnnotationCols
  24. final def isDefined(param: Param[_]): Boolean
    Definition Classes
    Params
  25. final def isSet(param: Param[_]): Boolean
    Definition Classes
    Params
  26. val lazyAnnotator: BooleanParam
    Definition Classes
    CanBeLazy
  27. def onWrite(path: String, spark: SparkSession): Unit
  28. val optionalInputAnnotatorTypes: Array[String]
    Definition Classes
    HasInputAnnotationCols
  29. val outputAnnotatorType: AnnotatorType
    Definition Classes
    UAEEmbeddingsHasOutputAnnotatorType
  30. lazy val params: Array[Param[_]]
    Definition Classes
    Params
  31. var parent: Estimator[UAEEmbeddings]
    Definition Classes
    Model
  32. def save(path: String): Unit
    Definition Classes
    MLWritable
    Annotations
    @Since( "1.6.0" ) @throws( ... )
  33. def sentenceStartTokenId: Int
  34. def set[T](param: ProtectedParam[T], value: T): UAEEmbeddings.this.type

    Sets the value for a protected Param.

    Sets the value for a protected Param.

    If the parameter was already set, it will not be set again. Default values do not count as a set value and can be overridden.

    T

    Type of the parameter

    param

    Protected parameter to set

    value

    Value for the parameter

    returns

    This object

    Definition Classes
    HasProtectedParams
  35. final def set[T](param: Param[T], value: T): UAEEmbeddings.this.type
    Definition Classes
    Params
  36. final def setInputCols(value: String*): UAEEmbeddings.this.type
    Definition Classes
    HasInputAnnotationCols
  37. def setInputCols(value: Array[String]): UAEEmbeddings.this.type

    Overrides required annotators column if different than default

    Overrides required annotators column if different than default

    Definition Classes
    HasInputAnnotationCols
  38. def setLazyAnnotator(value: Boolean): UAEEmbeddings.this.type
    Definition Classes
    CanBeLazy
  39. final def setOutputCol(value: String): UAEEmbeddings.this.type

    Overrides annotation column name when transforming

    Overrides annotation column name when transforming

    Definition Classes
    HasOutputAnnotationCol
  40. def setParent(parent: Estimator[UAEEmbeddings]): UAEEmbeddings
    Definition Classes
    Model
  41. def setStorageRef(value: String): UAEEmbeddings.this.type
    Definition Classes
    HasStorageRef
  42. def toString(): String
    Definition Classes
    Identifiable → AnyRef → Any
  43. def tokenize(sentences: Seq[Annotation]): Seq[WordpieceTokenizedSentence]
  44. final def transform(dataset: Dataset[_]): DataFrame

    Given requirements are met, this applies ML transformation within a Pipeline or stand-alone Output annotation will be generated as a new column, previous annotations are still available separately metadata is built at schema level to record annotations structural information outside its content

    Given requirements are met, this applies ML transformation within a Pipeline or stand-alone Output annotation will be generated as a new column, previous annotations are still available separately metadata is built at schema level to record annotations structural information outside its content

    dataset

    Dataset[Row]

    Definition Classes
    AnnotatorModel → Transformer
  45. def transform(dataset: Dataset[_], paramMap: ParamMap): DataFrame
    Definition Classes
    Transformer
    Annotations
    @Since( "2.0.0" )
  46. def transform(dataset: Dataset[_], firstParamPair: ParamPair[_], otherParamPairs: ParamPair[_]*): DataFrame
    Definition Classes
    Transformer
    Annotations
    @Since( "2.0.0" ) @varargs()
  47. final def transformSchema(schema: StructType): StructType

    requirement for pipeline transformation validation.

    requirement for pipeline transformation validation. It is called on fit()

    Definition Classes
    RawAnnotator → PipelineStage
  48. val uid: String
    Definition Classes
    UAEEmbeddings → Identifiable
  49. def validateStorageRef(dataset: Dataset[_], inputCols: Array[String], annotatorType: String): Unit
    Definition Classes
    HasStorageRef
  50. def write: MLWriter
    Definition Classes
    ParamsAndFeaturesWritable → DefaultParamsWritable → MLWritable
  51. def writeOnnxModel(path: String, spark: SparkSession, onnxWrapper: OnnxWrapper, suffix: String, fileName: String): Unit
    Definition Classes
    WriteOnnxModel
  52. def writeOnnxModels(path: String, spark: SparkSession, onnxWrappersWithNames: Seq[(OnnxWrapper, String)], suffix: String): Unit
    Definition Classes
    WriteOnnxModel
  53. def writeOpenvinoModel(path: String, spark: SparkSession, openvinoWrapper: OpenvinoWrapper, suffix: String, fileName: String): Unit
    Definition Classes
    WriteOpenvinoModel
  54. def writeOpenvinoModels(path: String, spark: SparkSession, ovWrappersWithNames: Seq[(OpenvinoWrapper, String)], suffix: String): Unit
    Definition Classes
    WriteOpenvinoModel
  55. def writeTensorflowHub(path: String, tfPath: String, spark: SparkSession, suffix: String = "_use"): Unit
    Definition Classes
    WriteTensorflowModel
  56. def writeTensorflowModel(path: String, spark: SparkSession, tensorflow: TensorflowWrapper, suffix: String, filename: String, configProtoBytes: Option[Array[Byte]] = None): Unit
    Definition Classes
    WriteTensorflowModel
  57. def writeTensorflowModelV2(path: String, spark: SparkSession, tensorflow: TensorflowWrapper, suffix: String, filename: String, configProtoBytes: Option[Array[Byte]] = None, savedSignatures: Option[Map[String, String]] = None): Unit
    Definition Classes
    WriteTensorflowModel

Parameter setters

  1. def sentenceEndTokenId: Int

  2. def setBatchSize(size: Int): UAEEmbeddings.this.type

    Size of every batch.

    Size of every batch.

    Definition Classes
    HasBatchedAnnotate
  3. def setCaseSensitive(value: Boolean): UAEEmbeddings.this.type

    Whether to lowercase tokens or not

    Whether to lowercase tokens or not

    Definition Classes
    UAEEmbeddingsHasCaseSensitiveProperties
  4. def setConfigProtoBytes(bytes: Array[Int]): UAEEmbeddings.this.type

  5. def setDimension(value: Int): UAEEmbeddings.this.type

    Set Embeddings dimensions for the BERT model Only possible to set this when the first time is saved dimension is not changeable, it comes from BERT config file

    Set Embeddings dimensions for the BERT model Only possible to set this when the first time is saved dimension is not changeable, it comes from BERT config file

    Definition Classes
    UAEEmbeddingsHasEmbeddingsProperties
  6. def setMaxSentenceLength(value: Int): UAEEmbeddings.this.type

  7. def setModelIfNotSet(spark: SparkSession, tensorflowWrapper: Option[TensorflowWrapper], onnxWrapper: Option[OnnxWrapper], openvinoWrapper: Option[OpenvinoWrapper]): UAEEmbeddings

  8. def setPoolingStrategy(value: String): UAEEmbeddings.this.type

    Pooling strategy to use for sentence embeddings.

    Pooling strategy to use for sentence embeddings.

    Available pooling strategies for sentence embeddings are:

    • "cls": leading [CLS] token
    • "cls_avg": leading [CLS] token + mean of all other tokens
    • "last": embeddings of the last token in the sequence
    • "avg": mean of all tokens
    • "max": max of all embedding features of the entire token sequence
    • "int": An integer number, which represents the index of the token to use as the embedding
  9. def setSignatures(value: Map[String, String]): UAEEmbeddings.this.type

  10. def setVocabulary(value: Map[String, Int]): UAEEmbeddings.this.type

Parameter getters

  1. def getBatchSize: Int

    Size of every batch.

    Size of every batch.

    Definition Classes
    HasBatchedAnnotate
  2. def getCaseSensitive: Boolean

    Definition Classes
    HasCaseSensitiveProperties
  3. def getConfigProtoBytes: Option[Array[Byte]]

  4. def getDimension: Int

    Definition Classes
    HasEmbeddingsProperties
  5. def getEngine: String

    Definition Classes
    HasEngine
  6. def getMaxSentenceLength: Int

  7. def getModelIfNotSet: UAE

  8. def getSignatures: Option[Map[String, String]]