• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JohnSnowLabs / spark-nlp / 4992350528

pending completion
4992350528

Pull #13797

github

GitHub
Merge 424c7ff18 into ef7906c5e
Pull Request #13797: SPARKNLP-835: ProtectedParam and ProtectedFeature

24 of 24 new or added lines in 6 files covered. (100.0%)

8643 of 13129 relevant lines covered (65.83%)

0.66 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/main/scala/com/johnsnowlabs/nlp/annotators/cv/ViTForImageClassification.scala
1
/*
2
 * Copyright 2017-2022 John Snow Labs
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *    http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package com.johnsnowlabs.nlp.annotators.cv
18

19
import com.johnsnowlabs.ml.ai.ViTClassifier
20
import com.johnsnowlabs.ml.tensorflow.{
21
  ReadTensorflowModel,
22
  TensorflowWrapper,
23
  WriteTensorflowModel
24
}
25
import com.johnsnowlabs.ml.util.LoadExternalModel.{
26
  loadJsonStringAsset,
27
  modelSanityCheck,
28
  notSupportedEngineError
29
}
30
import com.johnsnowlabs.ml.util.ModelEngine
31
import com.johnsnowlabs.nlp.AnnotatorType.{CATEGORY, IMAGE}
32
import com.johnsnowlabs.nlp._
33
import com.johnsnowlabs.nlp.annotators.cv.feature_extractor.Preprocessor
34
import com.johnsnowlabs.nlp.serialization.MapFeature
35
import org.apache.spark.broadcast.Broadcast
36
import org.apache.spark.ml.param.IntArrayParam
37
import org.apache.spark.ml.util.Identifiable
38
import org.apache.spark.sql.SparkSession
39
import org.json4s._
40
import org.json4s.jackson.JsonMethods._
41

42
import java.io.File
43

44
/** Vision Transformer (ViT) for image classification.
45
  *
46
  * ViT is a transformer based alternative to the convolutional neural networks usually used for
47
  * image recognition tasks.
48
  *
49
  * Pretrained models can be loaded with `pretrained` of the companion object:
50
  * {{{
51
  * val imageClassifier = ViTForImageClassification.pretrained()
52
  *   .setInputCols("image_assembler")
53
  *   .setOutputCol("class")
54
  * }}}
55
  * The default model is `"image_classifier_vit_base_patch16_224"`, if no name is provided.
56
  *
57
  * For available pretrained models please see the
58
  * [[https://sparknlp.org/models?task=Image+Classification Models Hub]].
59
  *
60
  * Models from the HuggingFace 🤗 Transformers library are also compatible with Spark NLP 🚀. To
61
  * see which models are compatible and how to import them see
62
  * [[https://github.com/JohnSnowLabs/spark-nlp/discussions/5669]] and to see more extended
63
  * examples, see
64
  * [[https://github.com/JohnSnowLabs/spark-nlp/blob/master/src/test/scala/com/johnsnowlabs/nlp/annotators/cv/ViTImageClassificationTestSpec.scala ViTImageClassificationTestSpec]].
65
  *
66
  * '''References:'''
67
  *
68
  * [[https://arxiv.org/abs/2010.11929 An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale]]
69
  *
70
  * '''Paper Abstract:'''
71
  *
72
  * ''While the Transformer architecture has become the de-facto standard for natural language
73
  * processing tasks, its applications to computer vision remain limited. In vision, attention is
74
  * either applied in conjunction with convolutional networks, or used to replace certain
75
  * components of convolutional networks while keeping their overall structure in place. We show
76
  * that this reliance on CNNs is not necessary and a pure transformer applied directly to
77
  * sequences of image patches can perform very well on image classification tasks. When
78
  * pre-trained on large amounts of data and transferred to multiple mid-sized or small image
79
  * recognition benchmarks (ImageNet, CIFAR-100, VTAB, etc.), Vision Transformer (ViT) attains
80
  * excellent results compared to state-of-the-art convolutional networks while requiring
81
  * substantially fewer computational resources to train.''
82
  *
83
  * ==Example==
84
  * {{{
85
  * import com.johnsnowlabs.nlp.annotator._
86
  * import com.johnsnowlabs.nlp.ImageAssembler
87
  * import org.apache.spark.ml.Pipeline
88
  *
89
  * val imageDF: DataFrame = spark.read
90
  *   .format("image")
91
  *   .option("dropInvalid", value = true)
92
  *   .load("src/test/resources/image/")
93
  *
94
  * val imageAssembler = new ImageAssembler()
95
  *   .setInputCol("image")
96
  *   .setOutputCol("image_assembler")
97
  *
98
  * val imageClassifier = ViTForImageClassification
99
  *   .pretrained()
100
  *   .setInputCols("image_assembler")
101
  *   .setOutputCol("class")
102
  *
103
  * val pipeline = new Pipeline().setStages(Array(imageAssembler, imageClassifier))
104
  * val pipelineDF = pipeline.fit(imageDF).transform(imageDF)
105
  *
106
  * pipelineDF
107
  *   .selectExpr("reverse(split(image.origin, '/'))[0] as image_name", "class.result")
108
  *   .show(truncate = false)
109
  * +-----------------+----------------------------------------------------------+
110
  * |image_name       |result                                                    |
111
  * +-----------------+----------------------------------------------------------+
112
  * |palace.JPEG      |[palace]                                                  |
113
  * |egyptian_cat.jpeg|[Egyptian cat]                                            |
114
  * |hippopotamus.JPEG|[hippopotamus, hippo, river horse, Hippopotamus amphibius]|
115
  * |hen.JPEG         |[hen]                                                     |
116
  * |ostrich.JPEG     |[ostrich, Struthio camelus]                               |
117
  * |junco.JPEG       |[junco, snowbird]                                         |
118
  * |bluetick.jpg     |[bluetick]                                                |
119
  * |chihuahua.jpg    |[Chihuahua]                                               |
120
  * |tractor.JPEG     |[tractor]                                                 |
121
  * |ox.JPEG          |[ox]                                                      |
122
  * +-----------------+----------------------------------------------------------+
123
  * }}}
124
  *
125
  * @param uid
126
  *   required uid for storing annotator to disk
127
  * @groupname anno Annotator types
128
  * @groupdesc anno
129
  *   Required input and expected output annotator types
130
  * @groupname Ungrouped Members
131
  * @groupname param Parameters
132
  * @groupname setParam Parameter setters
133
  * @groupname getParam Parameter getters
134
  * @groupname Ungrouped Members
135
  * @groupprio param  1
136
  * @groupprio anno  2
137
  * @groupprio Ungrouped 3
138
  * @groupprio setParam  4
139
  * @groupprio getParam  5
140
  * @groupdesc param
141
  *   A list of (hyper-)parameter keys this annotator can take. Users can set and get the
142
  *   parameter values through setters and getters, respectively.
143
  */
