Skip to content

cofai.backbone

BackboneProtocol

Protocol defining the interface for backbone models.

decode

decode(h: Tensor, tasks: list[str]) -> torch.Tensor

Decode encoded features for downstream tasks.

Parameters:

Name Type Description Default
h Tensor

Encoded features from encode method, shape (B, N, C)

required
tasks list[str]

List of tasks to decode for, e.g. ["rec", "cls", "seg"]

required

Returns: task_feats (dict): Dictionary of task-specific features

encode

encode(x: Tensor) -> torch.Tensor

Encode input images to intermediate features.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W)

required

Returns:

Name Type Description
h Tensor

Encoded features of shape (B, N, C)

Dinov2OrgBackbone

Dinov2OrgBackbone(model_size='small', img_size=256, patch_size=16, dynamic_size=False, slot=-4, n_last_blocks=4, ckpt_path=None)

DINOv2 backbone using the original Facebook Research implementation.

This class extends the original DINOv2 model to provide flexible feature extraction. The slot parameter determines the splitting point for dividing the ViT blocks into:

  • encode part: blocks[:slot],
  • decode part: blocks[slot:]

Intermediate features are extracted after the encode part and before the decode part.

Parameters:

Name Type Description Default
model_size str

Model variant specification ('small', 'base', 'large', 'giant'). Defaults to 'small'.

'small'
img_size int

Base input image size. Defaults to 256.

256
patch_size int

Patch embedding size. Defaults to 16.

16
dynamic_size bool

Whether to support dynamically varying input sizes. Defaults to False.

False
slot int

Block slicing position for feature extraction. Follows Python list slicing conventions. -4 means the last 4th block. Defaults to -4.

-4
n_last_blocks int

Number of final blocks to utilize for feature aggregation. Defaults to 4.

4
ckpt_path str

Path to pre-trained checkpoint for initialization. Defaults to None.

None

decode

decode(h, token_res=None, task='whole')

Decode encoded features through the decoder part of the DINOv2 model.

Parameters:

Name Type Description Default
h Tensor

Encoded features from the encoder.

required
token_res tuple

Token resolution (H, W) for reshaping patch tokens. Defaults to None.

None
task str

Decoding task type. Must be one of:

  • "whole": Return full token sequences from multiple layers.
  • "cls": Return class tokens and patch tokens separately.
  • "seg": Return patch tokens reshaped to 2D spatial format. Defaults to "whole".
'whole'

Returns:

Name Type Description
feats list[Tensor, ...]

Decoded features, format depends on task.

encode

encode(x)

Encode input images through the encoder part of the DINOv2 model.

The encoding process applies input normalization, prepares tokens with masks, and processes the input through the first slot transformer blocks.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required

Returns:

Name Type Description
h Tensor

Encoded features after the encoder blocks.

forward

forward(x, task='whole')

Forward pass through the backbone.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required
task str

Task type, one of ["whole", "cls", "seg"]. Defaults to "whole".

'whole'

Returns:

Name Type Description
feats list[Tensor, ...]

Output features, format depends on task.

slide_decode_seg

slide_decode_seg(feature_list, slide_res)

Decode features from sliding window encoding for segmentation task.

Parameters:

Name Type Description Default
feature_list list

List of encoded features from slide_encode.

required
slide_res tuple

Token resolution (H, W) for each crop.

required

Returns:

Name Type Description
multi_crop_feats list[list[Tensor, ...]]

List of decoded segmentation features, one for each crop.

slide_encode

slide_encode(img, slide_window, slide_stride)

Encode images using sliding window approach.

This method extracts features from overlapping image crops using a sliding window strategy. Useful for processing large images that don't fit in memory or for extracting features at multiple scales.

Parameters:

Name Type Description Default
img Tensor

Input image of shape (B, 3, H_img, W_img).

required
slide_window tuple

Window size for cropping (h_crop, w_crop).

required
slide_stride tuple

Stride for sliding window (h_stride, w_stride).

required

Returns:

Name Type Description
multi_crop_feats list[Tensor]

List of encoded features, one for each crop.

Dinov2TimmBackbone

