modeling_vitmatte.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. # coding=utf-8
  2. # Copyright 2023 HUST-VL 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. """PyTorch ViTMatte model."""
  16. from dataclasses import dataclass
  17. from typing import Optional, Tuple
  18. import torch
  19. from torch import nn
  20. from ...modeling_utils import PreTrainedModel
  21. from ...utils import (
  22. ModelOutput,
  23. add_start_docstrings,
  24. add_start_docstrings_to_model_forward,
  25. replace_return_docstrings,
  26. )
  27. from ...utils.backbone_utils import load_backbone
  28. from .configuration_vitmatte import VitMatteConfig
  29. # General docstring
  30. _CONFIG_FOR_DOC = "VitMatteConfig"
  31. @dataclass
  32. class ImageMattingOutput(ModelOutput):
  33. """
  34. Class for outputs of image matting models.
  35. Args:
  36. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  37. Loss.
  38. alphas (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  39. Estimated alpha values.
  40. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  41. Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  42. one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
  43. (also called feature maps) of the model at the output of each stage.
  44. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  45. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size,
  46. sequence_length)`.
  47. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  48. heads.
  49. """
  50. loss: Optional[torch.FloatTensor] = None
  51. alphas: torch.FloatTensor = None
  52. hidden_states: Optional[Tuple[torch.FloatTensor]] = None
  53. attentions: Optional[Tuple[torch.FloatTensor]] = None
  54. class VitMattePreTrainedModel(PreTrainedModel):
  55. """
  56. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  57. models.
  58. """
  59. config_class = VitMatteConfig
  60. main_input_name = "pixel_values"
  61. supports_gradient_checkpointing = True
  62. _no_split_modules = []
  63. def _init_weights(self, module):
  64. if isinstance(module, nn.Conv2d):
  65. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  66. if module.bias is not None:
  67. module.bias.data.zero_()
  68. class VitMatteBasicConv3x3(nn.Module):
  69. """
  70. Basic convolution layers including: Conv3x3, BatchNorm2d, ReLU layers.
  71. """
  72. def __init__(self, config, in_channels, out_channels, stride=2, padding=1):
  73. super().__init__()
  74. self.conv = nn.Conv2d(
  75. in_channels=in_channels,
  76. out_channels=out_channels,
  77. kernel_size=3,
  78. stride=stride,
  79. padding=padding,
  80. bias=False,
  81. )
  82. self.batch_norm = nn.BatchNorm2d(out_channels, eps=config.batch_norm_eps)
  83. self.relu = nn.ReLU()
  84. def forward(self, hidden_state):
  85. hidden_state = self.conv(hidden_state)
  86. hidden_state = self.batch_norm(hidden_state)
  87. hidden_state = self.relu(hidden_state)
  88. return hidden_state
  89. class VitMatteConvStream(nn.Module):
  90. """
  91. Simple ConvStream containing a series of basic conv3x3 layers to extract detail features.
  92. """
  93. def __init__(self, config):
  94. super().__init__()
  95. # We use a default in-case there isn't a backbone config set. This is for backwards compatibility and
  96. # to enable loading HF backbone models.
  97. in_channels = 4
  98. if config.backbone_config is not None:
  99. in_channels = config.backbone_config.num_channels
  100. out_channels = config.convstream_hidden_sizes
  101. self.convs = nn.ModuleList()
  102. self.conv_chans = [in_channels] + out_channels
  103. for i in range(len(self.conv_chans) - 1):
  104. in_chan_ = self.conv_chans[i]
  105. out_chan_ = self.conv_chans[i + 1]
  106. self.convs.append(VitMatteBasicConv3x3(config, in_chan_, out_chan_))
  107. def forward(self, pixel_values):
  108. out_dict = {"detailed_feature_map_0": pixel_values}
  109. embeddings = pixel_values
  110. for i in range(len(self.convs)):
  111. embeddings = self.convs[i](embeddings)
  112. name_ = "detailed_feature_map_" + str(i + 1)
  113. out_dict[name_] = embeddings
  114. return out_dict
  115. class VitMatteFusionBlock(nn.Module):
  116. """
  117. Simple fusion block to fuse features from ConvStream and Plain Vision Transformer.
  118. """
  119. def __init__(self, config, in_channels, out_channels):
  120. super().__init__()
  121. self.conv = VitMatteBasicConv3x3(config, in_channels, out_channels, stride=1, padding=1)
  122. def forward(self, features, detailed_feature_map):
  123. upscaled_features = nn.functional.interpolate(features, scale_factor=2, mode="bilinear", align_corners=False)
  124. out = torch.cat([detailed_feature_map, upscaled_features], dim=1)
  125. out = self.conv(out)
  126. return out
  127. class VitMatteHead(nn.Module):
  128. """
  129. Simple Matting Head, containing only conv3x3 and conv1x1 layers.
  130. """
  131. def __init__(self, config):
  132. super().__init__()
  133. in_channels = config.fusion_hidden_sizes[-1]
  134. mid_channels = 16
  135. self.matting_convs = nn.Sequential(
  136. nn.Conv2d(in_channels, mid_channels, kernel_size=3, stride=1, padding=1),
  137. nn.BatchNorm2d(mid_channels),
  138. nn.ReLU(True),
  139. nn.Conv2d(mid_channels, 1, kernel_size=1, stride=1, padding=0),
  140. )
  141. def forward(self, hidden_state):
  142. hidden_state = self.matting_convs(hidden_state)
  143. return hidden_state
  144. class VitMatteDetailCaptureModule(nn.Module):
  145. """
  146. Simple and lightweight Detail Capture Module for ViT Matting.
  147. """
  148. def __init__(self, config):
  149. super().__init__()
  150. if len(config.fusion_hidden_sizes) != len(config.convstream_hidden_sizes) + 1:
  151. raise ValueError(
  152. "The length of fusion_hidden_sizes should be equal to the length of convstream_hidden_sizes + 1."
  153. )
  154. self.config = config
  155. self.convstream = VitMatteConvStream(config)
  156. self.conv_chans = self.convstream.conv_chans
  157. self.fusion_blocks = nn.ModuleList()
  158. self.fusion_channels = [config.hidden_size] + config.fusion_hidden_sizes
  159. for i in range(len(self.fusion_channels) - 1):
  160. self.fusion_blocks.append(
  161. VitMatteFusionBlock(
  162. config=config,
  163. in_channels=self.fusion_channels[i] + self.conv_chans[-(i + 1)],
  164. out_channels=self.fusion_channels[i + 1],
  165. )
  166. )
  167. self.matting_head = VitMatteHead(config)
  168. def forward(self, features, pixel_values):
  169. detail_features = self.convstream(pixel_values)
  170. for i in range(len(self.fusion_blocks)):
  171. detailed_feature_map_name = "detailed_feature_map_" + str(len(self.fusion_blocks) - i - 1)
  172. features = self.fusion_blocks[i](features, detail_features[detailed_feature_map_name])
  173. alphas = torch.sigmoid(self.matting_head(features))
  174. return alphas
  175. VITMATTE_START_DOCSTRING = r"""
  176. Parameters:
  177. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
  178. it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
  179. behavior.
  180. config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.
  181. Initializing with a config file does not load the weights associated with the model, only the
  182. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  183. """
  184. VITMATTE_INPUTS_DOCSTRING = r"""
  185. Args:
  186. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  187. Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
  188. [`AutoImageProcessor`]. See [`VitMatteImageProcessor.__call__`] for details.
  189. output_attentions (`bool`, *optional*):
  190. Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See
  191. `attentions` under returned tensors for more detail.
  192. output_hidden_states (`bool`, *optional*):
  193. Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under
  194. returned tensors for more detail.
  195. return_dict (`bool`, *optional*):
  196. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  197. """
  198. @add_start_docstrings(
  199. """ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.""",
  200. VITMATTE_START_DOCSTRING,
  201. )
  202. class VitMatteForImageMatting(VitMattePreTrainedModel):
  203. def __init__(self, config):
  204. super().__init__(config)
  205. self.config = config
  206. self.backbone = load_backbone(config)
  207. self.decoder = VitMatteDetailCaptureModule(config)
  208. # Initialize weights and apply final processing
  209. self.post_init()
  210. @add_start_docstrings_to_model_forward(VITMATTE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  211. @replace_return_docstrings(output_type=ImageMattingOutput, config_class=_CONFIG_FOR_DOC)
  212. def forward(
  213. self,
  214. pixel_values: Optional[torch.Tensor] = None,
  215. output_attentions: Optional[bool] = None,
  216. output_hidden_states: Optional[bool] = None,
  217. labels: Optional[torch.Tensor] = None,
  218. return_dict: Optional[bool] = None,
  219. ):
  220. """
  221. labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
  222. Ground truth image matting for computing the loss.
  223. Returns:
  224. Examples:
  225. ```python
  226. >>> from transformers import VitMatteImageProcessor, VitMatteForImageMatting
  227. >>> import torch
  228. >>> from PIL import Image
  229. >>> from huggingface_hub import hf_hub_download
  230. >>> processor = VitMatteImageProcessor.from_pretrained("hustvl/vitmatte-small-composition-1k")
  231. >>> model = VitMatteForImageMatting.from_pretrained("hustvl/vitmatte-small-composition-1k")
  232. >>> filepath = hf_hub_download(
  233. ... repo_id="hf-internal-testing/image-matting-fixtures", filename="image.png", repo_type="dataset"
  234. ... )
  235. >>> image = Image.open(filepath).convert("RGB")
  236. >>> filepath = hf_hub_download(
  237. ... repo_id="hf-internal-testing/image-matting-fixtures", filename="trimap.png", repo_type="dataset"
  238. ... )
  239. >>> trimap = Image.open(filepath).convert("L")
  240. >>> # prepare image + trimap for the model
  241. >>> inputs = processor(images=image, trimaps=trimap, return_tensors="pt")
  242. >>> with torch.no_grad():
  243. ... alphas = model(**inputs).alphas
  244. >>> print(alphas.shape)
  245. torch.Size([1, 1, 640, 960])
  246. ```"""
  247. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  248. output_hidden_states = (
  249. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  250. )
  251. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  252. loss = None
  253. if labels is not None:
  254. raise NotImplementedError("Training is not yet supported")
  255. outputs = self.backbone.forward_with_filtered_kwargs(
  256. pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
  257. )
  258. features = outputs.feature_maps[-1]
  259. alphas = self.decoder(features, pixel_values)
  260. if not return_dict:
  261. output = (alphas,) + outputs[1:]
  262. return ((loss,) + output) if loss is not None else output
  263. return ImageMattingOutput(
  264. loss=loss,
  265. alphas=alphas,
  266. hidden_states=outputs.hidden_states,
  267. attentions=outputs.attentions,
  268. )