Transformers documentation
DINOv3
该模型于 2025-08-13 在 HF papers 上发布,并于 2025-08-14 贡献至 Hugging Face Transformers。
DINOv3
DINOv3 是一系列通用的视觉基础模型,在广泛的场景下无需微调即可超越专用领域的最先进水平。DINOv3 能够生成高质量的密集特征,在多种视觉任务上取得卓越性能,显著超越了以往的自监督及弱监督基础模型。
您可以在 DINOv3 集合中找到所有原始的 DINOv3 检查点。
点击右侧边栏中的 DINOv3 模型,以查看将 DINOv3 应用于不同视觉任务的更多示例。
以下示例演示了如何使用 Pipeline 或 AutoModel 类获取图像嵌入。
from transformers import pipeline
pipe = pipeline(
task="image-feature-extraction",
model="facebook/dinov3-vits16-pretrain-lvd1689m",
)
pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")import torch
from transformers import AutoImageProcessor, AutoModel
from transformers.image_utils import load_image
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = load_image(url)
processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vits16-pretrain-lvd1689m")
model = AutoModel.from_pretrained(
"facebook/dinov3-vits16-pretrain-lvd1689m",
device_map="auto",
attn_implementation="sdpa"
)
inputs = processor(images=image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
pooled_output = outputs.pooler_output
print("Pooled output shape:", pooled_output.shape)量化通过以较低精度表示权重来降低大模型的内存负担。有关更多可用的量化后端,请参阅 量化 概述。
以下示例使用 torchao 仅将权重量化为 int4。
# pip install torchao
import torch
from torchao.quantization import Int4WeightOnlyConfig
from transformers import AutoImageProcessor, AutoModel, TorchAoConfig
from transformers.image_utils import load_image
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = load_image(url)
processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vitsplus-pretrain-lvd1689m")
quant_type = Int4WeightOnlyConfig(group_size=128)
quantization_config = TorchAoConfig(quant_type=quant_type)
model = AutoModel.from_pretrained(
"facebook/dinov3-vit7b16-pretrain-lvd1689m",
device_map="auto",
quantization_config=quantization_config
)
inputs = processor(images=image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
pooled_output = outputs.pooler_output
print("Pooled output shape:", pooled_output.shape)备注
下面的示例展示了如何将输出张量拆分为:
- 整个图像的一个嵌入,通常称为
CLS标记, 适用于分类和检索 - register tokens - 可学习的嵌入,充当全局信息的专用“内存槽位”, 它们减少了 patch tokens 中的高范数伪影,从而生成更清晰的注意力图,并在密集预测任务上取得更好的性能。
- 一组局部嵌入,输入图像的每个
16x16图像块对应一个, 适用于语义分割等密集任务
import torch from transformers import AutoImageProcessor, AutoModel from transformers.image_utils import load_image url = "http://images.cocodataset.org/val2017/000000039769.jpg" image = load_image(url) print("Image size:", image.height, image.width) # [480, 640] processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vits16-pretrain-lvd1689m") model = AutoModel.from_pretrained("facebook/dinov3-vits16-pretrain-lvd1689m", device_map="auto") patch_size = model.config.patch_size print("Patch size:", patch_size) # 16 print("Num register tokens:", model.config.num_register_tokens) # 4 inputs = processor(images=image, return_tensors="pt").to(model.device) print("Preprocessed image size:", inputs.pixel_values.shape) # [1, 3, 224, 224] batch_size, _, img_height, img_width = inputs.pixel_values.shape num_patches_height, num_patches_width = img_height // patch_size, img_width // patch_size num_patches_flat = num_patches_height * num_patches_width with torch.inference_mode(): outputs = model(**inputs) last_hidden_states = outputs.last_hidden_state print(last_hidden_states.shape) # [1, 1 + 4 + 256, 384] assert last_hidden_states.shape == (batch_size, 1 + model.config.num_register_tokens + num_patches_flat, model.config.hidden_size) cls_token = last_hidden_states[:, 0, :] patch_features_flat = last_hidden_states[:, 1 + model.config.num_register_tokens:, :] patch_features = patch_features_flat.unflatten(1, (num_patches_height, num_patches_width))- 整个图像的一个嵌入,通常称为
DINOv3ViTConfig
class transformers.DINOv3ViTConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonepatch_size: int | list[int] | tuple[int, int] = 16hidden_size: int = 384intermediate_size: int = 1536num_hidden_layers: int = 12num_attention_heads: int = 6hidden_act: str = 'gelu'attention_dropout: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-05rope_theta: float = 100.0image_size: int | list[int] | tuple[int, int] = 224num_channels: int = 3query_bias: bool = Truekey_bias: bool = Falsevalue_bias: bool = Trueproj_bias: bool = Truemlp_bias: bool = Truelayerscale_value: float = 1.0drop_path_rate: float | int = 0.0use_gated_mlp: bool = Falsenum_register_tokens: int = 0pos_embed_shift: float | None = Nonepos_embed_jitter: float | None = Nonepos_embed_rescale: float | None = 2.0_out_features: list[str] | None = None_out_indices: list[int] | None = Noneapply_layernorm: bool = Truereshape_hidden_states: bool = True )
参数
- patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为16) — 每个 patch 的大小(分辨率)。 - hidden_size (
int,可选,默认为384) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为1536) — MLP 表示的维度。 - num_hidden_layers (
int, 可选, 默认为12) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为6) — Transformer 解码器中每个注意力层的注意力头数量。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-05) — 层归一化层所使用的 epsilon 值。 - rope_theta (
float,可选,默认为 100.0) — RoPE 嵌入的基础周期。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为224) — 每张图片的尺寸(分辨率)。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - query_bias (
bool,可选,默认为True) — 是否对查询投影添加偏置。 - key_bias (
bool,可选,默认为False) — 是否向键投影添加偏置。 - value_bias (
bool,可选,默认为True) — 是否对 value 投影添加偏置。 - proj_bias (
bool,可选,默认为True) — 是否向输出投影添加偏置。 - mlp_bias (
bool,可选,默认为True) — 是否在 MLP 层的 up_proj、down_proj 和 gate_proj 层中使用偏置。 - layerscale_value (
float,可选,默认为 1.0) — 用于 layer scale 的初始值。 - drop_path_rate (
Union[float, int],可选,默认为0.0) — 用于 patch fusion 的 drop path 比率。 - use_gated_mlp (
bool,可选,默认为False) — 是否使用 SwiGLU 前馈神经网络。 - num_register_tokens (
int,可选,默认为 0) — 注册 token 的数量。 - pos_embed_shift (
float, 可选) — 在 [-shift, shift] 范围内随机平移位置嵌入坐标的幅度,仅在训练模式下且不为None时生效。 - pos_embed_jitter (
float, 可选) — 以 [1/jitter, jitter] 范围内的对数均匀值随机抖动位置嵌入坐标的幅度,仅在训练模式下且不为None时生效。 - pos_embed_rescale (
float,可选,默认值为 2.0) — 在训练模式下(若不为None),对位置嵌入坐标进行随机重缩放的幅度,其值在 [1/rescale, rescale] 范围内按对数均匀分布采样。 - apply_layernorm (
bool,可选,默认为True) — 当用作 backbone 时,是否对特征图应用层归一化。 - reshape_hidden_states (
bool,可选,默认为True) — 当用作 backbone 时,是否将 hidden states 重塑为空间维度。
这是用于存储 DINOv3ViTModel 配置的类。它根据指定的参数实例化 Dinov3 Vit 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/dinov3-vits16-pretrain-lvd1689m 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import DINOv3ViTConfig, DINOv3ViTModel
>>> # Initializing a DINOv3 ViT-small style configuration
>>> config = DINOv3ViTConfig()
>>> # Initializing a model (with random weights) from the config
>>> model = DINOv3ViTModel(config)
>>> # Accessing the model config
>>> config = model.configDINOv3ConvNextConfig
class transformers.DINOv3ConvNextConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonenum_channels: int = 3hidden_sizes: list[int] | None = Nonedepths: list[int] | None = Nonehidden_act: str = 'gelu'initializer_range: float = 0.02layer_norm_eps: float = 1e-06layer_scale_init_value: float = 1e-06drop_path_rate: float | int = 0.0image_size: int | list[int] | tuple[int, int] = 224_out_features: list[str] | None = None_out_indices: list[int] | None = None )
参数
- num_channels (
int,可选,默认为3) — 输入通道的数量。 - hidden_sizes (
list[int], 可选) — 模型每个阶段的维度(隐藏层大小)。 - depths (
list[int],可选) — Transformer 中每一层的深度。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-06) — 层归一化层所使用的 epsilon 值。 - layer_scale_init_value (
float, 可选, 默认值为1e-06) — 用于自注意力层的缩放值。基础模型使用 0.1,大型模型使用 1e-6。设置为 0 可禁用 layer scale。 - drop_path_rate (
Union[float, int],可选,默认为0.0) — 用于 patch fusion 的 drop path 比率。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为224) — 每张图片的尺寸(分辨率)。
这是用于存储 DINOv3ConvNextModel 配置的类。它根据指定的参数实例化 Dinov3 Convnext 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/dinov3-convnext-tiny-pretrain-lvd1689m 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import DINOv3ConvNextConfig, DINOv3ConvNextModel
>>> # Initializing a DINOv3ConvNext (tiny variant) style configuration
>>> config = DINOv3ConvNextConfig()
>>> # Initializing a model (with random weights)
>>> model = DINOv3ConvNextModel(config)
>>> # Accessing the model config
>>> config = model.configDINOv3ViTModel
类 transformers.DINOv3ViTModel
< source >( config: DINOv3ViTConfig )
参数
- config (DINOv3ViTConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
原始的 Dinov3 Vit 模型,输出原始隐藏状态,顶部未添加任何特定的分类头。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorbool_masked_pos: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 DINOv3ViTImageProcessor 获取像素值。有关详细信息,请参阅 DINOv3ViTImageProcessor.call()(processor_class使用 DINOv3ViTImageProcessor 处理图像)。 - bool_masked_pos(形状为
(batch_size, sequence_length)的torch.BoolTensor)— 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。仅与预训练相关。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(DINOv3ViTConfig)和输入。
DINOv3ViTModel 的 forward 方法会重写 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
DINOv3ViTBackbone
class transformers.DINOv3ViTBackbone
< source >( config: DINOv3ViTConfig )
参数
- config (DINOv3ViTConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Dinov3 Vit 骨干网络。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DINOv3ViTBackboneOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 DINOv3ViTImageProcessor 获取像素值。有关详细信息,请参阅 DINOv3ViTImageProcessor.call()(processor_class使用 DINOv3ViTImageProcessor 处理图像)。
返回值
DINOv3ViTBackboneOutput 或 tuple(torch.Tensor)
DINOv3ViTBackboneOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(DINOv3ViTConfig)和输入。
DINOv3ViTBackbone 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
feature_maps(形状为
(batch_size, num_channels, height, width)的tuple(torch.Tensor))— 各阶段的特征图。hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层的输出以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)或(batch_size, num_channels, height, width),具体取决于骨干网络。模型在每个阶段输出处的隐藏状态,以及初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力机制时适用。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
cls_tokens (
tuple(torch.Tensor), 可选) — 来自每个所选特征阶段的 CLS token,每个的形状为(batch_size, hidden_size)。 仅当config.return_class_token=True时存在。
DINOv3ConvNextModel
class transformers.DINOv3ConvNextModel
< source >( config: DINOv3ConvNextConfig )
参数
- config (DINOv3ConvNextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
原始的 Dinov3 Convnext 模型,输出原始隐藏状态,顶部未添加任何特定头。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor**kwargs ) → BaseModelOutputWithPoolingAndNoAttention or tuple(torch.Tensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 对应于输入图像的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。
返回值
BaseModelOutputWithPoolingAndNoAttention 或 tuple(torch.Tensor)
BaseModelOutputWithPoolingAndNoAttention 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(DINOv3ConvNextConfig)和输入而定的各种元素。
DINOv3ConvNextModel 的 forward 方法会重写 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, num_channels, height, width)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output(形状为
(batch_size, hidden_size)的torch.Tensor)— 在空间维度上执行池化操作后的最后一层隐藏状态。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, num_channels, height, width)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
DINOv3ViTImageProcessor
class transformers.DINOv3ViTImageProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为{'height' -- 224, 'width': 224}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
构建一个 DINOv3ViTImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - image_like_kwargs (
dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks)是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用preprocess(images, image_like_inputs={"masks": masks})。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
预处理一张图像或一批图像。
DINOv3ConvNextBackbone
class transformers.DINOv3ConvNextBackbone
< source >( config: DINOv3ConvNextConfig )
参数
- config (DINOv3ConvNextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Dinov3 Convnext 骨干网络。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor**kwargs ) → BackboneOutput or tuple(torch.Tensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 对应于输入图像的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。
返回值
BackboneOutput 或 tuple(torch.Tensor)
BackboneOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(DINOv3ConvNextConfig)和输入。
DINOv3ConvNextBackbone 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
feature_maps(形状为
(batch_size, num_channels, height, width)的tuple(torch.Tensor))— 各阶段的特征图。hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层的输出以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)或(batch_size, num_channels, height, width),具体取决于骨干网络。模型在每个阶段输出处的隐藏状态,以及初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力机制时适用。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。