Dinov2TimmBackbone(model_size: str = 'small', img_size: int = 256, patch_size: int = 16, dynamic_size: bool = False, slot: int = -4, n_last_blocks: int = 4, ckpt_path: str = None, device: str = 'cuda' if torch.cuda.is_available() else 'cpu', cast_dtype: str = 'float', with_registers: bool = False, rae_decode_blocks: int | None = None)

DINOv2 backbone using timm library.

This class extends the DINOv2 model to provide flexible feature extraction. The DINOv2 backbone implemented with timm supports variable patch sizes and dynamic input image sizes. The slot parameter determines the splitting point for dividing the ViT blocks into:

  • encode part: blocks[:slot],
  • decode part: blocks[slot:]

Intermediate feature are extracted after the encode part and before the decode part.

Parameters:

Name Type Description Default
model_size str

Model variant specification ('small', 'base', 'large', 'giant'). Defaults to 'small'.

'small'
img_size int

Base input image size. Defaults to 256.

256
patch_size int

Patch embedding size. Defaults to 16.

16
dynamic_size bool

Whether to support dynamically varying input sizes. Defaults to False.

False
slot int or None

Block slicing position for feature extraction. Follows Python list slicing conventions. Defaults to -4.

-4
n_last_blocks int

Number of final blocks to utilize for feature aggregation. Defaults to 4.

4
ckpt_path str

Path to pre-trained checkpoint for initialization. Defaults to None.

None
cast_dtype str or dtype

Data type for autocast mixed precision. Supports string format like "torch.float", "torch.float16", "float32", etc. Defaults to "torch.float".

'float'
device str

Device to run the model on. Defaults to "cuda" if available, else "cpu".

'cuda' if is_available() else 'cpu'
with_registers bool

Whether to use register tokens in the model. Defaults to False.

False

decode

decode(h, token_res=None, task='whole')

Decode encoded features through the decoder part of the DINOv2 model.

Parameters:

Name Type Description Default
h Tensor

Encoded features from the encoder.

required
token_res tuple

Token resolution (H, W) for reshaping patch tokens. Defaults to None.

None
task str

Decoding task type. Must be one of:

  • "whole": Return full token sequences from multiple layers.
  • "cls": Return class tokens and patch tokens separately.
  • "seg": Return patch tokens reshaped to 2D spatial format. Defaults to "whole".
'whole'

Returns:

Name Type Description
feats list[Tensor, ...]

Decoded features, format depends on task.

decode_rae

decode_rae(h, token_res=None)

Decode encoded features for RAE decoder input.

By default this method follows the original MPCompress behavior: process the encoded features through the remaining transformer blocks and return final patch tokens. If rae_decode_blocks is configured, it instead runs exactly that many blocks after slot; 0 means using the encoder output directly.

It returns patch tokens without prefix tokens for RAE decoder. The input h should be the output from the encode method (after blocks[:slot]).

This method uses LayerNorm without learnable affine parameters (matching Dinov2TimmwithNorm with normalize=True). This equals to simple normalization.

encode

encode(x: Tensor) -> torch.Tensor

Encode input images through the encoder part of the DINOv2 model.

The encoding process applies input normalization, patch embedding, positional embedding, and processes the input through the first slot transformer blocks.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required

Returns:

Name Type Description
h Tensor

Encoded features after the encoder blocks, shape (B, N, C).

forward

forward(x, task='whole')

Forward pass through the backbone.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required
task str

Task type, one of ["whole", "cls", "seg"]. Defaults to "whole".

'whole'

Returns:

Name Type Description
feats list[Tensor]

Output features, format depends on task.

Dinov2TransformersBackbone

Dinov2TransformersBackbone(model_name: str = 'facebook/dinov2-base', img_size: int = 224, slot: int = -4, normalize: bool = True)

DINOv2 backbone using transformers library.

This backbone uses Dinov2Model or Dinov2WithRegistersModel from transformers library and provides encode/decode functionality for RAE.

Parameters:

Name Type Description Default
model_name str

HuggingFace model name, e.g., 'facebook/dinov2-base' or 'facebook/dinov2-with-registers-base'. Defaults to 'facebook/dinov2-base'.

'facebook/dinov2-base'
img_size int

Input image size. Defaults to 224.

224
slot int

Block slicing position for feature extraction. -4 means the last 4th block. -1 means use all blocks (matches old behavior). Defaults to -4.

-4
normalize bool

Whether to remove layernorm affine parameters (for RAE compatibility). Defaults to True.

True

encode

encode(x: Tensor) -> torch.Tensor

Encode input images through the DINOv2 encoder.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required

Returns:

Name Type Description
h Tensor

Encoded features, shape (B, N, C).

Dinov3FrozenTail

Dinov3FrozenTail(model: Module, split_layer_idx: int, rope: Any, attn_mask: Tensor | None = None)

RoPE-aware frozen tail for a split DINOv3 timm backbone.

forward_blocks

forward_blocks(x: Tensor) -> torch.Tensor

Run the frozen blocks without the final normalization.

forward_nograd

forward_nograd(x: Tensor) -> torch.Tensor

Run the teacher path without constructing an autograd graph.

train

train(mode: bool = True) -> FrozenTail

Keep the frozen teacher in evaluation mode.

Dinov3TimmBackbone

Dinov3TimmBackbone(model_size='large', img_size=256, patch_size=16, dynamic_size=False, slot=-4, n_last_blocks=4, device='cuda' if torch.cuda.is_available() else 'cpu', cast_dtype='float', qkvb=False, weights_tag='lvd1689m', return_registers=False, ckpt_path=None, pretrained=True)

DINOv3 backbone implemented with timm.

Key differences vs DINOv2
  • DINOv3 always includes register tokens
  • timm model names are fixed to patch16
  • model sizes include: large / huge_plus / 7b
  • qkvb is an explicit model variant

This class keeps the same encode/decode/slot abstraction as DINOv2 version.

build_frozen_tail

build_frozen_tail(layer_idx: int, token_hw: tuple[int, int], device: device | str) -> nn.Module

Build the frozen tail after layer_idx with spatial RoPE primed.

forward

forward(x, task='whole')
task
  • "whole": list of full token tensors
  • "cls": cls (+ optional reg) + patch tokens
  • "seg": patch tokens reshaped to 2D
  • "depth": patch tokens reshaped to 2D

FrozenTail

FrozenTail(blocks: Iterable[Module], norm_layer: Module)

Remaining token-sequence blocks followed by a normalization layer.

forward_blocks

forward_blocks(x: Tensor) -> torch.Tensor

Run the frozen blocks without the final normalization.

forward_nograd

forward_nograd(x: Tensor) -> torch.Tensor

Run the teacher path without constructing an autograd graph.

train

train(mode: bool = True) -> FrozenTail

Keep the frozen teacher in evaluation mode.

GPSTransReIDBackbone

GPSTransReIDBackbone(encoder: Module, global_decoder: Module, local_decoder: Module)

Adapt a released GPS TransReID model to the CoFAI backbone boundary.

GPS grouping remains inside the specialized multi-view TransReID encoder because it is interleaved with several Transformer blocks. The decoder preserves the checkpoint's global branch and four JPM local branches.

patches_per_view property

patches_per_view: int

Return the spatial token count produced for one input view.

token_grouper property writable

token_grouper

Return the grouping callable used inside the GPS Transformer.

MAETimmBackbone

MAETimmBackbone(model_name: str = 'vit_base_patch16_224.mae', img_size: int = 256, patch_size: int = 16, slot: int = -1, device: str = 'cuda' if torch.cuda.is_available() else 'cpu', cast_dtype: str = 'float')

MAE (Masked Autoencoder) backbone using timm library.

This backbone uses ViT-MAE from timm library and provides encode/decode functionality for RAE.

Available model names in timm
  • 'vit_base_patch16_224.mae' (default, standard MAE model)
  • 'vit_base_patch16_mae.in1k' (alternative naming)

Parameters:

Name Type Description Default
model_name str

Timm model name, e.g., 'vit_base_patch16_224.mae'. Defaults to 'vit_base_patch16_224.mae'.

