modeling_vitmatte.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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
  18. import torch
  19. from torch import nn
  20. from ...modeling_utils import PreTrainedModel
  21. from ...utils import ModelOutput, auto_docstring
  22. from ...utils.backbone_utils import load_backbone
  23. from .configuration_vitmatte import VitMatteConfig
  24. @dataclass
  25. @auto_docstring(
  26. custom_intro="""
  27. Class for outputs of image matting models.
  28. """
  29. )
  30. class ImageMattingOutput(ModelOutput):
  31. r"""
  32. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  33. Loss.
  34. alphas (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  35. Estimated alpha values.
  36. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  37. Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  38. one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
  39. (also called feature maps) of the model at the output of each stage.
  40. """
  41. loss: Optional[torch.FloatTensor] = None
  42. alphas: Optional[torch.FloatTensor] = None
  43. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  44. attentions: Optional[tuple[torch.FloatTensor]] = None
  45. @auto_docstring
  46. class VitMattePreTrainedModel(PreTrainedModel):
  47. config: VitMatteConfig
  48. main_input_name = "pixel_values"
  49. supports_gradient_checkpointing = True
  50. _no_split_modules = []
  51. def _init_weights(self, module: nn.Module):
  52. if isinstance(module, (nn.Conv2d, nn.BatchNorm2d)):
  53. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  54. if module.bias is not None:
  55. module.bias.data.zero_()
  56. class VitMatteBasicConv3x3(nn.Module):
  57. """
  58. Basic convolution layers including: Conv3x3, BatchNorm2d, ReLU layers.
  59. """
  60. def __init__(self, config, in_channels, out_channels, stride=2, padding=1):
  61. super().__init__()
  62. self.conv = nn.Conv2d(
  63. in_channels=in_channels,
  64. out_channels=out_channels,
  65. kernel_size=3,
  66. stride=stride,
  67. padding=padding,
  68. bias=False,
  69. )
  70. self.batch_norm = nn.BatchNorm2d(out_channels, eps=config.batch_norm_eps)
  71. self.relu = nn.ReLU()
  72. def forward(self, hidden_state):
  73. hidden_state = self.conv(hidden_state)
  74. hidden_state = self.batch_norm(hidden_state)
  75. hidden_state = self.relu(hidden_state)
  76. return hidden_state
  77. class VitMatteConvStream(nn.Module):
  78. """
  79. Simple ConvStream containing a series of basic conv3x3 layers to extract detail features.
  80. """
  81. def __init__(self, config):
  82. super().__init__()
  83. # We use a default in-case there isn't a backbone config set. This is for backwards compatibility and
  84. # to enable loading HF backbone models.
  85. in_channels = 4
  86. if config.backbone_config is not None:
  87. in_channels = config.backbone_config.num_channels
  88. out_channels = config.convstream_hidden_sizes
  89. self.convs = nn.ModuleList()
  90. self.conv_chans = [in_channels] + out_channels
  91. for i in range(len(self.conv_chans) - 1):
  92. in_chan_ = self.conv_chans[i]
  93. out_chan_ = self.conv_chans[i + 1]
  94. self.convs.append(VitMatteBasicConv3x3(config, in_chan_, out_chan_))
  95. def forward(self, pixel_values):
  96. out_dict = {"detailed_feature_map_0": pixel_values}
  97. embeddings = pixel_values
  98. for i in range(len(self.convs)):
  99. embeddings = self.convs[i](embeddings)
  100. name_ = "detailed_feature_map_" + str(i + 1)
  101. out_dict[name_] = embeddings
  102. return out_dict
  103. class VitMatteFusionBlock(nn.Module):
  104. """
  105. Simple fusion block to fuse features from ConvStream and Plain Vision Transformer.
  106. """
  107. def __init__(self, config, in_channels, out_channels):
  108. super().__init__()
  109. self.conv = VitMatteBasicConv3x3(config, in_channels, out_channels, stride=1, padding=1)
  110. def forward(self, features, detailed_feature_map):
  111. upscaled_features = nn.functional.interpolate(features, scale_factor=2, mode="bilinear", align_corners=False)
  112. out = torch.cat([detailed_feature_map, upscaled_features], dim=1)
  113. out = self.conv(out)
  114. return out
  115. class VitMatteHead(nn.Module):
  116. """
  117. Simple Matting Head, containing only conv3x3 and conv1x1 layers.
  118. """
  119. def __init__(self, config):
  120. super().__init__()
  121. in_channels = config.fusion_hidden_sizes[-1]
  122. mid_channels = 16
  123. self.matting_convs = nn.Sequential(
  124. nn.Conv2d(in_channels, mid_channels, kernel_size=3, stride=1, padding=1),
  125. nn.BatchNorm2d(mid_channels),
  126. nn.ReLU(True),
  127. nn.Conv2d(mid_channels, 1, kernel_size=1, stride=1, padding=0),
  128. )
  129. def forward(self, hidden_state):
  130. hidden_state = self.matting_convs(hidden_state)
  131. return hidden_state
  132. class VitMatteDetailCaptureModule(nn.Module):
  133. """
  134. Simple and lightweight Detail Capture Module for ViT Matting.
  135. """
  136. def __init__(self, config):
  137. super().__init__()
  138. if len(config.fusion_hidden_sizes) != len(config.convstream_hidden_sizes) + 1:
  139. raise ValueError(
  140. "The length of fusion_hidden_sizes should be equal to the length of convstream_hidden_sizes + 1."
  141. )
  142. self.config = config
  143. self.convstream = VitMatteConvStream(config)
  144. self.conv_chans = self.convstream.conv_chans
  145. self.fusion_blocks = nn.ModuleList()
  146. self.fusion_channels = [config.hidden_size] + config.fusion_hidden_sizes
  147. for i in range(len(self.fusion_channels) - 1):
  148. self.fusion_blocks.append(
  149. VitMatteFusionBlock(
  150. config=config,
  151. in_channels=self.fusion_channels[i] + self.conv_chans[-(i + 1)],
  152. out_channels=self.fusion_channels[i + 1],
  153. )
  154. )
  155. self.matting_head = VitMatteHead(config)
  156. def forward(self, features, pixel_values):
  157. detail_features = self.convstream(pixel_values)
  158. for i in range(len(self.fusion_blocks)):
  159. detailed_feature_map_name = "detailed_feature_map_" + str(len(self.fusion_blocks) - i - 1)
  160. features = self.fusion_blocks[i](features, detail_features[detailed_feature_map_name])
  161. alphas = torch.sigmoid(self.matting_head(features))
  162. return alphas
  163. @auto_docstring(
  164. custom_intro="""
  165. ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.
  166. """
  167. )
  168. class VitMatteForImageMatting(VitMattePreTrainedModel):
  169. def __init__(self, config):
  170. super().__init__(config)
  171. self.config = config
  172. self.backbone = load_backbone(config)
  173. self.decoder = VitMatteDetailCaptureModule(config)
  174. # Initialize weights and apply final processing
  175. self.post_init()
  176. @auto_docstring
  177. def forward(
  178. self,
  179. pixel_values: Optional[torch.Tensor] = None,
  180. output_attentions: Optional[bool] = None,
  181. output_hidden_states: Optional[bool] = None,
  182. labels: Optional[torch.Tensor] = None,
  183. return_dict: Optional[bool] = None,
  184. ):
  185. r"""
  186. labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
  187. Ground truth image matting for computing the loss.
  188. Examples:
  189. ```python
  190. >>> from transformers import VitMatteImageProcessor, VitMatteForImageMatting
  191. >>> import torch
  192. >>> from PIL import Image
  193. >>> from huggingface_hub import hf_hub_download
  194. >>> processor = VitMatteImageProcessor.from_pretrained("hustvl/vitmatte-small-composition-1k")
  195. >>> model = VitMatteForImageMatting.from_pretrained("hustvl/vitmatte-small-composition-1k")
  196. >>> filepath = hf_hub_download(
  197. ... repo_id="hf-internal-testing/image-matting-fixtures", filename="image.png", repo_type="dataset"
  198. ... )
  199. >>> image = Image.open(filepath).convert("RGB")
  200. >>> filepath = hf_hub_download(
  201. ... repo_id="hf-internal-testing/image-matting-fixtures", filename="trimap.png", repo_type="dataset"
  202. ... )
  203. >>> trimap = Image.open(filepath).convert("L")
  204. >>> # prepare image + trimap for the model
  205. >>> inputs = processor(images=image, trimaps=trimap, return_tensors="pt")
  206. >>> with torch.no_grad():
  207. ... alphas = model(**inputs).alphas
  208. >>> print(alphas.shape)
  209. torch.Size([1, 1, 640, 960])
  210. ```"""
  211. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  212. output_hidden_states = (
  213. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  214. )
  215. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  216. loss = None
  217. if labels is not None:
  218. raise NotImplementedError("Training is not yet supported")
  219. outputs = self.backbone.forward_with_filtered_kwargs(
  220. pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
  221. )
  222. features = outputs.feature_maps[-1]
  223. alphas = self.decoder(features, pixel_values)
  224. if not return_dict:
  225. output = (alphas,) + outputs[1:]
  226. return ((loss,) + output) if loss is not None else output
  227. return ImageMattingOutput(
  228. loss=loss,
  229. alphas=alphas,
  230. hidden_states=outputs.hidden_states,
  231. attentions=outputs.attentions,
  232. )
  233. __all__ = ["VitMattePreTrainedModel", "VitMatteForImageMatting"]