The YOLOS model was proposed in You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu. YOLOS proposes to just leverage the plain Vision Transformer (ViT) for object detection, inspired by DETR. It turns out that a base-sized encoder-only Transformer can also achieve 42 AP on COCO, similar to DETR and much more complex frameworks such as Faster R-CNN.
The abstract from the paper is the following:
Can Transformer perform 2D object- and region-level recognition from a pure sequence-to-sequence perspective with minimal knowledge about the 2D spatial structure? To answer this question, we present You Only Look at One Sequence (YOLOS), a series of object detection models based on the vanilla Vision Transformer with the fewest possible modifications, region priors, as well as inductive biases of the target task. We find that YOLOS pre-trained on the mid-sized ImageNet-1k dataset only can already achieve quite competitive performance on the challenging COCO object detection benchmark, e.g., YOLOS-Base directly adopted from BERT-Base architecture can obtain 42.0 box AP on COCO val. We also discuss the impacts as well as limitations of current pre-train schemes and model scaling strategies for Transformer in vision through YOLOS.
This model was contributed by nielsr. The original code can be found here.
A list of official Hugging Face and community (indicated by π) resources to help you get started with YOLOS.
If youβre interested in submitting a resource to be included here, please feel free to open a Pull Request and weβll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.
Use YolosImageProcessor for preparing images (and optional targets) for the model. Contrary to DETR, YOLOS doesnβt require a pixel_mask
to be created.
( hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-12 image_size = [512, 864] patch_size = 16 num_channels = 3 qkv_bias = True num_detection_tokens = 100 use_mid_position_embeddings = True auxiliary_loss = False class_cost = 1 bbox_cost = 5 giou_cost = 2 bbox_loss_coefficient = 5 giou_loss_coefficient = 2 eos_coefficient = 0.1 **kwargs )
Parameters
int
, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer. int
, optional, defaults to 12) —
Number of hidden layers in the Transformer encoder. int
, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer encoder. int
, optional, defaults to 3072) —
Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder. str
or function
, optional, defaults to "gelu"
) —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
,
"relu"
, "selu"
and "gelu_new"
are supported. float
, optional, defaults to 0.0) —
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. float
, optional, defaults to 0.0) —
The dropout ratio for the attention probabilities. float
, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices. float
, optional, defaults to 1e-12) —
The epsilon used by the layer normalization layers. List[int]
, optional, defaults to [512, 864]
) —
The size (resolution) of each image. int
, optional, defaults to 16) —
The size (resolution) of each patch. int
, optional, defaults to 3) —
The number of input channels. bool
, optional, defaults to True
) —
Whether to add a bias to the queries, keys and values. int
, optional, defaults to 100) —
The number of detection tokens. bool
, optional, defaults to True
) —
Whether to use the mid-layer position encodings. bool
, optional, defaults to False
) —
Whether auxiliary decoding losses (loss at each decoder layer) are to be used. float
, optional, defaults to 1) —
Relative weight of the classification error in the Hungarian matching cost. float
, optional, defaults to 5) —
Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost. float
, optional, defaults to 2) —
Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost. float
, optional, defaults to 5) —
Relative weight of the L1 bounding box loss in the object detection loss. float
, optional, defaults to 2) —
Relative weight of the generalized IoU loss in the object detection loss. float
, optional, defaults to 0.1) —
Relative classification weight of the ‘no-object’ class in the object detection loss. This is the configuration class to store the configuration of a YolosModel. It is used to instantiate a YOLOS model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the YOLOS hustvl/yolos-base architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Example:
>>> from transformers import YolosConfig, YolosModel
>>> # Initializing a YOLOS hustvl/yolos-base style configuration
>>> configuration = YolosConfig()
>>> # Initializing a model (with random weights) from the hustvl/yolos-base style configuration
>>> model = YolosModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
( format: Union = <AnnotationFormat.COCO_DETECTION: 'coco_detection'> do_resize: bool = True size: Dict = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 do_normalize: bool = True image_mean: Union = None image_std: Union = None do_convert_annotations: Optional = None do_pad: bool = True **kwargs )
Parameters
str
, optional, defaults to "coco_detection"
) —
Data format of the annotations. One of “coco_detection” or “coco_panoptic”. bool
, optional, defaults to True
) —
Controls whether to resize the image’s (height, width) dimensions to the specified size
. Can be
overridden by the do_resize
parameter in the preprocess
method. Dict[str, int]
optional, defaults to {"shortest_edge" -- 800, "longest_edge": 1333}
):
Size of the image’s (height, width) dimensions after resizing. Can be overridden by the size
parameter in
the preprocess
method. PILImageResampling
, optional, defaults to PILImageResampling.BILINEAR
) —
Resampling filter to use if resizing the image. bool
, optional, defaults to True
) —
Controls whether to rescale the image by the specified scale rescale_factor
. Can be overridden by the
do_rescale
parameter in the preprocess
method. int
or float
, optional, defaults to 1/255
) —
Scale factor to use if rescaling the image. Can be overridden by the rescale_factor
parameter in the
preprocess
method.
do_normalize —
Controls whether to normalize the image. Can be overridden by the do_normalize
parameter in the
preprocess
method. float
or List[float]
, optional, defaults to IMAGENET_DEFAULT_MEAN
) —
Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
channel. Can be overridden by the image_mean
parameter in the preprocess
method. float
or List[float]
, optional, defaults to IMAGENET_DEFAULT_STD
) —
Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
for each channel. Can be overridden by the image_std
parameter in the preprocess
method. bool
, optional, defaults to True
) —
Controls whether to pad the image. Can be overridden by the do_pad
parameter in the preprocess
method. If True
will pad the images in the batch to the largest height and width in the batch.
Padding will be applied to the bottom and right of the image with zeros. Constructs a Detr image processor.
( images: Union annotations: Union = None return_segmentation_masks: bool = None masks_path: Union = None do_resize: Optional = None size: Optional = None resample = None do_rescale: Optional = None rescale_factor: Union = None do_normalize: Optional = None image_mean: Union = None image_std: Union = None do_convert_annotations: Optional = None do_pad: Optional = None format: Union = None return_tensors: Union = None data_format: Union = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None **kwargs )
Parameters
ImageInput
) —
Image or batch of images 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
. AnnotationType
or List[AnnotationType]
, optional) —
List of annotations associated with the image or batch of images. If annotation is for object
detection, the annotations should be a dictionary with the following keys:int
): The image id.List[Dict]
): List of annotations for an image. Each annotation should be a
dictionary. An image can have no annotations, in which case the list should be empty.
If annotation is for segmentation, the annotations should be a dictionary with the following keys:int
): The image id.List[Dict]
): List of segments for an image. Each segment should be a dictionary.
An image can have no segments, in which case the list should be empty.str
): The file name of the image.bool
, optional, defaults to self.return_segmentation_masks) —
Whether to return segmentation masks. str
or pathlib.Path
, optional) —
Path to the directory containing the segmentation masks. bool
, optional, defaults to self.do_resize) —
Whether to resize the image. Dict[str, int]
, optional, defaults to self.size) —
Size of the image after resizing. PILImageResampling
, optional, defaults to self.resample) —
Resampling filter to use when resizing the image. bool
, optional, defaults to self.do_rescale) —
Whether to rescale the image. float
, optional, defaults to self.rescale_factor) —
Rescale factor to use when rescaling the image. bool
, optional, defaults to self.do_normalize) —
Whether to normalize the image. float
or List[float]
, optional, defaults to self.image_mean) —
Mean to use when normalizing the image. float
or List[float]
, optional, defaults to self.image_std) —
Standard deviation to use when normalizing the image. bool
, optional, defaults to self.do_convert_annotations) —
Whether to convert the annotations to the format expected by the model. Converts the bounding
boxes from the format (top_left_x, top_left_y, width, height)
to (center_x, center_y, width, height)
and in relative coordinates. bool
, optional, defaults to self.do_pad) —
Whether to pad the image. If True
will pad the images in the batch to the largest image in the batch
and create a pixel mask. Padding will be applied to the bottom and right of the image with zeros. str
or AnnotationFormat
, optional, defaults to self.format) —
Format of the annotations. str
or TensorType
, optional, defaults to self.return_tensors) —
Type of tensors to return. If None
, will return the list of images. str
or ChannelDimension
, optional, defaults to self.data_format) —
The channel dimension format of the image. If not provided, it will be the same as the input image. ChannelDimension
or str
, optional) —
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 ChannelDimension.LAST
: image in (height, width, num_channels) format."none"
or ChannelDimension.NONE
: image in (height, width) format.Preprocess an image or a batch of images so that it can be used by the model.
( images: List annotations: Optional = None constant_values: Union = 0 return_pixel_mask: bool = False return_tensors: Union = None data_format: Optional = None input_data_format: Union = None update_bboxes: bool = True )
Parameters
np.ndarray
) —
Image to pad. List[Dict[str, any]]
, optional) —
Annotations to pad along with the images. If provided, the bounding boxes will be updated to match the
padded images. float
or Iterable[float]
, optional) —
The value to use for the padding if mode
is "constant"
. bool
, optional, defaults to True
) —
Whether to return a pixel mask. str
or TensorType
, optional) —
The type of tensors to return. Can be one of:np.ndarray
.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 jax.numpy.ndarray
.str
or ChannelDimension
, optional) —
The channel dimension format of the image. If not provided, it will be the same as the input image. ChannelDimension
or str
, optional) —
The channel dimension format of the input image. If not provided, it will be inferred. bool
, optional, defaults to True
) —
Whether to update the bounding boxes in the annotations to match the padded images. If the
bounding boxes have not been converted to relative coordinates and (centre_x, centre_y, width, height)
format, the bounding boxes will not be updated. Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width in the batch and optionally returns their corresponding pixel mask.
( outputs threshold: float = 0.5 target_sizes: Union = None ) β List[Dict]
Parameters
YolosObjectDetectionOutput
) —
Raw outputs of the model. float
, optional) —
Score threshold to keep object detection predictions. torch.Tensor
or List[Tuple[int, int]]
, optional) —
Tensor of shape (batch_size, 2)
or list of tuples (Tuple[int, int]
) containing the target size
(height, width)
of each image in the batch. If unset, predictions will not be resized. 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.
Converts the raw output of YolosForObjectDetection into final bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
Preprocess an image or a batch of images.
( images: List annotations: Optional = None constant_values: Union = 0 return_pixel_mask: bool = False return_tensors: Union = None data_format: Optional = None input_data_format: Union = None update_bboxes: bool = True )
Parameters
np.ndarray
) —
Image to pad. List[Dict[str, any]]
, optional) —
Annotations to pad along with the images. If provided, the bounding boxes will be updated to match the
padded images. float
or Iterable[float]
, optional) —
The value to use for the padding if mode
is "constant"
. bool
, optional, defaults to True
) —
Whether to return a pixel mask. str
or TensorType
, optional) —
The type of tensors to return. Can be one of:np.ndarray
.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 jax.numpy.ndarray
.str
or ChannelDimension
, optional) —
The channel dimension format of the image. If not provided, it will be the same as the input image. ChannelDimension
or str
, optional) —
The channel dimension format of the input image. If not provided, it will be inferred. bool
, optional, defaults to True
) —
Whether to update the bounding boxes in the annotations to match the padded images. If the
bounding boxes have not been converted to relative coordinates and (centre_x, centre_y, width, height)
format, the bounding boxes will not be updated. Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width in the batch and optionally returns their corresponding pixel mask.
( outputs threshold: float = 0.5 target_sizes: Union = None ) β List[Dict]
Parameters
YolosObjectDetectionOutput
) —
Raw outputs of the model. float
, optional) —
Score threshold to keep object detection predictions. torch.Tensor
or List[Tuple[int, int]]
, optional) —
Tensor of shape (batch_size, 2)
or list of tuples (Tuple[int, int]
) containing the target size
(height, width)
of each image in the batch. If unset, predictions will not be resized. 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.
Converts the raw output of YolosForObjectDetection into final bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
( config: YolosConfig add_pooling_layer: bool = True )
Parameters
The bare YOLOS Model transformer outputting raw hidden-states without any specific head on top. This model is a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( pixel_values: Optional = None head_mask: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) β transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel values. Pixel values can be obtained using AutoImageProcessor. See
YolosImageProcessor.call() for details. torch.FloatTensor
of shape (num_heads,)
or (num_layers, num_heads)
, optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]
:
bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. Returns
transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (YolosConfig) and inputs.
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 model.
pooler_output (torch.FloatTensor
of shape (batch_size, hidden_size)
) β Last layer hidden-state of the first token of the sequence (classification token) after further processing
through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns
the classification token after processing through a linear layer and a tanh activation function. The linear
layer weights are trained from the next sentence prediction (classification) objective during pretraining.
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) β Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the optional 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 layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The YolosModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example:
>>> from transformers import AutoImageProcessor, YolosModel
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-small")
>>> model = YolosModel.from_pretrained("hustvl/yolos-small")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 3401, 384]
( config: YolosConfig )
Parameters
YOLOS Model (consisting of a ViT encoder) with object detection heads on top, for tasks such as COCO detection.
This model is a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( pixel_values: FloatTensor labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) β transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel values. Pixel values can be obtained using AutoImageProcessor. See
YolosImageProcessor.call() for details. torch.FloatTensor
of shape (num_heads,)
or (num_layers, num_heads)
, optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]
:
bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. List[Dict]
of len (batch_size,)
, optional) —
Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
following 2 keys: 'class_labels'
and 'boxes'
(the class labels and bounding boxes of an image in the
batch respectively). The class labels themselves should be a torch.LongTensor
of len (number of bounding boxes in the image,)
and the boxes a torch.FloatTensor
of shape (number of bounding boxes in the image, 4)
. Returns
transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutput
or tuple(torch.FloatTensor)
A transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (YolosConfig) and inputs.
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 the generalized
scale-invariant IoU loss.Dict
, optional) β A dictionary containing the individual losses. Useful for logging.torch.FloatTensor
of shape (batch_size, num_queries, num_classes + 1)
) β Classification logits (including no-object) for all queries.torch.FloatTensor
of shape (batch_size, num_queries, 4)
) β 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 post_process()
to retrieve the unnormalized bounding
boxes.list[Dict]
, optional) β Optional, only returned when auxilary losses are activated (i.e. config.auxiliary_loss
is set to True
)
and labels are provided. It is a list of dictionaries containing the two above keys (logits
and
pred_boxes
) for each decoder layer.torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) β Sequence of hidden-states at the output of the last layer of the decoder of the model.tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) β Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
. Hidden-states of
the model at the output of each layer plus the optional initial embedding outputs.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) β Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The YolosForObjectDetection forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> import torch
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-tiny")
>>> model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
... 0
... ]
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
... box = [round(i, 2) for i in box.tolist()]
... print(
... f"Detected {model.config.id2label[label.item()]} with confidence "
... f"{round(score.item(), 3)} at location {box}"
... )
Detected remote with confidence 0.994 at location [46.96, 72.61, 181.02, 119.73]
Detected remote with confidence 0.975 at location [340.66, 79.19, 372.59, 192.65]
Detected cat with confidence 0.984 at location [12.27, 54.25, 319.42, 470.99]
Detected remote with confidence 0.922 at location [41.66, 71.96, 178.7, 120.33]
Detected cat with confidence 0.914 at location [342.34, 21.48, 638.64, 372.46]