text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
@add_start_docstrings_to_model_forward(LAYOUTLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
bbox: Optional[torch.LongTe... | 9,618 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. | 9,618 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
Returns:
Examples:
```python
>>> from transformers import AutoTokenizer, LayoutLMForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
>>> model = LayoutLMForTokenClassification.from_pretrained("microso... | 9,618 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
>>> encoding = tokenizer(" ".join(words), return_tensors="pt")
>>> input_ids = encoding["input_ids"]
>>> attention_mask = encoding["attention_mask"]
>>> token_type_ids = encoding["token_type_ids"]
>>> bbox = torch.tensor([token_boxes])
>>> token_labels = torch.tensor([1, 1, 0, 0]... | 9,618 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
outputs = self.layoutlm(
input_ids=input_ids,
bbox=bbox,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_att... | 9,618 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
) | 9,618 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
class LayoutLMForQuestionAnswering(LayoutLMPreTrainedModel):
def __init__(self, config, has_visual_segment_embedding=True):
super().__init__(config)
self.num_labels = config.num_labels
self.layoutlm = LayoutLMModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_l... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
@replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
bbox: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Opt... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
end_positions (`torch.Lo... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
Returns:
Example:
In the example below, we prepare a question + context pair for the LayoutLM model. It will give us a prediction
of what it thinks the answer is (the span of the answer within the texts parsed from the image).
```python
>>> from transformers import AutoTokeniz... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
>>> encoding = tokenizer(
... question.split(), words, is_split_into_words=True, return_token_type_ids=True, return_tensors="pt"
... )
>>> bbox = []
>>> for i, s, w in zip(encoding.input_ids[0], encoding.sequence_ids(0), encoding.word_ids(0)):
... if s == 1:
... ... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.layoutlm(
input_ids=input_ids,
bbox=bbox,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_ma... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
... | 9,619 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/layoutlm/modeling_layoutlm.py |
class Owlv2ImageProcessor(BaseImageProcessor):
r"""
Constructs an OWLv2 image processor. | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Args:
do_rescale (`bool`, *optional*, defaults to `True`):
Whether to rescale the image by the specified scale `rescale_factor`. Can be overriden by `do_rescale` in
the `preprocess` method.
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
Scale fact... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Size to resize the image to. Can be overriden by `size` in the `preprocess` method.
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
Resampling method to use if resizing the image. Can be overriden by `resample` in the `preprocess` method.
do_normalize (`bool`,... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
""" | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
model_input_names = ["pixel_values"]
def __init__(
self,
do_rescale: bool = True,
rescale_factor: Union[int, float] = 1 / 255,
do_pad: bool = True,
do_resize: bool = True,
size: Dict[str, int] = None,
resample: PILImageResampling = PILImageResampling.BILINEAR... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
def pad(
self,
image: np.array,
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
):
"""
Pad an image to a square with gray pixels on the bottom and the right, as per the original OWLv2
... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Args:
image (`np.ndarray`):
Image to pad.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *option... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
def resize(
self,
image: np.ndarray,
size: Dict[str, int],
anti_aliasing: bool = True,
anti_aliasing_sigma=None,
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Dictionary containing the height and width to resize the image to.
anti_aliasing (`bool`, *optional*, defaults to `True`):
Whether to apply anti-aliasing when downsam... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
output_shape = (size["height"], size["width"])
image = to_channel_dimension_format(image, ChannelDimension.LAST)
image, output_shape = _preprocess_resize_output_shape(image, output_shape)
input_shape = image.shape
factors = np.divide(input_shape, output_shape) | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
# Translate modes used by np.pad to those used by scipy.ndimage
ndi_mode = "mirror"
cval = 0
order = 1
if anti_aliasing:
if anti_aliasing_sigma is None:
anti_aliasing_sigma = np.maximum(0, (factors - 1) / 2)
else:
anti_aliasing_sigm... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
zoom_factors = [1 / f for f in factors]
out = ndi.zoom(filtered, zoom_factors, order=order, mode=ndi_mode, cval=cval, grid_mode=True)
image = _clip_warp_output(image, out)
image = to_channel_dimension_format(image, input_data_format, ChannelDimension.LAST)
image = (
to_chan... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
@filter_out_non_signature_kwargs()
def preprocess(
self,
images: ImageInput,
do_pad: bool = None,
do_resize: bool = None,
size: Dict[str, int] = None,
do_rescale: bool = None,
rescale_factor: float = None,
do_normalize: bool = None,
image_mean:... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.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_pad (`bool`, *optional*, defaults to `self.do_pad`):
... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
Image mean.
image_std (`float` or `List[float]`, *optional*, defaults to `self.ima... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_las... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
"""
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
do_pad = do_pad if do_pad is not None else self.do_pad... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
size = size if size is not None else self.size
size = get_size_dict(size) # for BC
images = make_list_of_images(images)
if not valid_images(images):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tens... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
# All transformations expect numpy arrays.
images = [to_numpy_array(image) for image in images]
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 pi... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
if do_resize:
images = [
self.resize(
image=image,
size=size,
input_data_format=input_data_format,
)
for image in images
]
if do_normalize:
images = [
... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
# Copied from transformers.models.owlvit.image_processing_owlvit.OwlViTImageProcessor.post_process_object_detection with OwlViT->Owlv2
def post_process_object_detection(
self,
outputs: "Owlv2ObjectDetectionOutput",
threshold: float = 0.1,
target_sizes: Optional[Union[TensorType, List... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Args:
outputs ([`Owlv2ObjectDetectionOutput`]):
Raw outputs of the model.
threshold (`float`, *optional*, defaults to 0.1):
Score threshold to keep object detection predictions.
target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Returns:
`List[Dict]`: A list of dictionaries, each dictionary containing the following keys:
- "scores": The confidence scores for each predicted box on the image.
- "labels": Indexes of the classes predicted by the model on the image.
- "boxes": Image bounding boxes in ... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
# Convert to [x0, y0, x1, y1] format
batch_boxes = center_to_corners_format(batch_boxes)
# Convert from relative [0, 1] to absolute [0, height] coordinates
if target_sizes is not None:
batch_boxes = _scale_boxes(batch_boxes, target_sizes)
results = []
for scores, la... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Args:
outputs ([`OwlViTImageGuidedObjectDetectionOutput`]):
Raw outputs of the model.
threshold (`float`, *optional*, defaults to 0.0):
Minimum confidence threshold to use to filter out predicted boxes.
nms_threshold (`float`, *optional*, defaults to 0... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
Returns:
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
in the batch as predicted by the model. All labels are set to None as
`OwlViTForObjectDetection.image_guided_detection` perform one-shot object detection.
"""
... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
# Apply non-maximum suppression (NMS)
if nms_threshold < 1.0:
for idx in range(target_boxes.shape[0]):
for i in torch.argsort(-scores[idx]):
if not scores[idx][i]:
continue
ious = box_iou(target_boxes[idx][i, :].unsquee... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
# Apply threshold on scores before scaling
query_scores[query_scores < threshold] = 0.0
# Scale box alpha such that the best box for each query has alpha 1.0 and the worst box has alpha 0.1.
# All other boxes will either belong to a different query, or will not be shown.
... | 9,620 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/image_processing_owlv2.py |
class Owlv2Processor(ProcessorMixin):
r"""
Constructs an Owlv2 processor which wraps [`Owlv2ImageProcessor`] and [`CLIPTokenizer`]/[`CLIPTokenizerFast`] into
a single processor that interits both the image processor and tokenizer functionalities. See the
[`~OwlViTProcessor.__call__`] and [`~OwlViTProces... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
# Copied from transformers.models.owlvit.processing_owlvit.OwlViTProcessor.__call__ with OwlViT->Owlv2
def __call__(self, text=None, images=None, query_images=None, padding="max_length", return_tensors="np", **kwargs):
"""
Main method to prepare for the model one or several text(s) and image(s). Thi... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
Args:
text (`str`, `List[str]`, `List[List[str]]`):
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
`is_sp... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image
should be of shape (C, H, W), where C is a number of channels, H and W are image height and width.
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will ... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
`None`).
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
""" | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
if text is None and query_images is None and images is None:
raise ValueError(
"You have to specify at least one text or query image or image. All three cannot be none."
)
if text is not None:
if isinstance(text, str) or (isinstance(text, List) and not isinst... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
encoding = self.tokenizer(t, padding=padding, return_tensors=return_tensors, **kwargs)
encodings.append(encoding)
else:
raise TypeError("Input text should be a string, a list of strings or a nested list of strings")
if return_tensors == "np":
... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
input_ids = torch.cat([encoding["input_ids"] for encoding in encodings], dim=0)
attention_mask = torch.cat([encoding["attention_mask"] for encoding in encodings], dim=0)
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
input_ids = t... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
if query_images is not None:
encoding = BatchEncoding()
query_pixel_values = self.image_processor(
query_images, return_tensors=return_tensors, **kwargs
).pixel_values
encoding["query_pixel_values"] = query_pixel_values
if images is not None:
... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
# Copied from transformers.models.owlvit.processing_owlvit.OwlViTProcessor.post_process_object_detection with OwlViT->Owlv2
def post_process_object_detection(self, *args, **kwargs):
"""
This method forwards all its arguments to [`Owlv2ImageProcessor.post_process_object_detection`]. Please refer
... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
# Copied from transformers.models.owlvit.processing_owlvit.OwlViTProcessor.post_process_grounded_object_detection with OwlViT->Owlv2
def post_process_grounded_object_detection(
self,
outputs: "Owlv2ObjectDetectionOutput",
threshold: float = 0.1,
target_sizes: Optional[Union[TensorTyp... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
Args:
outputs ([`Owlv2ObjectDetectionOutput`]):
Raw outputs of the model.
threshold (`float`, *optional*, defaults to 0.1):
Score threshold to keep object detection predictions.
target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
Returns:
`List[Dict]`: A list of dictionaries, each dictionary containing the following keys:
- "scores": The confidence scores for each predicted box on the image.
- "labels": Indexes of the classes predicted by the model on the image.
- "boxes": Image bounding boxes in ... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
# adding text labels to the output
if text_labels is not None:
for image_output, image_text_labels in zip(output, text_labels):
object_text_labels = [image_text_labels[i] for i in image_output["labels"]]
image_output["text_labels"] = object_text_labels
else:
... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
Args:
outputs ([`Owlv2ImageGuidedObjectDetectionOutput`]):
Raw outputs of the model.
threshold (`float`, *optional*, defaults to 0.0):
Minimum confidence threshold to use to filter out predicted boxes.
nms_threshold (`float`, *optional*, defaults to 0.... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
Returns:
`List[Dict]`: A list of dictionaries, each dictionary containing the following keys:
- "scores": The confidence scores for each predicted box on the image.
- "boxes": Image bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format.
- "labe... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
# Copied from transformers.models.owlvit.processing_owlvit.OwlViTProcessor.decode
def decode(self, *args, **kwargs):
"""
This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
the docstring of this method for more information.
"... | 9,621 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/processing_owlv2.py |
class Owlv2TextConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of an [`Owlv2TextModel`]. It is used to instantiate an
Owlv2 text encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will y... | 9,622 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
Args:
vocab_size (`int`, *optional*, defaults to 49408):
Vocabulary size of the OWLv2 text model. Defines the number of different tokens that can be represented
by the `inputs_ids` passed when calling [`Owlv2TextModel`].
hidden_size (`int`, *optional*, defaults to 512):
... | 9,622 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
The non-linear activation function (function or string) in the en... | 9,622 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
testing).
pad_token_id (`int`, *optional*, defaults to 0):
The id of the padding token in the input sequences.
bos_token_id (`int`, *optional*, defaults to 49406):
T... | 9,622 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
Example:
```python
>>> from transformers import Owlv2TextConfig, Owlv2TextModel
>>> # Initializing a Owlv2TextModel with google/owlv2-base-patch16 style configuration
>>> configuration = Owlv2TextConfig()
>>> # Initializing a Owlv2TextConfig from the google/owlv2-base-patch16 style configuration
... | 9,622 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
def __init__(
self,
vocab_size=49408,
hidden_size=512,
intermediate_size=2048,
num_hidden_layers=12,
num_attention_heads=8,
max_position_embeddings=16,
hidden_act="quick_gelu",
layer_norm_eps=1e-5,
attention_dropout=0.0,
initializer... | 9,622 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.max_position_embeddings = max_position_embeddings
self.hidden_act = hidden... | 9,622 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
class Owlv2VisionConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of an [`Owlv2VisionModel`]. It is used to instantiate
an OWLv2 image encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults w... | 9,623 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
Args:
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
num_hidd... | 9,623 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the layer normalization layers.
a... | 9,623 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
Example:
```python
>>> from transformers import Owlv2VisionConfig, Owlv2VisionModel
>>> # Initializing a Owlv2VisionModel with google/owlv2-base-patch16 style configuration
>>> configuration = Owlv2VisionConfig()
>>> # Initializing a Owlv2VisionModel model from the google/owlv2-base-patch16 style... | 9,623 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_channels = num_channels
self.image_size = image_size
self.patch_size = patch_size
self.hidd... | 9,623 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
class Owlv2Config(PretrainedConfig):
r"""
[`Owlv2Config`] is the configuration class to store the configuration of an [`Owlv2Model`]. It is used to
instantiate an OWLv2 model according to the specified arguments, defining the text model and vision model
configs. Instantiating a configuration with the de... | 9,624 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
Args:
text_config (`dict`, *optional*):
Dictionary of configuration options used to initialize [`Owlv2TextConfig`].
vision_config (`dict`, *optional*):
Dictionary of configuration options used to initialize [`Owlv2VisionConfig`].
projection_dim (`int`, *optional*, default... | 9,624 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
def __init__(
self,
text_config=None,
vision_config=None,
projection_dim=512,
logit_scale_init_value=2.6592,
return_dict=True,
**kwargs,
):
super().__init__(**kwargs)
if text_config is None:
text_config = {}
logger.info... | 9,624 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
@classmethod
def from_text_vision_configs(cls, text_config: Dict, vision_config: Dict, **kwargs):
r"""
Instantiate a [`Owlv2Config`] (or a derived class) from owlv2 text model configuration and owlv2 vision
model configuration.
Returns:
[`Owlv2Config`]: An instance of a ... | 9,624 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/configuration_owlv2.py |
class Owlv2Output(ModelOutput):
"""
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
Contrastive loss for image-text similarity.
logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
The ... | 9,625 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
The image embeddings obtained by applying the projection layer to the pooled output of
[`Owlv2VisionModel`].
text_model_output (Tuple[`BaseModelOutputWithPooling`]):
The output of the [`Owlv2TextModel`].
vision_model_output (`BaseModelOutputWithPooling`):
The output o... | 9,625 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
loss: Optional[torch.FloatTensor] = None
logits_per_image: torch.FloatTensor = None
logits_per_text: torch.FloatTensor = None
text_embeds: torch.FloatTensor = None
image_embeds: torch.FloatTensor = None
text_model_output: BaseModelOutputWithPooling = None
vision_model_output: BaseModelOutputWith... | 9,625 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
class Owlv2ObjectDetectionOutput(ModelOutput):
"""
Output type of [`Owlv2ForObjectDetection`]. | 9,626 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
bounding box loss. The latter is defined as a linear combination of the L1 loss and... | 9,626 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
possible padding). You can use [`~Owlv2ImageProcessor.post_process_object_detection`] ... | 9,626 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
Class embeddings of all image patches. OWLv2 represents images as a set of image patches where the total
number of patches is (image_size / patch_size)**2.
text_model_output (Tuple[`BaseModelOutputWithPooling`]):
The output of the [`Owlv2TextModel`].
vision_model_output (`BaseMod... | 9,626 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
loss: Optional[torch.FloatTensor] = None
loss_dict: Optional[Dict] = None
logits: torch.FloatTensor = None
objectness_logits: torch.FloatTensor = None
pred_boxes: torch.FloatTensor = None
text_embeds: torch.FloatTensor = None
image_embeds: torch.FloatTensor = None
class_embeds: torch.FloatTe... | 9,626 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
class Owlv2ImageGuidedObjectDetectionOutput(ModelOutput):
"""
Output type of [`Owlv2ForObjectDetection.image_guided_detection`]. | 9,627 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
Args:
logits (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`):
Classification logits (including no-object) for all queries.
target_pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`):
Normalized boxes coordinates for all queries, repres... | 9,627 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
(disregarding possible padding). You can use [`~Owlv2ImageProcessor.post_process_object_detection`] to
retrieve the unnormalized bounding boxes.
image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
Pooled output of [`Owlv2VisionModel`]. OWLv2 rep... | 9,627 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
text_model_output (Tuple[`BaseModelOutputWithPooling`]):
The output of the [`Owlv2TextModel`].
vision_model_output (`BaseModelOutputWithPooling`):
The output of the [`Owlv2VisionModel`].
""" | 9,627 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
logits: torch.FloatTensor = None
image_embeds: torch.FloatTensor = None
query_image_embeds: torch.FloatTensor = None
target_pred_boxes: torch.FloatTensor = None
query_pred_boxes: torch.FloatTensor = None
class_embeds: torch.FloatTensor = None
text_model_output: BaseModelOutputWithPooling = None
... | 9,627 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
class Owlv2VisionEmbeddings(nn.Module):
def __init__(self, config: Owlv2VisionConfig):
super().__init__()
self.patch_size = config.patch_size
self.config = config
self.embed_dim = config.hidden_size
self.class_embedding = nn.Parameter(torch.randn(config.hidden_size))
... | 9,628 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings.interpolate_pos_encoding
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
"""
This method allows to interpolate the pre-trained position encodings, to be able to use the mo... | 9,628 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
return self.position_embedding(self.position_ids)
class_pos_embed = position_embedding[:, :1]
patch_pos_e... | 9,628 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
batch_size, _, height, width = pixel_values.shape
patch_embeds = self.patch_embedding(pixel_values) # shape = [batch_size, num_cha... | 9,628 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
class Owlv2TextEmbeddings(nn.Module):
def __init__(self, config: Owlv2TextConfig):
super().__init__()
self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
self.position_embedding = nn.Embedding(config.max_position_embeddings, config.hidden_size)
# position_ids ... | 9,629 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
if inputs_embeds is None:
inputs_embeds = self.token_embedding(input_ids)
position_embeddings = self.position_embedding(position_ids)
embeddings = inputs_embeds + position_embeddings
return embeddings | 9,629 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
class Owlv2Attention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.e... | 9,630 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
causal_attention_mask: ... | 9,630 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
key_states = key_states.view(*proj_shape)
value_states = value_states.view(*proj_shape)
src_len = key_states.size(1)
attn_weights = torch.bmm(query_sta... | 9,630 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
# apply the causal_attention_mask first
if causal_attention_mask is not None:
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
f" {causal_a... | 9,630 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
if attention_mask is not None:
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights.view(bsz, se... | 9,630 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
if output_attentions:
# this operation is a bit akward, 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_weight... | 9,630 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/owlv2/modeling_owlv2.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.