144
class ViTForImageClassification(override val uid: String)
145
    extends AnnotatorModel[ViTForImageClassification]
146
    with HasBatchedAnnotateImage[ViTForImageClassification]
147
    with HasImageFeatureProperties
148
    with WriteTensorflowModel
149
    with HasEngine {
150

151
  /** Annotator reference id. Used to identify elements in metadata or to refer to this annotator
152
    * type
153
    */
154
  def this() = this(Identifiable.randomUID("ViTForImageClassification"))
×
155

156
  /** Output annotator type : CATEGORY
157
    *
158
    * @group anno
159
    */
160
  override val outputAnnotatorType: AnnotatorType = CATEGORY
×
161

162
  /** Input annotator type : IMAGE
163
    *
164
    * @group anno
165
    */
166
  override val inputAnnotatorTypes: Array[AnnotatorType] = Array(IMAGE)
×
167

168
  /** ConfigProto from tensorflow, serialized into byte array. Get with
169
    * config_proto.SerializeToString()
170
    *
171
    * @group param
172
    */
173
  val configProtoBytes = new IntArrayParam(
×
174
    this,
175
    "configProtoBytes",
×
176
    "ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()")
×
177

178
  /** ConfigProto from tensorflow, serialized into byte array. Get with
179
    * config_proto.SerializeToString()
180
    *
181
    * @group setParam
182
    */
183
  def setConfigProtoBytes(bytes: Array[Int]): ViTForImageClassification.this.type =
184
    set(this.configProtoBytes, bytes)
×
185

186
  /** ConfigProto from tensorflow, serialized into byte array. Get with
187
    * config_proto.SerializeToString()
188
    *
189
    * @group getParam
190
    */
191
  def getConfigProtoBytes: Option[Array[Byte]] =
192
    get(this.configProtoBytes).map(_.map(_.toByte))
×
193

194
  /** Labels used to decode predicted IDs back to string tags
195
    *
196
    * @group param
197
    */
198
  val labels: MapFeature[String, BigInt] = new MapFeature(this, "labels").setProtected()
×
199

200
  /** @group setParam */
201
  def setLabels(value: Map[String, BigInt]): this.type = set(labels, value)
×
202

203
  /** Returns labels used to train this model */
204
  def getClasses: Array[String] = {
205
    $$(labels).keys.toArray
×
206
  }
207

208
  /** It contains TF model signatures for the laded saved model
209
    *
210
    * @group param
211
    */
212
  val signatures =
213
    new MapFeature[String, String](model = this, name = "signatures").setProtected()
×
214

215
  /** @group setParam */
216
  def setSignatures(value: Map[String, String]): this.type = {
217
    set(signatures, value)
×
218
    this
219
  }
220

221
  /** @group getParam */
222
  def getSignatures: Option[Map[String, String]] = get(this.signatures)
×
223

224
  private var _model: Option[Broadcast[ViTClassifier]] = None
×
225

226
  /** @group getParam */
227
  def getModelIfNotSet: ViTClassifier = _model.get.value
×
228

229
  /** @group setParam */
230
  def setModelIfNotSet(
231
      spark: SparkSession,
232
      tensorflow: TensorflowWrapper,
233
      preprocessor: Preprocessor): this.type = {
234
    if (_model.isEmpty) {
×
235

236
      _model = Some(
×
237
        spark.sparkContext.broadcast(
×
238
          new ViTClassifier(
×
239
            tensorflow,
240
            configProtoBytes = getConfigProtoBytes,
×
241
            tags = $$(labels),
×
242
            preprocessor = preprocessor,
243
            signatures = getSignatures)))
×
244
    }
245
    this
246
  }
247

248
  setDefault(batchSize -> 2)
×
249

250
  /** Takes a document and annotations and produces new annotations of this annotator's annotation
251
    * type
252
    *
253
    * @param batchedAnnotations
254
    *   Annotations that correspond to inputAnnotationCols generated by previous annotators if any
255
    * @return
256
    *   any number of annotations processed for every input annotation. Not necessary one to one
257
    *   relationship
258
    */
259
  override def batchAnnotate(
260
      batchedAnnotations: Seq[Array[AnnotationImage]]): Seq[Seq[Annotation]] = {
261

262
    // Zip annotations to the row it belongs to
263
    val imagesWithRow = batchedAnnotations.zipWithIndex
×
264
      .flatMap { case (annotations, i) => annotations.map(x => (x, i)) }
×
265

266
    val noneEmptyImages = imagesWithRow.map(_._1).filter(_.result.nonEmpty).toArray
×
267

268
    val allAnnotations =
269
      if (noneEmptyImages.nonEmpty) {
×
270
        getModelIfNotSet.predict(
×
271
          images = noneEmptyImages,
272
          batchSize = $(batchSize),
×
273
          preprocessor = Preprocessor(
×
274
            do_normalize = getDoNormalize,
×
275
            do_resize = getDoResize,
×
276
            feature_extractor_type = getFeatureExtractorType,
×
277
            image_mean = getImageMean,
×
278
            image_std = getImageStd,
×
279
            resample = getResample,
×
280
            size = getSize))
×
281
      } else {
282
        Seq.empty[Annotation]
×
283
      }
284

285
    // Group resulting annotations by rows. If there are not sentences in a given row, return empty sequence
286
    batchedAnnotations.indices.map(rowIndex => {
×
287
      val rowAnnotations = allAnnotations
288
        // zip each annotation with its corresponding row index
289
        .zip(imagesWithRow)
×
290
        // select the sentences belonging to the current row
291
        .filter(_._2._2 == rowIndex)
×
292
        // leave the annotation only
293
        .map(_._1)
×
294

295
      if (rowAnnotations.nonEmpty)
×
296
        rowAnnotations
×
297
      else
298
        Seq.empty[Annotation]
×
299
    })
300

301
  }
302

303
  override def onWrite(path: String, spark: SparkSession): Unit = {
304
    super.onWrite(path, spark)
×
305
    writeTensorflowModelV2(
×
306
      path,
307
      spark,
308
      getModelIfNotSet.tensorflowWrapper,
×
309
      "_image_classification",
×
310
      ViTForImageClassification.tfFile,
×
311
      configProtoBytes = getConfigProtoBytes)
×
312
  }
313

314
}
315

