modeling_tf_convnext.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. # coding=utf-8
  2. # Copyright 2022 Meta Platforms Inc. and The HuggingFace Inc. team. All rights reserved.
  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. """TF 2.0 ConvNext model."""
  16. from __future__ import annotations
  17. from typing import List, Optional, Tuple, Union
  18. import numpy as np
  19. import tensorflow as tf
  20. from ...activations_tf import get_tf_activation
  21. from ...modeling_tf_outputs import TFBaseModelOutput, TFBaseModelOutputWithPooling, TFSequenceClassifierOutput
  22. from ...modeling_tf_utils import (
  23. TFModelInputType,
  24. TFPreTrainedModel,
  25. TFSequenceClassificationLoss,
  26. get_initializer,
  27. keras,
  28. keras_serializable,
  29. unpack_inputs,
  30. )
  31. from ...tf_utils import shape_list
  32. from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
  33. from .configuration_convnext import ConvNextConfig
  34. logger = logging.get_logger(__name__)
  35. _CONFIG_FOR_DOC = "ConvNextConfig"
  36. _CHECKPOINT_FOR_DOC = "facebook/convnext-tiny-224"
  37. class TFConvNextDropPath(keras.layers.Layer):
  38. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  39. References:
  40. (1) github.com:rwightman/pytorch-image-models
  41. """
  42. def __init__(self, drop_path: float, **kwargs):
  43. super().__init__(**kwargs)
  44. self.drop_path = drop_path
  45. def call(self, x: tf.Tensor, training=None):
  46. if training:
  47. keep_prob = 1 - self.drop_path
  48. shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
  49. random_tensor = keep_prob + tf.random.uniform(shape, 0, 1)
  50. random_tensor = tf.floor(random_tensor)
  51. return (x / keep_prob) * random_tensor
  52. return x
  53. class TFConvNextEmbeddings(keras.layers.Layer):
  54. """This class is comparable to (and inspired by) the SwinEmbeddings class
  55. found in src/transformers/models/swin/modeling_swin.py.
  56. """
  57. def __init__(self, config: ConvNextConfig, **kwargs):
  58. super().__init__(**kwargs)
  59. self.patch_embeddings = keras.layers.Conv2D(
  60. filters=config.hidden_sizes[0],
  61. kernel_size=config.patch_size,
  62. strides=config.patch_size,
  63. name="patch_embeddings",
  64. kernel_initializer=get_initializer(config.initializer_range),
  65. bias_initializer=keras.initializers.Zeros(),
  66. )
  67. self.layernorm = keras.layers.LayerNormalization(epsilon=1e-6, name="layernorm")
  68. self.num_channels = config.num_channels
  69. self.config = config
  70. def call(self, pixel_values):
  71. if isinstance(pixel_values, dict):
  72. pixel_values = pixel_values["pixel_values"]
  73. tf.debugging.assert_equal(
  74. shape_list(pixel_values)[1],
  75. self.num_channels,
  76. message="Make sure that the channel dimension of the pixel values match with the one set in the configuration.",
  77. )
  78. # When running on CPU, `keras.layers.Conv2D` doesn't support `NCHW` format.
  79. # So change the input format from `NCHW` to `NHWC`.
  80. # shape = (batch_size, in_height, in_width, in_channels)
  81. pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
  82. embeddings = self.patch_embeddings(pixel_values)
  83. embeddings = self.layernorm(embeddings)
  84. return embeddings
  85. def build(self, input_shape=None):
  86. if self.built:
  87. return
  88. self.built = True
  89. if getattr(self, "patch_embeddings", None) is not None:
  90. with tf.name_scope(self.patch_embeddings.name):
  91. self.patch_embeddings.build([None, None, None, self.config.num_channels])
  92. if getattr(self, "layernorm", None) is not None:
  93. with tf.name_scope(self.layernorm.name):
  94. self.layernorm.build([None, None, None, self.config.hidden_sizes[0]])
  95. class TFConvNextLayer(keras.layers.Layer):
  96. """This corresponds to the `Block` class in the original implementation.
  97. There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
  98. H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
  99. The authors used (2) as they find it slightly faster in PyTorch. Since we already permuted the inputs to follow
  100. NHWC ordering, we can just apply the operations straight-away without the permutation.
  101. Args:
  102. config ([`ConvNextConfig`]): Model configuration class.
  103. dim (`int`): Number of input channels.
  104. drop_path (`float`): Stochastic depth rate. Default: 0.0.
  105. """
  106. def __init__(self, config, dim, drop_path=0.0, **kwargs):
  107. super().__init__(**kwargs)
  108. self.dim = dim
  109. self.config = config
  110. self.dwconv = keras.layers.Conv2D(
  111. filters=dim,
  112. kernel_size=7,
  113. padding="same",
  114. groups=dim,
  115. kernel_initializer=get_initializer(config.initializer_range),
  116. bias_initializer="zeros",
  117. name="dwconv",
  118. ) # depthwise conv
  119. self.layernorm = keras.layers.LayerNormalization(
  120. epsilon=1e-6,
  121. name="layernorm",
  122. )
  123. self.pwconv1 = keras.layers.Dense(
  124. units=4 * dim,
  125. kernel_initializer=get_initializer(config.initializer_range),
  126. bias_initializer="zeros",
  127. name="pwconv1",
  128. ) # pointwise/1x1 convs, implemented with linear layers
  129. self.act = get_tf_activation(config.hidden_act)
  130. self.pwconv2 = keras.layers.Dense(
  131. units=dim,
  132. kernel_initializer=get_initializer(config.initializer_range),
  133. bias_initializer="zeros",
  134. name="pwconv2",
  135. )
  136. # Using `layers.Activation` instead of `tf.identity` to better control `training`
  137. # behaviour.
  138. self.drop_path = (
  139. TFConvNextDropPath(drop_path, name="drop_path")
  140. if drop_path > 0.0
  141. else keras.layers.Activation("linear", name="drop_path")
  142. )
  143. def build(self, input_shape: tf.TensorShape = None):
  144. # PT's `nn.Parameters` must be mapped to a TF layer weight to inherit the same name hierarchy (and vice-versa)
  145. self.layer_scale_parameter = (
  146. self.add_weight(
  147. shape=(self.dim,),
  148. initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
  149. trainable=True,
  150. name="layer_scale_parameter",
  151. )
  152. if self.config.layer_scale_init_value > 0
  153. else None
  154. )
  155. if self.built:
  156. return
  157. self.built = True
  158. if getattr(self, "dwconv", None) is not None:
  159. with tf.name_scope(self.dwconv.name):
  160. self.dwconv.build([None, None, None, self.dim])
  161. if getattr(self, "layernorm", None) is not None:
  162. with tf.name_scope(self.layernorm.name):
  163. self.layernorm.build([None, None, None, self.dim])
  164. if getattr(self, "pwconv1", None) is not None:
  165. with tf.name_scope(self.pwconv1.name):
  166. self.pwconv1.build([None, None, self.dim])
  167. if getattr(self, "pwconv2", None) is not None:
  168. with tf.name_scope(self.pwconv2.name):
  169. self.pwconv2.build([None, None, 4 * self.dim])
  170. if getattr(self, "drop_path", None) is not None:
  171. with tf.name_scope(self.drop_path.name):
  172. self.drop_path.build(None)
  173. def call(self, hidden_states, training=False):
  174. input = hidden_states
  175. x = self.dwconv(hidden_states)
  176. x = self.layernorm(x)
  177. x = self.pwconv1(x)
  178. x = self.act(x)
  179. x = self.pwconv2(x)
  180. if self.layer_scale_parameter is not None:
  181. x = self.layer_scale_parameter * x
  182. x = input + self.drop_path(x, training=training)
  183. return x
  184. class TFConvNextStage(keras.layers.Layer):
  185. """ConvNext stage, consisting of an optional downsampling layer + multiple residual blocks.
  186. Args:
  187. config (`ConvNextV2Config`):
  188. Model configuration class.
  189. in_channels (`int`):
  190. Number of input channels.
  191. out_channels (`int`):
  192. Number of output channels.
  193. depth (`int`):
  194. Number of residual blocks.
  195. drop_path_rates(`List[float]`):
  196. Stochastic depth rates for each layer.
  197. """
  198. def __init__(
  199. self,
  200. config: ConvNextConfig,
  201. in_channels: int,
  202. out_channels: int,
  203. kernel_size: int = 2,
  204. stride: int = 2,
  205. depth: int = 2,
  206. drop_path_rates: Optional[List[float]] = None,
  207. **kwargs,
  208. ):
  209. super().__init__(**kwargs)
  210. if in_channels != out_channels or stride > 1:
  211. self.downsampling_layer = [
  212. keras.layers.LayerNormalization(
  213. epsilon=1e-6,
  214. name="downsampling_layer.0",
  215. ),
  216. # Inputs to this layer will follow NHWC format since we
  217. # transposed the inputs from NCHW to NHWC in the `TFConvNextEmbeddings`
  218. # layer. All the outputs throughout the model will be in NHWC
  219. # from this point on until the output where we again change to
  220. # NCHW.
  221. keras.layers.Conv2D(
  222. filters=out_channels,
  223. kernel_size=kernel_size,
  224. strides=stride,
  225. kernel_initializer=get_initializer(config.initializer_range),
  226. bias_initializer=keras.initializers.Zeros(),
  227. name="downsampling_layer.1",
  228. ),
  229. ]
  230. else:
  231. self.downsampling_layer = [tf.identity]
  232. drop_path_rates = drop_path_rates or [0.0] * depth
  233. self.layers = [
  234. TFConvNextLayer(
  235. config,
  236. dim=out_channels,
  237. drop_path=drop_path_rates[j],
  238. name=f"layers.{j}",
  239. )
  240. for j in range(depth)
  241. ]
  242. self.in_channels = in_channels
  243. self.out_channels = out_channels
  244. self.stride = stride
  245. def call(self, hidden_states):
  246. for layer in self.downsampling_layer:
  247. hidden_states = layer(hidden_states)
  248. for layer in self.layers:
  249. hidden_states = layer(hidden_states)
  250. return hidden_states
  251. def build(self, input_shape=None):
  252. if self.built:
  253. return
  254. self.built = True
  255. if getattr(self, "layers", None) is not None:
  256. for layer in self.layers:
  257. with tf.name_scope(layer.name):
  258. layer.build(None)
  259. if self.in_channels != self.out_channels or self.stride > 1:
  260. with tf.name_scope(self.downsampling_layer[0].name):
  261. self.downsampling_layer[0].build([None, None, None, self.in_channels])
  262. with tf.name_scope(self.downsampling_layer[1].name):
  263. self.downsampling_layer[1].build([None, None, None, self.in_channels])
  264. class TFConvNextEncoder(keras.layers.Layer):
  265. def __init__(self, config, **kwargs):
  266. super().__init__(**kwargs)
  267. self.stages = []
  268. drop_path_rates = tf.linspace(0.0, config.drop_path_rate, sum(config.depths))
  269. drop_path_rates = tf.split(drop_path_rates, config.depths)
  270. drop_path_rates = [x.numpy().tolist() for x in drop_path_rates]
  271. prev_chs = config.hidden_sizes[0]
  272. for i in range(config.num_stages):
  273. out_chs = config.hidden_sizes[i]
  274. stage = TFConvNextStage(
  275. config,
  276. in_channels=prev_chs,
  277. out_channels=out_chs,
  278. stride=2 if i > 0 else 1,
  279. depth=config.depths[i],
  280. drop_path_rates=drop_path_rates[i],
  281. name=f"stages.{i}",
  282. )
  283. self.stages.append(stage)
  284. prev_chs = out_chs
  285. def call(self, hidden_states, output_hidden_states=False, return_dict=True):
  286. all_hidden_states = () if output_hidden_states else None
  287. for i, layer_module in enumerate(self.stages):
  288. if output_hidden_states:
  289. all_hidden_states = all_hidden_states + (hidden_states,)
  290. hidden_states = layer_module(hidden_states)
  291. if output_hidden_states:
  292. all_hidden_states = all_hidden_states + (hidden_states,)
  293. if not return_dict:
  294. return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
  295. return TFBaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
  296. def build(self, input_shape=None):
  297. for stage in self.stages:
  298. with tf.name_scope(stage.name):
  299. stage.build(None)
  300. @keras_serializable
  301. class TFConvNextMainLayer(keras.layers.Layer):
  302. config_class = ConvNextConfig
  303. def __init__(self, config: ConvNextConfig, add_pooling_layer: bool = True, **kwargs):
  304. super().__init__(**kwargs)
  305. self.config = config
  306. self.embeddings = TFConvNextEmbeddings(config, name="embeddings")
  307. self.encoder = TFConvNextEncoder(config, name="encoder")
  308. self.layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm")
  309. # We are setting the `data_format` like so because from here on we will revert to the
  310. # NCHW output format
  311. self.pooler = keras.layers.GlobalAvgPool2D(data_format="channels_first") if add_pooling_layer else None
  312. @unpack_inputs
  313. def call(
  314. self,
  315. pixel_values: TFModelInputType | None = None,
  316. output_hidden_states: Optional[bool] = None,
  317. return_dict: Optional[bool] = None,
  318. training: bool = False,
  319. ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
  320. output_hidden_states = (
  321. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  322. )
  323. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  324. if pixel_values is None:
  325. raise ValueError("You have to specify pixel_values")
  326. embedding_output = self.embeddings(pixel_values, training=training)
  327. encoder_outputs = self.encoder(
  328. embedding_output,
  329. output_hidden_states=output_hidden_states,
  330. return_dict=return_dict,
  331. training=training,
  332. )
  333. last_hidden_state = encoder_outputs[0]
  334. # Change to NCHW output format have uniformity in the modules
  335. last_hidden_state = tf.transpose(last_hidden_state, perm=(0, 3, 1, 2))
  336. pooled_output = self.layernorm(self.pooler(last_hidden_state))
  337. # Change the other hidden state outputs to NCHW as well
  338. if output_hidden_states:
  339. hidden_states = tuple([tf.transpose(h, perm=(0, 3, 1, 2)) for h in encoder_outputs[1]])
  340. if not return_dict:
  341. hidden_states = hidden_states if output_hidden_states else ()
  342. return (last_hidden_state, pooled_output) + hidden_states
  343. return TFBaseModelOutputWithPooling(
  344. last_hidden_state=last_hidden_state,
  345. pooler_output=pooled_output,
  346. hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,
  347. )
  348. def build(self, input_shape=None):
  349. if self.built:
  350. return
  351. self.built = True
  352. if getattr(self, "embeddings", None) is not None:
  353. with tf.name_scope(self.embeddings.name):
  354. self.embeddings.build(None)
  355. if getattr(self, "encoder", None) is not None:
  356. with tf.name_scope(self.encoder.name):
  357. self.encoder.build(None)
  358. if getattr(self, "layernorm", None) is not None:
  359. with tf.name_scope(self.layernorm.name):
  360. self.layernorm.build([None, self.config.hidden_sizes[-1]])
  361. class TFConvNextPreTrainedModel(TFPreTrainedModel):
  362. """
  363. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  364. models.
  365. """
  366. config_class = ConvNextConfig
  367. base_model_prefix = "convnext"
  368. main_input_name = "pixel_values"
  369. CONVNEXT_START_DOCSTRING = r"""
  370. This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
  371. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  372. etc.)
  373. This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
  374. as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
  375. behavior.
  376. <Tip>
  377. TensorFlow models and layers in `transformers` accept two formats as input:
  378. - having all inputs as keyword arguments (like PyTorch models), or
  379. - having all inputs as a list, tuple or dict in the first positional argument.
  380. The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
  381. and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
  382. pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
  383. format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
  384. the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
  385. positional argument:
  386. - a single Tensor with `pixel_values` only and nothing else: `model(pixel_values)`
  387. - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
  388. `model([pixel_values, attention_mask])` or `model([pixel_values, attention_mask, token_type_ids])`
  389. - a dictionary with one or several input Tensors associated to the input names given in the docstring:
  390. `model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})`
  391. Note that when creating models and layers with
  392. [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
  393. about any of this, as you can just pass inputs like you would to any other Python function!
  394. </Tip>
  395. Parameters:
  396. config ([`ConvNextConfig`]): Model configuration class with all the parameters of the model.
  397. Initializing with a config file does not load the weights associated with the model, only the
  398. configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
  399. """
  400. CONVNEXT_INPUTS_DOCSTRING = r"""
  401. Args:
  402. pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
  403. Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
  404. [`ConvNextImageProcessor.__call__`] for details.
  405. output_hidden_states (`bool`, *optional*):
  406. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  407. more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
  408. used instead.
  409. return_dict (`bool`, *optional*):
  410. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
  411. eager mode, in graph mode the value will always be set to True.
  412. """
  413. @add_start_docstrings(
  414. "The bare ConvNext model outputting raw features without any specific head on top.",
  415. CONVNEXT_START_DOCSTRING,
  416. )
  417. class TFConvNextModel(TFConvNextPreTrainedModel):
  418. def __init__(self, config, *inputs, add_pooling_layer=True, **kwargs):
  419. super().__init__(config, *inputs, **kwargs)
  420. self.convnext = TFConvNextMainLayer(config, add_pooling_layer=add_pooling_layer, name="convnext")
  421. @unpack_inputs
  422. @add_start_docstrings_to_model_forward(CONVNEXT_INPUTS_DOCSTRING)
  423. @replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC)
  424. def call(
  425. self,
  426. pixel_values: TFModelInputType | None = None,
  427. output_hidden_states: Optional[bool] = None,
  428. return_dict: Optional[bool] = None,
  429. training: bool = False,
  430. ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
  431. r"""
  432. Returns:
  433. Examples:
  434. ```python
  435. >>> from transformers import AutoImageProcessor, TFConvNextModel
  436. >>> from PIL import Image
  437. >>> import requests
  438. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  439. >>> image = Image.open(requests.get(url, stream=True).raw)
  440. >>> image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224")
  441. >>> model = TFConvNextModel.from_pretrained("facebook/convnext-tiny-224")
  442. >>> inputs = image_processor(images=image, return_tensors="tf")
  443. >>> outputs = model(**inputs)
  444. >>> last_hidden_states = outputs.last_hidden_state
  445. ```"""
  446. output_hidden_states = (
  447. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  448. )
  449. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  450. if pixel_values is None:
  451. raise ValueError("You have to specify pixel_values")
  452. outputs = self.convnext(
  453. pixel_values=pixel_values,
  454. output_hidden_states=output_hidden_states,
  455. return_dict=return_dict,
  456. training=training,
  457. )
  458. if not return_dict:
  459. return (outputs[0],) + outputs[1:]
  460. return TFBaseModelOutputWithPooling(
  461. last_hidden_state=outputs.last_hidden_state,
  462. pooler_output=outputs.pooler_output,
  463. hidden_states=outputs.hidden_states,
  464. )
  465. def build(self, input_shape=None):
  466. if self.built:
  467. return
  468. self.built = True
  469. if getattr(self, "convnext", None) is not None:
  470. with tf.name_scope(self.convnext.name):
  471. self.convnext.build(None)
  472. @add_start_docstrings(
  473. """
  474. ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
  475. ImageNet.
  476. """,
  477. CONVNEXT_START_DOCSTRING,
  478. )
  479. class TFConvNextForImageClassification(TFConvNextPreTrainedModel, TFSequenceClassificationLoss):
  480. def __init__(self, config: ConvNextConfig, *inputs, **kwargs):
  481. super().__init__(config, *inputs, **kwargs)
  482. self.num_labels = config.num_labels
  483. self.convnext = TFConvNextMainLayer(config, name="convnext")
  484. # Classifier head
  485. self.classifier = keras.layers.Dense(
  486. units=config.num_labels,
  487. kernel_initializer=get_initializer(config.initializer_range),
  488. bias_initializer="zeros",
  489. name="classifier",
  490. )
  491. self.config = config
  492. @unpack_inputs
  493. @add_start_docstrings_to_model_forward(CONVNEXT_INPUTS_DOCSTRING)
  494. @replace_return_docstrings(output_type=TFSequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
  495. def call(
  496. self,
  497. pixel_values: TFModelInputType | None = None,
  498. output_hidden_states: Optional[bool] = None,
  499. return_dict: Optional[bool] = None,
  500. labels: np.ndarray | tf.Tensor | None = None,
  501. training: Optional[bool] = False,
  502. ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
  503. r"""
  504. labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
  505. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  506. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  507. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  508. Returns:
  509. Examples:
  510. ```python
  511. >>> from transformers import AutoImageProcessor, TFConvNextForImageClassification
  512. >>> import tensorflow as tf
  513. >>> from PIL import Image
  514. >>> import requests
  515. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  516. >>> image = Image.open(requests.get(url, stream=True).raw)
  517. >>> image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224")
  518. >>> model = TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224")
  519. >>> inputs = image_processor(images=image, return_tensors="tf")
  520. >>> outputs = model(**inputs)
  521. >>> logits = outputs.logits
  522. >>> # model predicts one of the 1000 ImageNet classes
  523. >>> predicted_class_idx = tf.math.argmax(logits, axis=-1)[0]
  524. >>> print("Predicted class:", model.config.id2label[int(predicted_class_idx)])
  525. ```"""
  526. output_hidden_states = (
  527. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  528. )
  529. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  530. if pixel_values is None:
  531. raise ValueError("You have to specify pixel_values")
  532. outputs = self.convnext(
  533. pixel_values,
  534. output_hidden_states=output_hidden_states,
  535. return_dict=return_dict,
  536. training=training,
  537. )
  538. pooled_output = outputs.pooler_output if return_dict else outputs[1]
  539. logits = self.classifier(pooled_output)
  540. loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
  541. if not return_dict:
  542. output = (logits,) + outputs[2:]
  543. return ((loss,) + output) if loss is not None else output
  544. return TFSequenceClassifierOutput(
  545. loss=loss,
  546. logits=logits,
  547. hidden_states=outputs.hidden_states,
  548. )
  549. def build(self, input_shape=None):
  550. if self.built:
  551. return
  552. self.built = True
  553. if getattr(self, "convnext", None) is not None:
  554. with tf.name_scope(self.convnext.name):
  555. self.convnext.build(None)
  556. if getattr(self, "classifier", None) is not None:
  557. if hasattr(self.classifier, "name"):
  558. with tf.name_scope(self.classifier.name):
  559. self.classifier.build([None, None, self.config.hidden_sizes[-1]])