Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2022 KAIST 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 at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# limitations under the License.15"""PyTorch GLPN model."""16 17import math18from typing import Optional, Union19 20import torch21from torch import nn22 23from ...activations import ACT2FN24from ...modeling_outputs import BaseModelOutput, DepthEstimatorOutput25from ...modeling_utils import PreTrainedModel26from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer27from ...utils import auto_docstring, logging28from .configuration_glpn import GLPNConfig29 30 31logger = logging.get_logger(__name__)32 33 34# Copied from transformers.models.beit.modeling_beit.drop_path35def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:36 """37 Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).38 39 Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,40 however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...41 See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the42 layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the43 argument.44 """45 if drop_prob == 0.0 or not training:46 return input47 keep_prob = 1 - drop_prob48 shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets49 random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)50 random_tensor.floor_() # binarize51 output = input.div(keep_prob) * random_tensor52 return output53 54 55# Copied from transformers.models.segformer.modeling_segformer.SegformerDropPath56class GLPNDropPath(nn.Module):57 """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""58 59 def __init__(self, drop_prob: Optional[float] = None) -> None:60 super().__init__()61 self.drop_prob = drop_prob62 63 def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:64 return drop_path(hidden_states, self.drop_prob, self.training)65 66 def extra_repr(self) -> str:67 return f"p={self.drop_prob}"68 69 70# Copied from transformers.models.segformer.modeling_segformer.SegformerOverlapPatchEmbeddings71class GLPNOverlapPatchEmbeddings(nn.Module):72 """Construct the overlapping patch embeddings."""73 74 def __init__(self, patch_size, stride, num_channels, hidden_size):75 super().__init__()76 self.proj = nn.Conv2d(77 num_channels,78 hidden_size,79 kernel_size=patch_size,80 stride=stride,81 padding=patch_size // 2,82 )83 84 self.layer_norm = nn.LayerNorm(hidden_size)85 86 def forward(self, pixel_values):87 embeddings = self.proj(pixel_values)88 _, _, height, width = embeddings.shape89 # (batch_size, num_channels, height, width) -> (batch_size, num_channels, height*width) -> (batch_size, height*width, num_channels)90 # this can be fed to a Transformer layer91 embeddings = embeddings.flatten(2).transpose(1, 2)92 embeddings = self.layer_norm(embeddings)93 return embeddings, height, width94 95 96# Copied from transformers.models.segformer.modeling_segformer.SegformerEfficientSelfAttention97class GLPNEfficientSelfAttention(nn.Module):98 """SegFormer's efficient self-attention mechanism. Employs the sequence reduction process introduced in the [PvT99 paper](https://huggingface.co/papers/2102.12122)."""100 101 def __init__(self, config, hidden_size, num_attention_heads, sequence_reduction_ratio):102 super().__init__()103 self.hidden_size = hidden_size104 self.num_attention_heads = num_attention_heads105 106 if self.hidden_size % self.num_attention_heads != 0:107 raise ValueError(108 f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "109 f"heads ({self.num_attention_heads})"110 )111 112 self.attention_head_size = int(self.hidden_size / self.num_attention_heads)113 self.all_head_size = self.num_attention_heads * self.attention_head_size114 115 self.query = nn.Linear(self.hidden_size, self.all_head_size)116 self.key = nn.Linear(self.hidden_size, self.all_head_size)117 self.value = nn.Linear(self.hidden_size, self.all_head_size)118 119 self.dropout = nn.Dropout(config.attention_probs_dropout_prob)120 121 self.sr_ratio = sequence_reduction_ratio122 if sequence_reduction_ratio > 1:123 self.sr = nn.Conv2d(124 hidden_size, hidden_size, kernel_size=sequence_reduction_ratio, stride=sequence_reduction_ratio125 )126 self.layer_norm = nn.LayerNorm(hidden_size)127 128 def forward(129 self,130 hidden_states,131 height,132 width,133 output_attentions=False,134 ):135 batch_size, seq_length, _ = hidden_states.shape136 query_layer = (137 self.query(hidden_states)138 .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)139 .transpose(1, 2)140 )141 142 if self.sr_ratio > 1:143 batch_size, seq_len, num_channels = hidden_states.shape144 # Reshape to (batch_size, num_channels, height, width)145 hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)146 # Apply sequence reduction147 hidden_states = self.sr(hidden_states)148 # Reshape back to (batch_size, seq_len, num_channels)149 hidden_states = hidden_states.reshape(batch_size, num_channels, -1).permute(0, 2, 1)150 hidden_states = self.layer_norm(hidden_states)151 152 key_layer = (153 self.key(hidden_states)154 .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)155 .transpose(1, 2)156 )157 value_layer = (158 self.value(hidden_states)159 .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)160 .transpose(1, 2)161 )162 163 # Take the dot product between "query" and "key" to get the raw attention scores.164 attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))165 166 attention_scores = attention_scores / math.sqrt(self.attention_head_size)167 168 # Normalize the attention scores to probabilities.169 attention_probs = nn.functional.softmax(attention_scores, dim=-1)170 171 # This is actually dropping out entire tokens to attend to, which might172 # seem a bit unusual, but is taken from the original Transformer paper.173 attention_probs = self.dropout(attention_probs)174 175 context_layer = torch.matmul(attention_probs, value_layer)176 177 context_layer = context_layer.permute(0, 2, 1, 3).contiguous()178 new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)179 context_layer = context_layer.view(new_context_layer_shape)180 181 outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)182 183 return outputs184 185 186# Copied from transformers.models.segformer.modeling_segformer.SegformerSelfOutput187class GLPNSelfOutput(nn.Module):188 def __init__(self, config, hidden_size):189 super().__init__()190 self.dense = nn.Linear(hidden_size, hidden_size)191 self.dropout = nn.Dropout(config.hidden_dropout_prob)192 193 def forward(self, hidden_states, input_tensor):194 hidden_states = self.dense(hidden_states)195 hidden_states = self.dropout(hidden_states)196 return hidden_states197 198 199# Copied from transformers.models.segformer.modeling_segformer.SegformerAttention with Segformer->GLPN200class GLPNAttention(nn.Module):201 def __init__(self, config, hidden_size, num_attention_heads, sequence_reduction_ratio):202 super().__init__()203 self.self = GLPNEfficientSelfAttention(204 config=config,205 hidden_size=hidden_size,206 num_attention_heads=num_attention_heads,207 sequence_reduction_ratio=sequence_reduction_ratio,208 )209 self.output = GLPNSelfOutput(config, hidden_size=hidden_size)210 self.pruned_heads = set()211 212 def prune_heads(self, heads):213 if len(heads) == 0:214 return215 heads, index = find_pruneable_heads_and_indices(216 heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads217 )218 219 # Prune linear layers220 self.self.query = prune_linear_layer(self.self.query, index)221 self.self.key = prune_linear_layer(self.self.key, index)222 self.self.value = prune_linear_layer(self.self.value, index)223 self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)224 225 # Update hyper params and store pruned heads226 self.self.num_attention_heads = self.self.num_attention_heads - len(heads)227 self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads228 self.pruned_heads = self.pruned_heads.union(heads)229 230 def forward(self, hidden_states, height, width, output_attentions=False):231 self_outputs = self.self(hidden_states, height, width, output_attentions)232 233 attention_output = self.output(self_outputs[0], hidden_states)234 outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them235 return outputs236 237 238# Copied from transformers.models.segformer.modeling_segformer.SegformerDWConv239class GLPNDWConv(nn.Module):240 def __init__(self, dim=768):241 super().__init__()242 self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)243 244 def forward(self, hidden_states, height, width):245 batch_size, seq_len, num_channels = hidden_states.shape246 hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width)247 hidden_states = self.dwconv(hidden_states)248 hidden_states = hidden_states.flatten(2).transpose(1, 2)249 250 return hidden_states251 252 253# Copied from transformers.models.segformer.modeling_segformer.SegformerMixFFN with Segformer->GLPN254class GLPNMixFFN(nn.Module):255 def __init__(self, config, in_features, hidden_features=None, out_features=None):256 super().__init__()257 out_features = out_features or in_features258 self.dense1 = nn.Linear(in_features, hidden_features)259 self.dwconv = GLPNDWConv(hidden_features)260 if isinstance(config.hidden_act, str):261 self.intermediate_act_fn = ACT2FN[config.hidden_act]262 else:263 self.intermediate_act_fn = config.hidden_act264 self.dense2 = nn.Linear(hidden_features, out_features)265 self.dropout = nn.Dropout(config.hidden_dropout_prob)266 267 def forward(self, hidden_states, height, width):268 hidden_states = self.dense1(hidden_states)269 hidden_states = self.dwconv(hidden_states, height, width)270 hidden_states = self.intermediate_act_fn(hidden_states)271 hidden_states = self.dropout(hidden_states)272 hidden_states = self.dense2(hidden_states)273 hidden_states = self.dropout(hidden_states)274 return hidden_states275 276 277# Copied from transformers.models.segformer.modeling_segformer.SegformerLayer with Segformer->GLPN278class GLPNLayer(nn.Module):279 """This corresponds to the Block class in the original implementation."""280 281 def __init__(self, config, hidden_size, num_attention_heads, drop_path, sequence_reduction_ratio, mlp_ratio):282 super().__init__()283 self.layer_norm_1 = nn.LayerNorm(hidden_size)284 self.attention = GLPNAttention(285 config,286 hidden_size=hidden_size,287 num_attention_heads=num_attention_heads,288 sequence_reduction_ratio=sequence_reduction_ratio,289 )290 self.drop_path = GLPNDropPath(drop_path) if drop_path > 0.0 else nn.Identity()291 self.layer_norm_2 = nn.LayerNorm(hidden_size)292 mlp_hidden_size = int(hidden_size * mlp_ratio)293 self.mlp = GLPNMixFFN(config, in_features=hidden_size, hidden_features=mlp_hidden_size)294 295 def forward(self, hidden_states, height, width, output_attentions=False):296 self_attention_outputs = self.attention(297 self.layer_norm_1(hidden_states), # in GLPN, layernorm is applied before self-attention298 height,299 width,300 output_attentions=output_attentions,301 )302 303 attention_output = self_attention_outputs[0]304 outputs = self_attention_outputs[1:] # add self attentions if we output attention weights305 306 # first residual connection (with stochastic depth)307 attention_output = self.drop_path(attention_output)308 hidden_states = attention_output + hidden_states309 310 mlp_output = self.mlp(self.layer_norm_2(hidden_states), height, width)311 312 # second residual connection (with stochastic depth)313 mlp_output = self.drop_path(mlp_output)314 layer_output = mlp_output + hidden_states315 316 outputs = (layer_output,) + outputs317 318 return outputs319 320 321class GLPNEncoder(nn.Module):322 def __init__(self, config):323 super().__init__()324 self.config = config325 326 # stochastic depth decay rule327 dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]328 329 # patch embeddings330 embeddings = []331 for i in range(config.num_encoder_blocks):332 embeddings.append(333 GLPNOverlapPatchEmbeddings(334 patch_size=config.patch_sizes[i],335 stride=config.strides[i],336 num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1],337 hidden_size=config.hidden_sizes[i],338 )339 )340 self.patch_embeddings = nn.ModuleList(embeddings)341 342 # Transformer blocks343 blocks = []344 cur = 0345 for i in range(config.num_encoder_blocks):346 # each block consists of layers347 layers = []348 if i != 0:349 cur += config.depths[i - 1]350 for j in range(config.depths[i]):351 layers.append(352 GLPNLayer(353 config,354 hidden_size=config.hidden_sizes[i],355 num_attention_heads=config.num_attention_heads[i],356 drop_path=dpr[cur + j],357 sequence_reduction_ratio=config.sr_ratios[i],358 mlp_ratio=config.mlp_ratios[i],359 )360 )361 blocks.append(nn.ModuleList(layers))362 363 self.block = nn.ModuleList(blocks)364 365 # Layer norms366 self.layer_norm = nn.ModuleList(367 [nn.LayerNorm(config.hidden_sizes[i]) for i in range(config.num_encoder_blocks)]368 )369 370 def forward(371 self,372 pixel_values,373 output_attentions=False,374 output_hidden_states=False,375 return_dict=True,376 ):377 all_hidden_states = () if output_hidden_states else None378 all_self_attentions = () if output_attentions else None379 380 batch_size = pixel_values.shape[0]381 382 hidden_states = pixel_values383 for idx, x in enumerate(zip(self.patch_embeddings, self.block, self.layer_norm)):384 embedding_layer, block_layer, norm_layer = x385 # first, obtain patch embeddings386 hidden_states, height, width = embedding_layer(hidden_states)387 # second, send embeddings through blocks388 for i, blk in enumerate(block_layer):389 layer_outputs = blk(hidden_states, height, width, output_attentions)390 hidden_states = layer_outputs[0]391 if output_attentions:392 all_self_attentions = all_self_attentions + (layer_outputs[1],)393 # third, apply layer norm394 hidden_states = norm_layer(hidden_states)395 # fourth, optionally reshape back to (batch_size, num_channels, height, width)396 hidden_states = hidden_states.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()397 if output_hidden_states:398 all_hidden_states = all_hidden_states + (hidden_states,)399 400 if not return_dict:401 return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)402 return BaseModelOutput(403 last_hidden_state=hidden_states,404 hidden_states=all_hidden_states,405 attentions=all_self_attentions,406 )407 408 409@auto_docstring410class GLPNPreTrainedModel(PreTrainedModel):411 config: GLPNConfig412 base_model_prefix = "glpn"413 main_input_name = "pixel_values"414 _no_split_modules = []415 416 # Copied from transformers.models.segformer.modeling_segformer.SegformerPreTrainedModel._init_weights417 def _init_weights(self, module):418 """Initialize the weights"""419 if isinstance(module, (nn.Linear, nn.Conv2d)):420 # Slightly different from the TF version which uses truncated_normal for initialization421 # cf https://github.com/pytorch/pytorch/pull/5617422 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)423 if module.bias is not None:424 module.bias.data.zero_()425 elif isinstance(module, nn.Embedding):426 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)427 if module.padding_idx is not None:428 module.weight.data[module.padding_idx].zero_()429 elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):430 module.bias.data.zero_()431 module.weight.data.fill_(1.0)432 433 434@auto_docstring435class GLPNModel(GLPNPreTrainedModel):436 # Copied from transformers.models.segformer.modeling_segformer.SegformerModel.__init__ with Segformer->GLPN437 def __init__(self, config):438 super().__init__(config)439 self.config = config440 441 # hierarchical Transformer encoder442 self.encoder = GLPNEncoder(config)443 444 # Initialize weights and apply final processing445 self.post_init()446 447 def _prune_heads(self, heads_to_prune):448 """449 Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base450 class PreTrainedModel451 """452 for layer, heads in heads_to_prune.items():453 self.encoder.layer[layer].attention.prune_heads(heads)454 455 @auto_docstring456 # Copied from transformers.models.segformer.modeling_segformer.SegformerModel.forward457 def forward(458 self,459 pixel_values: torch.FloatTensor,460 output_attentions: Optional[bool] = None,461 output_hidden_states: Optional[bool] = None,462 return_dict: Optional[bool] = None,463 ) -> Union[tuple, BaseModelOutput]:464 output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions465 output_hidden_states = (466 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states467 )468 return_dict = return_dict if return_dict is not None else self.config.use_return_dict469 470 encoder_outputs = self.encoder(471 pixel_values,472 output_attentions=output_attentions,473 output_hidden_states=output_hidden_states,474 return_dict=return_dict,475 )476 sequence_output = encoder_outputs[0]477 478 if not return_dict:479 return (sequence_output,) + encoder_outputs[1:]480 481 return BaseModelOutput(482 last_hidden_state=sequence_output,483 hidden_states=encoder_outputs.hidden_states,484 attentions=encoder_outputs.attentions,485 )486 487 488class GLPNSelectiveFeatureFusion(nn.Module):489 """490 Selective Feature Fusion module, as explained in the [paper](https://huggingface.co/papers/2201.07436) (section 3.4). This491 module adaptively selects and integrates local and global features by attaining an attention map for each feature.492 """493 494 def __init__(self, in_channel=64):495 super().__init__()496 497 self.convolutional_layer1 = nn.Sequential(498 nn.Conv2d(in_channels=int(in_channel * 2), out_channels=in_channel, kernel_size=3, stride=1, padding=1),499 nn.BatchNorm2d(in_channel),500 nn.ReLU(),501 )502 503 self.convolutional_layer2 = nn.Sequential(504 nn.Conv2d(in_channels=in_channel, out_channels=int(in_channel / 2), kernel_size=3, stride=1, padding=1),505 nn.BatchNorm2d(int(in_channel / 2)),506 nn.ReLU(),507 )508 509 self.convolutional_layer3 = nn.Conv2d(510 in_channels=int(in_channel / 2), out_channels=2, kernel_size=3, stride=1, padding=1511 )512 513 self.sigmoid = nn.Sigmoid()514 515 def forward(self, local_features, global_features):516 # concatenate features along the channel dimension517 features = torch.cat((local_features, global_features), dim=1)518 # pass through convolutional layers519 features = self.convolutional_layer1(features)520 features = self.convolutional_layer2(features)521 features = self.convolutional_layer3(features)522 # apply sigmoid to get two-channel attention map523 attn = self.sigmoid(features)524 # construct hybrid features by adding element-wise525 hybrid_features = local_features * attn[:, 0, :, :].unsqueeze(1) + global_features * attn[526 :, 1, :, :527 ].unsqueeze(1)528 529 return hybrid_features530 531 532class GLPNDecoderStage(nn.Module):533 def __init__(self, in_channels, out_channels):534 super().__init__()535 should_skip = in_channels == out_channels536 self.convolution = nn.Conv2d(in_channels, out_channels, kernel_size=1) if not should_skip else nn.Identity()537 self.fusion = GLPNSelectiveFeatureFusion(out_channels)538 self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)539 540 def forward(self, hidden_state, residual=None):541 hidden_state = self.convolution(hidden_state)542 if residual is not None:543 hidden_state = self.fusion(hidden_state, residual)544 hidden_state = self.upsample(hidden_state)545 546 return hidden_state547 548 hidden_state = self.upsample(hidden_state)549 return hidden_state550 551 552class GLPNDecoder(nn.Module):553 def __init__(self, config):554 super().__init__()555 # we use features from end -> start556 reserved_hidden_sizes = config.hidden_sizes[::-1]557 out_channels = config.decoder_hidden_size558 559 self.stages = nn.ModuleList(560 [GLPNDecoderStage(hidden_size, out_channels) for hidden_size in reserved_hidden_sizes]561 )562 # don't fuse in first stage563 self.stages[0].fusion = None564 565 self.final_upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)566 567 def forward(self, hidden_states: list[torch.Tensor]) -> list[torch.Tensor]:568 stage_hidden_states = []569 stage_hidden_state = None570 for hidden_state, stage in zip(hidden_states[::-1], self.stages):571 stage_hidden_state = stage(hidden_state, stage_hidden_state)572 stage_hidden_states.append(stage_hidden_state)573 574 stage_hidden_states[-1] = self.final_upsample(stage_hidden_state)575 576 return stage_hidden_states577 578 579class SiLogLoss(nn.Module):580 r"""581 Implements the Scale-invariant log scale loss [Eigen et al., 2014](https://huggingface.co/papers/1406.2283).582 583 $$L=\frac{1}{n} \sum_{i} d_{i}^{2}-\frac{1}{2 n^{2}}\left(\sum_{i} d_{i}^{2}\right)$$ where $d_{i}=\log y_{i}-\log584 y_{i}^{*}$.585 586 """587 588 def __init__(self, lambd=0.5):589 super().__init__()590 self.lambd = lambd591 592 def forward(self, pred, target):593 valid_mask = (target > 0).detach()594 diff_log = torch.log(target[valid_mask]) - torch.log(pred[valid_mask])595 loss = torch.sqrt(torch.pow(diff_log, 2).mean() - self.lambd * torch.pow(diff_log.mean(), 2))596 597 return loss598 599 600class GLPNDepthEstimationHead(nn.Module):601 def __init__(self, config):602 super().__init__()603 604 self.config = config605 606 channels = config.decoder_hidden_size607 self.head = nn.Sequential(608 nn.Conv2d(channels, channels, kernel_size=3, stride=1, padding=1),609 nn.ReLU(inplace=False),610 nn.Conv2d(channels, 1, kernel_size=3, stride=1, padding=1),611 )612 613 def forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor:614 # use last features of the decoder615 hidden_states = hidden_states[self.config.head_in_index]616 617 hidden_states = self.head(hidden_states)618 619 predicted_depth = torch.sigmoid(hidden_states) * self.config.max_depth620 predicted_depth = predicted_depth.squeeze(dim=1)621 622 return predicted_depth623 624 625@auto_docstring(626 custom_intro="""627 GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.628 """629)630class GLPNForDepthEstimation(GLPNPreTrainedModel):631 def __init__(self, config):632 super().__init__(config)633 634 self.glpn = GLPNModel(config)635 self.decoder = GLPNDecoder(config)636 self.head = GLPNDepthEstimationHead(config)637 638 # Initialize weights and apply final processing639 self.post_init()640 641 @auto_docstring642 def forward(643 self,644 pixel_values: torch.FloatTensor,645 labels: Optional[torch.FloatTensor] = None,646 output_attentions: Optional[bool] = None,647 output_hidden_states: Optional[bool] = None,648 return_dict: Optional[bool] = None,649 ) -> Union[tuple[torch.Tensor], DepthEstimatorOutput]:650 r"""651 labels (`torch.FloatTensor` of shape `(batch_size, height, width)`, *optional*):652 Ground truth depth estimation maps for computing the loss.653 654 Examples:655 656 ```python657 >>> from transformers import AutoImageProcessor, GLPNForDepthEstimation658 >>> import torch659 >>> import numpy as np660 >>> from PIL import Image661 >>> import requests662 663 >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"664 >>> image = Image.open(requests.get(url, stream=True).raw)665 666 >>> image_processor = AutoImageProcessor.from_pretrained("vinvino02/glpn-kitti")667 >>> model = GLPNForDepthEstimation.from_pretrained("vinvino02/glpn-kitti")668 669 >>> # prepare image for the model670 >>> inputs = image_processor(images=image, return_tensors="pt")671 672 >>> with torch.no_grad():673 ... outputs = model(**inputs)674 675 >>> # interpolate to original size676 >>> post_processed_output = image_processor.post_process_depth_estimation(677 ... outputs,678 ... target_sizes=[(image.height, image.width)],679 ... )680 681 >>> # visualize the prediction682 >>> predicted_depth = post_processed_output[0]["predicted_depth"]683 >>> depth = predicted_depth * 255 / predicted_depth.max()684 >>> depth = depth.detach().cpu().numpy()685 >>> depth = Image.fromarray(depth.astype("uint8"))686 ```"""687 return_dict = return_dict if return_dict is not None else self.config.use_return_dict688 output_hidden_states = (689 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states690 )691 692 outputs = self.glpn(693 pixel_values,694 output_attentions=output_attentions,695 output_hidden_states=True, # we need the intermediate hidden states696 return_dict=return_dict,697 )698 699 hidden_states = outputs.hidden_states if return_dict else outputs[1]700 701 out = self.decoder(hidden_states)702 predicted_depth = self.head(out)703 704 loss = None705 if labels is not None:706 loss_fct = SiLogLoss()707 loss = loss_fct(predicted_depth, labels)708 709 if not return_dict:710 if output_hidden_states:711 output = (predicted_depth,) + outputs[1:]712 else:713 output = (predicted_depth,) + outputs[2:]714 return ((loss,) + output) if loss is not None else output715 716 return DepthEstimatorOutput(717 loss=loss,718 predicted_depth=predicted_depth,719 hidden_states=outputs.hidden_states if output_hidden_states else None,720 attentions=outputs.attentions,721 )722 723 724__all__ = ["GLPNForDepthEstimation", "GLPNLayer", "GLPNModel", "GLPNPreTrainedModel"]725 