text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
Returns:
`np.ndarray`: The resized image.
"""
size = get_size_dict(size)
if "height" not in size or "width" not in size:
raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
output_size = (size["height"], size["w... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
def _preprocess_step(
self,
images: ImageInput,
do_resize: Optional[bool] = None,
size: Dict[str, int] = None,
resample: PILImageResampling = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = No... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
Args:
images (`ImageInput`):
Image to _preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
do_resize (`bool`, *optional*, defaults to `self.do_resi... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the ou... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
Whether to convert the prompt mask to... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
channel to a 3 channel RGB. Not specifying this will result in the prompt mask either being passed
through as is if it is already in RGB format or being duplicated across the channel dimension.
"""
do_resize = do_resize if do_resize is not None else self.do_resize
do_rescale = do... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
size = size if size is not None else self.size
size_dict = get_size_dict(size)
# If segmentation map is passed we expect 2D images
images = make_list_of_images(images, expected_ndims=2 if do_convert_rgb else 3)
if not valid_images(images):
raise ValueError(
... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
if do_rescale and is_scaled_image(images[0]):
logger.warning_once(
"It looks like you are trying to rescale already rescaled images. If the input"
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
)
if inpu... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
if do_resize:
images = [
self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)
for image in images
]
if do_rescale:
images = [
self.rescale(image=image, scale=rescale_factor, input_dat... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
def preprocess(
self,
images: Optional[ImageInput] = None,
prompt_images: Optional[ImageInput] = None,
prompt_masks: Optional[ImageInput] = None,
do_resize: Optional[bool] = None,
size: Dict[str, int] = None,
resample: PILImageResampling = None,
do_rescale... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
Args:
images (`ImageInput`):
Image to _preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
prompt_images (`ImageInput`):
Prompt ima... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
specifying `num_labels` is recommended to build a palette to map the prompt mask from a single channel to
a 3 channel RGB. If `num_labels` is not specified, the prompt mask will be duplicated across the channel
dimension.
do_resize (`bool`, *optional*, defaults to `self.do_re... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
Whether to rescale the image values between [0 - 1].
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
to map the prompt mask from a single channel to a 3 channel RGB. If unset, the prompt mask is duplicated
across the channel dimension. Must be set to `False` if the prompt mask is already in RGB format.
num_labels: (`int`, *optional*):
Number of classes in the segmentation ta... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
- `TensorType.JAX` or `'jax'`: Return a batch of type `ja... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimens... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
data = {}
if images is not None:
images = self._preprocess_step(
images,
is_mask=False,
do_resize=do_resize,
size=size,
resample=resample,
do_rescale=do_rescale,
rescale_factor=rescale_fa... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
if prompt_images is not None:
prompt_images = self._preprocess_step(
prompt_images,
is_mask=False,
do_resize=do_resize,
size=size,
resample=resample,
do_rescale=do_rescale,
rescale_factor=rescale_... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
if prompt_masks is not None:
prompt_masks = self._preprocess_step(
prompt_masks,
do_resize=do_resize,
size=size,
resample=PILImageResampling.NEAREST,
do_rescale=do_rescale,
rescale_factor=rescale_factor,
... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
def post_process_semantic_segmentation(
self, outputs, target_sizes: Optional[List[Tuple[int, int]]] = None, num_labels: Optional[int] = None
):
"""
Converts the output of [`SegGptImageSegmentationOutput`] into segmentation maps. Only supports
PyTorch. | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
Args:
outputs ([`SegGptImageSegmentationOutput`]):
Raw outputs of the model.
target_sizes (`List[Tuple[int, int]]`, *optional*):
List of length (batch_size), where each list item (`Tuple[int, int]`) corresponds to the requested
final size (height, ... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
"""
requires_backends(self, ["torch"])
# batch_size x num_channels x 2*height x width
masks = outputs.pred_masks | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
# Predicted mask and prompt are concatenated in the height dimension
# batch_size x num_channels x height x width
masks = masks[:, :, masks.shape[2] // 2 :, :]
# To unnormalize we need to permute to channel last
# batch_size x height x width x num_channels
std = torch.tensor(sel... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
semantic_segmentation = []
palette_tensor = None
palette = self.get_palette(num_labels) if num_labels is not None else None
if palette is not None:
palette_tensor = torch.tensor(palette).float().to(masks.device)
_, num_channels, _, _ = masks.shape
palette_tens... | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
else:
# If no palette is specified SegGpt will try to paint using the mask class idx as RGB
pred = mask.mean(dim=0).int()
semantic_segmentation.append(pred)
return semantic_segmentation | 10,005 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/image_processing_seggpt.py |
class SegGptConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SegGptModel`]. It is used to instantiate a SegGPT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar... | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
Args:
hidden_size (`int`, *optional*, defaults to 1024):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 24):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults ... | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the layer normalization layers.
image_size (`List[int]`, *optional*, defaults to `[896, 448]`):
The size (... | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
pretrain_image_size (`int`, *optional*, defaults to 224):
The pretrained size of the absolute position embeddings.
decoder_hidden_size (`int`, *optional*, defaults to 64):
Hidden size for decoder.
use_relative_position_embeddings (`bool`, *optional*, defaults to `True`):
... | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
Example:
```python
>>> from transformers import SegGptConfig, SegGptModel
>>> # Initializing a SegGPT seggpt-vit-large style configuration
>>> configuration = SegGptConfig()
>>> # Initializing a model (with random weights) from the seggpt-vit-large style configuration
>>> model = SegGptModel(... | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
def __init__(
self,
hidden_size=1024,
num_hidden_layers=24,
num_attention_heads=16,
hidden_act="gelu",
hidden_dropout_prob=0.0,
initializer_range=0.02,
layer_norm_eps=1e-6,
image_size=[896, 448],
patch_size=16,
num_channels=3,
... | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
if merge_index > min(intermediate_hidden_state_indices):
raise ValueError(
f"Merge index must be less than the minimum encoder output index, but got {merge_index=} and {intermediate_hidden_state_indices=}"
)
self.hidden_size = hidden_size
self.num_hidden_layers = ... | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
self.intermediate_hidden_state_indices = intermediate_hidden_state_indices
self.beta = beta
self.mlp_dim = int(hidden_size * 4) if mlp_dim is None else mlp_dim | 10,006 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/configuration_seggpt.py |
class SegGptEncoderOutput(ModelOutput):
"""
Output type of [`SegGptEncoderOutput`].
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, patch_height, patch_width, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states... | 10,007 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
Tuple of `torch.FloatTensor` of shape `(batch_size, patch_height, patch_width, hidden_size)`.
Each element in the Tuple corresponds to the output of the layer specified in `config.intermediate_hidden_state_indices`.
Additionaly, each feature passes through a LayerNorm.
""" | 10,007 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
last_hidden_state: torch.FloatTensor
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
intermediate_hidden_states: Optional[Tuple[torch.FloatTensor]] = None | 10,007 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptImageSegmentationOutput(ModelOutput):
"""
Output type of [`SegGptImageSegmentationOutput`].
Args:
loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
The loss value.
pred_masks (`torch.FloatTensor` of shape `(batch_size, num_channels, height, ... | 10,008 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
loss: Optional[torch.FloatTensor] = None
pred_masks: Optional[torch.FloatTensor] = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None | 10,008 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptPatchEmbeddings(nn.Module):
"""
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
Transformer.
"""
def __init__(self, config):
... | 10,009 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
def forward(self, pixel_values):
batch_size, num_channels, height, width = pixel_values.shape
if num_channels != self.num_channels:
raise ValueError(
"Make sure that the cha... | 10,009 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptEmbeddings(nn.Module):
"""
Construct the embeddings from patch, position embeddings for input and prompt.
"""
def __init__(self, config: SegGptConfig) -> None:
super().__init__()
self.mask_token = nn.Parameter(torch.zeros(1, 1, 1, config.hidden_size))
self.segment_t... | 10,010 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def interpolate_pos_encoding(self, height: int, width: int) -> torch.Tensor:
patch_pos_embed = self.position_embeddings[:, 1:]
num_patches = patch_pos_embed.shape[1]
pretrain_patch_size = torch_int(num_patches**0.5)
# always interpolate when tracing to ensure the exported model works fo... | 10,010 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def forward(
self,
pixel_values: torch.Tensor,
prompt_pixel_values: torch.Tensor,
bool_masked_pos: Optional[torch.BoolTensor] = None,
embedding_type: Optional[str] = None,
) -> torch.Tensor:
input_embeddings = self.patch_embeddings(pixel_values)
prompt_embeddi... | 10,010 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
# add segment token
input_embeddings = input_embeddings + self.segment_token_input
prompt_embeddings = prompt_embeddings + self.segment_token_prompt
# add position embedding skipping CLS
input_embeddings = input_embeddings + pos_embed
prompt_embeddings = prompt_embeddings + pos_... | 10,010 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptAttention(nn.Module):
"""Multi-head Attention block with relative position embeddings."""
def __init__(self, config):
super().__init__()
image_size, patch_size = config.image_size, config.patch_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) ... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
self.use_relative_position_embeddings = config.use_relative_position_embeddings
if self.use_relative_position_embeddings:
if input_size is None:
raise ValueError("Input size must be provided if using relative positional encoding.")
# initialize relative positional embedd... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
Returns:
Extracted positional embeddings according to relative positions.
"""
max_rel_dist = int(2 * max(q_size, k_size) - 1)
# Interpolate rel pos.
rel_pos_resized = F.interpolate(
rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
size=max_re... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def add_decomposed_rel_pos(
self,
attn: torch.Tensor,
query: torch.Tensor,
rel_pos_h: torch.Tensor,
rel_pos_w: torch.Tensor,
q_size: Tuple[int, int],
k_size: Tuple[int, int],
) -> torch.Tensor:
"""
Calculate decomposed Relative Positional Embed... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
Args:
attn (`torch.Tensor`):
attention map.
query (`torch.Tensor`):
query q in the attention layer with shape (batch_size, query_height * query_width, channel).
rel_pos_h (`torch.Tensor`):
relative position embeddings (Lh, channel) for ... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
Returns:
attn (`torch.Tensor`):
attention map with added relative positional embeddings.
"""
query_height, query_width = q_size
key_height, key_width = k_size
relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
relative_pos... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor:
batch_size, height, width, _ = hidden_states.shape
# qkv with shape (3, batch_size, nHead, height * width, channel)
qkv = (
self.qkv(hidden_states)
.reshape(batch_size, height * width... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
if output_attentions:
# this operation is a bit awkward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_weigh... | 10,011 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptMlp(nn.Module):
def __init__(self, config):
super().__init__()
self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
self.act = ACT2FN[config.hidden_act]
def forward(self, hidden_states: torch.Tensor) -> t... | 10,012 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptDropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> tor... | 10,013 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptLayer(nn.Module):
def __init__(self, config: SegGptConfig, drop_path_rate: float) -> None:
super().__init__()
self.attention = SegGptAttention(config)
self.mlp = SegGptMlp(config)
self.drop_path = SegGptDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
... | 10,014 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def forward(
self,
hidden_states: torch.Tensor,
ensemble_cond: int,
feature_ensemble: bool = False,
output_attentions: bool = False,
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
self_attention_outputs = self.attention(
self.layernorm... | 10,014 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
if feature_ensemble and attention_output.shape[0] // 2 >= ensemble_cond:
prompt, inputs = attention_output.split(attention_output.shape[1] // 2, dim=1)
if ensemble_cond == 2:
num_prompts = attention_output.shape[0] // 2
inputs = inputs.reshape(2, num_prompts, -1)
... | 10,014 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptEncoder(nn.Module):
def __init__(self, config: SegGptConfig) -> None:
super().__init__()
self.config = config
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
self.layers = nn.ModuleList([SegGptLayer(config, dpr[i]) for i in ran... | 10,015 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
for i, layer_module in enumerate(self.layers):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
# Condition to check if we have the appropriate number of prompts to ensemble
ensemble_cond = 2 if self.config.merge_index > i else 1
... | 10,015 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
if i == self.config.merge_index:
hidden_states = (
hidden_states[: hidden_states.shape[0] // 2] + hidden_states[hidden_states.shape[0] // 2 :]
) * 0.5
if i in self.config.intermediate_hidden_state_indices:
intermediate_hidden_states.append... | 10,015 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
if not return_dict:
return tuple(
v
for v in [hidden_states, all_hidden_states, all_self_attentions, intermediate_hidden_states]
if v is not None
)
return SegGptEncoderOutput(
last_hidden_state=hidden_states,
hidden_... | 10,015 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptLayerNorm(nn.Module):
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
width, channels) while channels_first corresponds to inputs with shape ... | 10,016 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.data_format == "channels_last":
x = torch.nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
elif self.data_format == "channels_first":
input_dtype = x.dtype
x = x.float()
... | 10,016 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptDecoderHead(nn.Module):
def __init__(self, config):
super().__init__()
self.conv = nn.Conv2d(
config.decoder_hidden_size,
config.decoder_hidden_size,
kernel_size=3,
padding=1,
)
self.layernorm = SegGptLayerNorm(
... | 10,017 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptDecoder(nn.Module):
def __init__(self, config):
super().__init__()
self.decoder_embed = nn.Linear(
config.hidden_size * len(config.intermediate_hidden_state_indices),
config.patch_size**2 * config.decoder_hidden_size,
bias=True,
)
self.... | 10,018 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def _reshape_hidden_states(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
batch_size, patch_height, patch_width, _ = hidden_states.shape
hidden_states = hidden_states.reshape(
batch_size, patch_height, patch_width, self.patch_size, self.patch_size, self.decoder_hidden_size
... | 10,018 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = SegGptConfig
base_model_prefix = "model"
main_input_name = "pixel_values"
supports_gradient_check... | 10,019 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
"""Initialize the weights"""
std = self.config.initializer_range
if isinstance(module, (nn.Linear, nn.Conv2d)):
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
# ... | 10,019 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
module.rel_pos_w.data = nn.init.trunc_normal_(
module.rel_pos_w.data.to(torch.float32),
mean=0.0,
std=std,
).to(module.rel_pos_w.dtype)
elif isinstance(module, SegGptEmbeddings):
module.position_embeddings.data = nn.init.trunc_normal_(
... | 10,019 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptModel(SegGptPreTrainedModel):
def __init__(self, config: SegGptConfig):
super().__init__(config)
self.config = config
self.embeddings = SegGptEmbeddings(config)
self.encoder = SegGptEncoder(config)
# Initialize weights and apply final processing
self.pos... | 10,020 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
@add_start_docstrings_to_model_forward(SEGGPT_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=SegGptEncoderOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
pixel_values: torch.Tensor,
prompt_pixel_values: torch.Tensor,
prompt_masks: torch.Tensor,
bool_mas... | 10,020 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
```python
>>> from transformers import SegGptImageProcessor, SegGptModel
>>> from PIL import Image
>>> import requests
>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_url = "https://ra... | 10,020 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")
>>> outputs = model(**inputs)
>>> list(outputs.last_hidden_state.shape)
[1, 56, 28, 1024]
```
"""
output_attentions = output_attentions if output_a... | 10,020 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
# Prepare inputs
pixel_values = torch.cat((prompt_pixel_values, pixel_values), dim=2)
prompt_pixel_values = (
torch.cat((prompt_masks, prompt_masks), dim=2)
if labels is None
else torch.cat((prompt_masks, labels), dim=2)
)
if bool_masked_pos is None a... | 10,020 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
# We concat on height axis so SegGPT can handle as a single image, hence we need to mask the portion
# of the mask prompt pixels that will be destinated to the prediction as they don't add any information.
# This is only the case for inference. In training, the model concat of prompt mask and label is m... | 10,020 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
encoder_outputs = self.encoder(
embedding_output,
feature_ensemble=feature_ensemble,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
return encoder_outputs | 10,020 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptLoss(nn.Module):
def __init__(self, config):
super().__init__()
self.beta = config.beta
self.patch_size = config.patch_size
def forward(
self,
prompt_masks: torch.FloatTensor,
pred_masks: torch.FloatTensor,
labels: torch.FloatTensor,
b... | 10,021 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
Returns:
`torch.FloatTensor`: The mean L1 loss between the predicted masks and the ground truth masks.
"""
... | 10,021 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class SegGptForImageSegmentation(SegGptPreTrainedModel):
def __init__(self, config: SegGptConfig):
super().__init__(config)
self.config = config
self.model = SegGptModel(config)
self.decoder = SegGptDecoder(config)
# Initialize weights and apply final processing
sel... | 10,022 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
@add_start_docstrings_to_model_forward(SEGGPT_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=SegGptImageSegmentationOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
pixel_values: torch.Tensor,
prompt_pixel_values: torch.Tensor,
prompt_masks: torch.Tensor,
... | 10,022 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
```python
>>> from transformers import SegGptImageProcessor, SegGptForImageSegmentation
>>> from PIL import Image
>>> import requests
>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_ur... | 10,022 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
>>> checkpoint = "BAAI/seggpt-vit-large"
>>> model = SegGptForImageSegmentation.from_pretrained(checkpoint)
>>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)
>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensor... | 10,022 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
if bool_masked_pos is None:
num_patches = self.model.embeddings.patch_embeddings.num_patches
bool_masked_pos = torch.zeros(num_patches, dtype=torch.bool).to(pixel_values.device)
bool_masked_pos[num_patches // 2 :] = 1
bool_masked_pos = bool_masked_pos.unsqueeze(0)
... | 10,022 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
intermediate_hidden_states = outputs.intermediate_hidden_states if return_dict else outputs[-1]
intermediate_hidden_states = torch.cat(intermediate_hidden_states, dim=-1)
pred_masks = self.decoder(intermediate_hidden_states)
loss = None
if labels is not None:
loss_fn = SegGp... | 10,022 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/seggpt/modeling_seggpt.py |
class Swin2SRConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Swin2SRModel`]. It is used to instantiate a Swin
Transformer v2 model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will ... | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
Args:
image_size (`int`, *optional*, defaults to 64):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 1):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
... | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
Ratio of MLP hidden dimensionality to embedding dimensionality.
qkv_bias (`bool`, *optional*, defaults to `True`):
Whether or not a learnable bias should be added to the queries, keys and values.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability ... | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
Whether or not to add absolute position embeddings to the patch embeddings.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
... | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
The reconstruction reconstruction module. Can be 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None. | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
Example:
```python
>>> from transformers import Swin2SRConfig, Swin2SRModel
>>> # Initializing a Swin2SR caidas/swin2sr-classicalsr-x2-64 style configuration
>>> configuration = Swin2SRConfig()
>>> # Initializing a model (with random weights) from the caidas/swin2sr-classicalsr-x2-64 style config... | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
def __init__(
self,
image_size=64,
patch_size=1,
num_channels=3,
num_channels_out=None,
embed_dim=180,
depths=[6, 6, 6, 6, 6, 6],
num_heads=[6, 6, 6, 6, 6, 6],
window_size=8,
mlp_ratio=2.0,
qkv_bias=True,
hidden_dropout_prob... | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.num_channels_out = num_channels if num_channels_out is None else num_channels_out
self.embed_dim = embed_dim
self.depths = depths
self.num_layers = len(depths)
self.num... | 10,023 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/configuration_swin2sr.py |
class Swin2SREncoderOutput(ModelOutput):
"""
Swin2SR encoder's outputs, with potential hidden states and attentions.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the mode... | 10,024 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/modeling_swin2sr.py |
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch... | 10,024 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/modeling_swin2sr.py |
class Swin2SRDropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> to... | 10,025 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/modeling_swin2sr.py |
class Swin2SREmbeddings(nn.Module):
"""
Construct the patch and optional position embeddings.
"""
def __init__(self, config):
super().__init__()
self.patch_embeddings = Swin2SRPatchEmbeddings(config)
num_patches = self.patch_embeddings.num_patches
if config.use_absolut... | 10,026 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/modeling_swin2sr.py |
class Swin2SRPatchEmbeddings(nn.Module):
def __init__(self, config, normalize_patches=True):
super().__init__()
num_channels = config.embed_dim
image_size, patch_size = config.image_size, config.patch_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) e... | 10,027 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/modeling_swin2sr.py |
def forward(self, embeddings: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor, Tuple[int]]:
embeddings = self.projection(embeddings)
_, _, height, width = embeddings.shape
output_dimensions = (height, width)
embeddings = embeddings.flatten(2).transpose(1, 2)
if self.layernorm... | 10,027 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/modeling_swin2sr.py |
class Swin2SRPatchUnEmbeddings(nn.Module):
r"""Image to Patch Unembedding"""
def __init__(self, config):
super().__init__()
self.embed_dim = config.embed_dim
def forward(self, embeddings, x_size):
batch_size, height_width, num_channels = embeddings.shape
embeddings = embed... | 10,028 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/swin2sr/modeling_swin2sr.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.