316
trait ReadablePretrainedViTForImageModel
317
    extends ParamsAndFeaturesReadable[ViTForImageClassification]
318
    with HasPretrained[ViTForImageClassification] {
319
  override val defaultModelName: Some[String] = Some("image_classifier_vit_base_patch16_224")
×
320

321
  /** Java compliant-overrides */
322
  override def pretrained(): ViTForImageClassification = super.pretrained()
×
323

324
  override def pretrained(name: String): ViTForImageClassification = super.pretrained(name)
×
325

326
  override def pretrained(name: String, lang: String): ViTForImageClassification =
327
    super.pretrained(name, lang)
×
328

329
  override def pretrained(
330
      name: String,
331
      lang: String,
332
      remoteLoc: String): ViTForImageClassification = super.pretrained(name, lang, remoteLoc)
×
333
}
334

335
trait ReadViTForImageDLModel extends ReadTensorflowModel {
336
  this: ParamsAndFeaturesReadable[ViTForImageClassification] =>
337

338
  override val tfFile: String = "image_classification_tensorflow"
×
339

340
  def readModel(instance: ViTForImageClassification, path: String, spark: SparkSession): Unit = {
341

342
    val tf = readTensorflowModel(path, spark, "_image_classification_tf", initAllTables = false)
×
343

344
    val preprocessor = Preprocessor(
×
345
      do_normalize = true,
×
346
      do_resize = true,
×
347
      "ViTFeatureExtractor",
×
348
      instance.getImageMean,
×
349
      instance.getImageStd,
×
350
      instance.getResample,
×
351
      instance.getSize)
×
352

353
    instance.setModelIfNotSet(spark, tf, preprocessor)
×
354
  }
355

356
  addReader(readModel)
×
357

358
  def loadSavedModel(modelPath: String, spark: SparkSession): ViTForImageClassification = {
359

360
    val (localModelPath, detectedEngine) = modelSanityCheck(modelPath)
×
361

362
    // TODO: sometimes results in [String, BigInt] where BigInt is actually a string
363
    val labelJsonContent = loadJsonStringAsset(localModelPath, "labels.json")
×
364
    val labelJsonMap =
365
      parse(labelJsonContent, useBigIntForLong = true).values
×
366
        .asInstanceOf[Map[String, BigInt]]
×
367

368
    val preprocessorConfigJsonContent =
369
      loadJsonStringAsset(localModelPath, "preprocessor_config.json")
×
370
    val preprocessorConfig =
371
      Preprocessor.loadPreprocessorConfig(preprocessorConfigJsonContent)
×
372

373
    /*Universal parameters for all engines*/
374
    val annotatorModel = new ViTForImageClassification()
375
      .setLabels(labelJsonMap)
376
      .setDoNormalize(preprocessorConfig.do_normalize)
×
377
      .setDoResize(preprocessorConfig.do_resize)
×
378
      .setFeatureExtractorType(preprocessorConfig.feature_extractor_type)
×
379
      .setImageMean(preprocessorConfig.image_mean)
×
380
      .setImageStd(preprocessorConfig.image_std)
×
381
      .setResample(preprocessorConfig.resample)
×
382
      .setSize(preprocessorConfig.size)
×
383

384
    annotatorModel.set(annotatorModel.engine, detectedEngine)
×
385

386
    detectedEngine match {
387
      case ModelEngine.tensorflow =>
388
        val (wrapper, signatures) =
×
389
          TensorflowWrapper.read(localModelPath, zipped = false, useBundle = true)
390

391
        val _signatures = signatures match {
392
          case Some(s) => s
393
          case None => throw new Exception("Cannot load signature definitions from model!")
×
394
        }
395

396
        /** the order of setSignatures is important if we use getSignatures inside
397
          * setModelIfNotSet
398
          */
399
        annotatorModel
400
          .setSignatures(_signatures)
401
          .setModelIfNotSet(spark, wrapper, preprocessorConfig)
×
402

403
      case _ =>
404
        throw new Exception(notSupportedEngineError)
×
405
    }
406

407
    annotatorModel
408
  }
409
}
410

411
/** This is the companion object of [[ViTForImageClassification]]. Please refer to that class for
412
  * the documentation.
413
  */
414
object ViTForImageClassification
415
    extends ReadablePretrainedViTForImageModel
416
    with ReadViTForImageDLModel
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc