FocalNet

## [](#overview)Overview

The FocalNet model was proposed in [Focal Modulation Networks](https://arxiv.org/abs/2203.11926) by Jianwei Yang, Chunyuan Li, Xiyang Dai, Lu Yuan, Jianfeng Gao. FocalNets completely replace self-attention (used in models like [ViT](vit) and [Swin](swin)) by a focal modulation mechanism for modeling token interactions in vision. The authors claim that FocalNets outperform self-attention based models with similar computational costs on the tasks of image classification, object detection, and segmentation.

The abstract from the paper is the following:

_We propose focal modulation networks (FocalNets in short), where self-attention (SA) is completely replaced by a focal modulation mechanism for modeling token interactions in vision. Focal modulation comprises three components: (i) hierarchical contextualization, implemented using a stack of depth-wise convolutional layers, to encode visual contexts from short to long ranges, (ii) gated aggregation to selectively gather contexts for each query token based on its content, and (iii) element-wise modulation or affine transformation to inject the aggregated context into the query. Extensive experiments show FocalNets outperform the state-of-the-art SA counterparts (e.g., Swin and Focal Transformers) with similar computational costs on the tasks of image classification, object detection, and segmentation. Specifically, FocalNets with tiny and base size achieve 82.3% and 83.9% top-1 accuracy on ImageNet-1K. After pretrained on ImageNet-22K in 224 resolution, it attains 86.5% and 87.3% top-1 accuracy when finetuned with resolution 224 and 384, respectively. When transferred to downstream tasks, FocalNets exhibit clear superiority. For object detection with Mask R-CNN, FocalNet base trained with 1\\times outperforms the Swin counterpart by 2.1 points and already surpasses Swin trained with 3\\times schedule (49.0 v.s. 48.5). For semantic segmentation with UPerNet, FocalNet base at single-scale outperforms Swin by 2.4, and beats Swin at multi-scale (50.5 v.s. 49.7). Using large FocalNet and Mask2former, we achieve 58.5 mIoU for ADE20K semantic segmentation, and 57.9 PQ for COCO Panoptic Segmentation. Using huge FocalNet and DINO, we achieved 64.3 and 64.4 mAP on COCO minival and test-dev, respectively, establishing new SoTA on top of much larger attention-based models like Swinv2-G and BEIT-3._

Tips:

-   One can use the [AutoImageProcessor](/docs/transformers/v4.30.0/en/model_doc/auto#transformers.AutoImageProcessor) class to prepare images for the model.

This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/microsoft/FocalNet).

## [](#transformers.FocalNetConfig)FocalNetConfig

### class transformers.FocalNetConfig

[](#transformers.FocalNetConfig)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/focalnet/configuration_focalnet.py#L29)

( image\_size = 224patch\_size = 4num\_channels = 3embed\_dim = 96use\_conv\_embed = Falsehidden\_sizes = \[192, 384, 768, 768\]depths = \[2, 2, 6, 2\]focal\_levels = \[2, 2, 2, 2\]focal\_windows = \[3, 3, 3, 3\]hidden\_act = 'gelu'mlp\_ratio = 4.0hidden\_dropout\_prob = 0.0drop\_path\_rate = 0.1use\_layerscale = Falselayerscale\_value = 0.0001use\_post\_layernorm = Falseuse\_post\_layernorm\_in\_modulation = Falsenormalize\_modulator = Falseinitializer\_range = 0.02layer\_norm\_eps = 1e-05encoder\_stride = 32out\_features = Noneout\_indices = None\*\*kwargs )

This is the configuration class to store the configuration of a [FocalNetModel](/docs/transformers/v4.30.0/en/model_doc/focalnet#transformers.FocalNetModel). It is used to instantiate a FocalNet 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 FocalNet [microsoft/focalnet-tiny](https://huggingface.co/microsoft/focalnet-tiny) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Example:

```
>>> from transformers import FocalNetConfig, FocalNetModel

>>> 
>>> configuration = FocalNetConfig()

>>> 
>>> model = FocalNetModel(configuration)

>>> 
>>> configuration = model.config```

## [](#transformers.FocalNetModel)FocalNetModel

### class transformers.FocalNetModel

[](#transformers.FocalNetModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/focalnet/modeling_focalnet.py#L696)

( configadd\_pooling\_layer = Trueuse\_mask\_token = False )

Parameters

-   [](#transformers.FocalNetModel.config)**config** ([FocalNetConfig](/docs/transformers/v4.30.0/en/model_doc/focalnet#transformers.FocalNetConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The bare FocalNet Model outputting raw hidden-states without any specific head on top. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.FocalNetModel.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/focalnet/modeling_focalnet.py#L715)

( pixel\_values: typing.Optional\[torch.FloatTensor\] = Nonebool\_masked\_pos: typing.Optional\[torch.BoolTensor\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → `transformers.models.focalnet.modeling_focalnet.FocalNetModelOutput` or `tuple(torch.FloatTensor)`

The [FocalNetModel](/docs/transformers/v4.30.0/en/model_doc/focalnet#transformers.FocalNetModel) 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, FocalNetModel
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny")
>>> model = FocalNetModel.from_pretrained("microsoft/focalnet-tiny")

>>> 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, 49, 768]```

## [](#transformers.FocalNetForMaskedImageModeling)FocalNetForMaskedImageModeling

### class transformers.FocalNetForMaskedImageModeling

[](#transformers.FocalNetForMaskedImageModeling)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/focalnet/modeling_focalnet.py#L786)

( config )

Parameters

-   [](#transformers.FocalNetForMaskedImageModeling.config)**config** ([FocalNetConfig](/docs/transformers/v4.30.0/en/model_doc/focalnet#transformers.FocalNetConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

FocalNet Model with a decoder on top for masked image modeling.

This follows the same implementation as in [SimMIM](https://arxiv.org/abs/2111.09886).

Note that we provide a script to pre-train this model on custom data in our [examples directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.FocalNetForMaskedImageModeling.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/focalnet/modeling_focalnet.py#L804)

( pixel\_values: typing.Optional\[torch.FloatTensor\] = Nonebool\_masked\_pos: typing.Optional\[torch.BoolTensor\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → `transformers.models.focalnet.modeling_focalnet.FocalNetMaskedImageModelingOutput` or `tuple(torch.FloatTensor)`

The [FocalNetForMaskedImageModeling](/docs/transformers/v4.30.0/en/model_doc/focalnet#transformers.FocalNetForMaskedImageModeling) 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, FocalNetConfig, FocalNetForMaskedImageModeling
>>> 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("microsoft/focalnet-base-simmim-window6-192")
>>> config = FocalNetConfig()
>>> model = FocalNetForMaskedImageModeling(config)

>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> 
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()

>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.logits
>>> list(reconstructed_pixel_values.shape)
[1, 3, 192, 192]```

## [](#transformers.FocalNetForImageClassification)FocalNetForImageClassification

### class transformers.FocalNetForImageClassification

[](#transformers.FocalNetForImageClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/focalnet/modeling_focalnet.py#L894)

( config )

Parameters

-   [](#transformers.FocalNetForImageClassification.config)**config** ([FocalNetConfig](/docs/transformers/v4.30.0/en/model_doc/focalnet#transformers.FocalNetConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

FocalNet Model with an image classification head on top (a linear layer on top of the pooled output) e.g. for ImageNet.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.FocalNetForImageClassification.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/focalnet/modeling_focalnet.py#L910)

( pixel\_values: typing.Optional\[torch.FloatTensor\] = Nonelabels: typing.Optional\[torch.LongTensor\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → `transformers.models.focalnet.modeling_focalnet.FocalNetImageClassifierOutput` or `tuple(torch.FloatTensor)`

The [FocalNetForImageClassification](/docs/transformers/v4.30.0/en/model_doc/focalnet#transformers.FocalNetForImageClassification) 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, FocalNetForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny")
>>> model = FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny")

>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> 
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
tabby, tabby cat```