'vit_base_patch16_224.mae'
img_size int

Input image size. Defaults to 256.

256
patch_size int

Patch embedding size. Defaults to 16.

16
slot int

Block slicing position for feature extraction. -1 means use all blocks. Defaults to -1.

-1
cast_dtype str or dtype

Data type for autocast mixed precision. Defaults to "float".

'float'
device str

Device to run the model on. Defaults to "cuda" if available, else "cpu".

'cuda' if is_available() else 'cpu'

encode

encode(x: Tensor) -> torch.Tensor

Encode input images through the MAE encoder.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required

Returns:

Name Type Description
h Tensor

Encoded features, shape (B, N, C).

MAETransformersBackbone

MAETransformersBackbone(model_name: str = 'facebook/vit-mae-base', img_size: int = 256, slot: int = -1)

MAE (Masked Autoencoder) backbone using transformers library.

This backbone uses ViTMAE from transformers library and provides encode/decode functionality for RAE.

Parameters:

Name Type Description Default
model_name str

HuggingFace model name, e.g., 'facebook/vit-mae-base'. Defaults to 'facebook/vit-mae-base'.

'facebook/vit-mae-base'
img_size int

Input image size. Defaults to 256.

256
slot int

Block slicing position for feature extraction. -1 means use all blocks. Defaults to -1.

-1

encode

encode(x: Tensor) -> torch.Tensor

Encode input images through the MAE encoder.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required

Returns:

Name Type Description
h Tensor

Encoded features, shape (B, N, C).

Qwen3VLBackbone

Qwen3VLBackbone(model_path: str = 'Qwen/Qwen3-VL-8B-Instruct', device: str = 'cuda' if torch.cuda.is_available() else 'cpu', default_prompt: str = '', local_files_only: bool = False, dtype: Union[str, dtype] = 'bfloat16', min_pixels: Optional[int] = 768 * 28 * 28, max_pixels: Optional[int] = 1536 * 28 * 28, max_new_tokens: int = 256, do_sample: bool = False, slot: Optional[int] = None)

Qwen3VL backbone using the transformers library.

Extracts and re-injects intermediate visual features from a Qwen3VL model, serving as the standard VLM backbone API in the CoFAI framework. The slot (breakpoint) is fixed to the first deepstack index of the visual encoder ("slot 9"), which is the mandatory breakpoint for this model.

The encode part (extract_features) runs visual.blocks[:slot] and returns token features (1, L, C). The decode part (decode_text) accepts the same layout (with token_res), runs the remaining blocks, collects deepstack features, and drives the language model to generate text.

Parameters:

Name Type Description Default
model_path str

HuggingFace model name or local path. Defaults to 'Qwen/Qwen3-VL-8B-Instruct'.

'Qwen/Qwen3-VL-8B-Instruct'
device str

Device to run the model on. Defaults to "cuda" if available, else "cpu".

'cuda' if is_available() else 'cpu'
default_prompt str

Fallback prompt used when none is supplied. Defaults to "".

''
local_files_only bool

Whether to load strictly from local cache. Defaults to False.

False
dtype str or dtype

Model weight dtype passed to from_pretrained. Accepts "auto", "bfloat16", "float16", etc., or a torch.dtype. Defaults to "bfloat16".

'bfloat16'
min_pixels int

Minimum pixels for image resizing in the processor. Defaults to 7682828.

768 * 28 * 28
max_pixels int

Maximum pixels for image resizing in the processor. Defaults to 15362828.

1536 * 28 * 28
max_new_tokens int

Default max new tokens for generation. Defaults to 256.

256
do_sample bool

Default sampling flag for generation. Defaults to False.

False
slot int

Encoder breakpoint, following timm slicing convention (encode=blocks[:slot], decode=blocks[slot:]); "slot N" is the feature after layer N-1, and slot may start from 0. Defaults to the first deepstack feature (slot 9, after layer 8), the latest valid breakpoint. A smaller slot is allowed; a larger one is rejected.

None

decode_text

decode_text(hidden_states: Tensor, prompt: Optional[str] = '', token_res: Optional[tuple[int, int]] = None, max_new_tokens: Optional[int] = None, do_sample: Optional[bool] = None, temperature: float = 1.0, what_to_return: str = 'string', **gen_kwargs)

Decode: continue the visual encoder from reconstructed features and generate text.

Accepts codec tokens (1, L, C) or flat (L, C). token_res=(H, W) is required so the visual grid metadata can be reconstructed.

Parameters:

Name Type Description Default
hidden_states Tensor

Reconstructed tokens, (1, L, C) or (L, C).

required
prompt str

The text prompt. Falls back to default_prompt if empty.

''
token_res tuple[int, int]

Token grid (H, W) with L=H*W.

None
max_new_tokens int

Max new tokens; falls back to the instance default self.max_new_tokens when None.

None
do_sample bool

Sampling flag; falls back to the instance default self.do_sample when None.

None
temperature float

Sampling temperature. Defaults to 1.0.

1.0
what_to_return str

"string" for decoded text, "ids" for token ids.

'string'
**gen_kwargs

Extra keyword arguments forwarded to model.generate.

{}

Returns:

Type Description

str or torch.Tensor: Generated text, or generated token ids.

encode_image

encode_image(image: Union[str, Image, Tensor]) -> tuple[torch.Tensor, tuple[int, int]]

Preprocess an image and extract breakpoint tokens plus grid shape.

Convenience wrapper around prepare_image + extract_features.

Returns:

Name Type Description
h_tokens Tensor

Token features, shape (1, L, C).

token_res tuple[int, int]

Token grid (H, W) with L = H * W.

extract_features

extract_features(pixel_values: Tensor, image_grid_thw: Tensor) -> torch.Tensor

Encode: run the visual encoder up to the breakpoint slot.

Runs visual.blocks[:slot] and returns encoder tokens in the same (B, L, C) layout used by :class:~cofai.models.base.DinoFeatureCodecModel (single-image eval uses B=1, L=H*W).

Parameters:

Name Type Description Default
pixel_values Tensor

Patch pixel values from prepare_image.

required
image_grid_thw Tensor

Grid (t, h, w) from prepare_image.

required

Returns:

Name Type Description
hidden_states Tensor

Token features, shape (1, L, C).

prepare_image

prepare_image(image: Union[str, Image, Tensor])

Preprocess one image into pixel_values and image_grid_thw.

Parameters:

Name Type Description Default
image Union[str, Image, Tensor]

Image path, PIL image, or CHW tensor. Batched tensors must contain exactly one image.

required

Returns:

Name Type Description
pixel_values Tensor

Flattened patch pixel values.

image_grid_thw Tensor

Grid (t, h, w) for the image.

SigLIP2TimmBackbone

SigLIP2TimmBackbone(model_name: str = 'vit_base_patch16_siglip_224', img_size: int = 224, patch_size: int = 16, slot: int = -1, device: str = 'cuda' if torch.cuda.is_available() else 'cpu', cast_dtype: str = 'float')

SigLIP2 backbone using timm library.

This backbone uses SigLIP2 from timm library and provides encode/decode functionality for RAE.

Available model names in timm
  • 'vit_base_patch16_siglip_224' (default, standard SigLIP model)
  • 'vit_base_patch16_siglip.in1k' (alternative naming)
  • 'vit_base_patch16_siglip_256' (alternative size)

Parameters:

Name Type Description Default
model_name str

Timm model name for SigLIP2. Defaults to 'vit_base_patch16_siglip_224'.

'vit_base_patch16_siglip_224'
img_size int

Input image size. Defaults to 224.

224
patch_size int

Patch embedding size. Defaults to 16.

16
slot int

Block slicing position for feature extraction. -1 means use all blocks. Defaults to -1.

-1
cast_dtype str or dtype

Data type for autocast mixed precision. Defaults to "float".

'float'
device str

Device to run the model on. Defaults to "cuda" if available, else "cpu".

'cuda' if is_available() else 'cpu'

encode

encode(x: Tensor) -> torch.Tensor

Encode input images through the SigLIP2 encoder.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required

Returns:

Name Type Description
h Tensor

Encoded features, shape (B, N, C).

SigLIP2TransformersBackbone

SigLIP2TransformersBackbone(model_name: str = 'google/siglip2-base-patch16-256', img_size: int = 256, slot: int = -1)

SigLIP2 backbone using transformers library.

This backbone uses SiglipModel from transformers library and provides encode/decode functionality for RAE.

Parameters:

Name Type Description Default
model_name str

HuggingFace model name, e.g., 'google/siglip2-base-patch16-256'. Defaults to 'google/siglip2-base-patch16-256'.

'google/siglip2-base-patch16-256'
img_size int

Input image size. Defaults to 256.

256
slot int

Block slicing position for feature extraction. -1 means use all blocks. Defaults to -1.

-1

encode

encode(x: Tensor) -> torch.Tensor

Encode input images through the SigLIP2 encoder.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W).

required

Returns:

Name Type Description
h Tensor

Encoded features, shape (B, N, C).

TransReIDJPMFeatures dataclass

TransReIDJPMFeatures(global_feature: Tensor, bottleneck_global_feature: Tensor, local_token_features: tuple[Tensor, ...])

Global and local features consumed by a TransReID JPM head.

VGGBackbone

VGGBackbone(device)

extract

extract(frame_bgr)

对应原 extract_vgg_feature 函数 输入: cv2 读取的 BGR 图片 (numpy array) 输出: [1, 512, 1, 1] 的 Tensor

VqganBackbone

VqganBackbone(**kwargs)

VQGAN-based backbone for image encoding and decoding.

This backbone uses a VQGAN (Vector Quantized Generative Adversarial Network) model to encode images into discrete tokens and decode them back to images. The encoding process converts images to latent codes and quantizes them using a codebook.

Parameters:

Name Type Description Default
vqgan_config dict

Configuration dictionary for the VQModel initialization.

required
**kwargs dict

Unused keyword arguments for API compatibility.

{}

Attributes:

Name Type Description
vqgan VQModel

The underlying VQGAN model.

codebook_size int

Size of the quantization codebook.

decode

decode(z_q)

Decode quantized latent codes back to images.

Parameters:

Name Type Description Default
z_q Tensor

Quantized latent codes of shape (B, C, H, W).

required

Returns:

Name Type Description
x_hat Tensor

Reconstructed images of shape (B, 3, H, W) in range [0, 1].

encode

encode(x)

Encode input images into latent codes and tokens.

The input images x are expected to be in the range [0, 1], which are then transformed to [-1, 1] for the VQGAN encoder. The encoder produces latent codes that are quantized using the codebook to produce discrete tokens. The quantization process produces z_q' = z + (z_q - z).detach(), which incurs a small MSE error (approximately 1e-18) between z_q' and z_q. We use z_q as the context for consistency.

Parameters:

Name Type Description Default
x Tensor

Input images of shape (B, 3, H, W) in range [0, 1].

required

Returns:

Name Type Description
vqgan_enc dict

A dictionary containing:

  • "z" (torch.Tensor): Continuous latent codes before quantization.
  • "z_q" (torch.Tensor): Quantized latent codes of shape (B, C, H, W).
  • "tokens" (torch.Tensor): Discrete token indices of shape (B, H, W).
  • "shape" (tuple): Spatial dimensions (H, W) of the latent representation.

tokens_to_features

tokens_to_features(tokens)

Convert discrete tokens to quantized latent features.

Parameters:

Name Type Description Default
tokens Tensor

Discrete token indices of shape (B, H, W).

required

Returns:

Name Type Description
z_q Tensor

Quantized latent features of shape (B, C, H, W).

extract_vgg_features

extract_vgg_features(vgg_model, frame_tensor)

提取VGG特征(与process_video并行执行) 参数: vgg_model: 预初始化的VGG特征提取器 frame_tensor: 输入图像张量 [1,3,H,W], 范围[0,1] 返回: features: 提取的特征向量 [1,C]

setup_vgg_feature_extractor

setup_vgg_feature_extractor(device='cuda')

初始化VGG16特征提取器