Transformers documentation

CHMv2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-03-06 在 HF papers 上发布,并于 2026-03-11 贡献至 Hugging Face Transformers。

CHMv2

FlashAttention SDPA

概述

Canopy Height Maps v2 (CHMv2) 模型在 CHMv2: Improvements in Global Canopy Height Mapping using DINOv3 中提出。基于我们于 2024 年发布的 原始高分辨率树冠高度图,CHMv2 通过利用 Meta 的自监督视觉模型 DINOv3,在精度、细节和全球一致性方面实现了显著提升。

您可以在此处找到更多信息,原始代码见此处。

该论文的摘要如下:

精确的树冠高度信息对于量化森林碳储量、监测森林恢复与退化以及评估栖息地结构至关重要,然而,来自机载激光雷达(ALS)的高保真测量数据在全球范围内的分布并不均衡。在此,我们提出了 CHMv2,这是一张全球范围、米级分辨率的树冠高度图,它基于高分辨率光学卫星影像,利用构建于 DINOv3 之上并针对 ALS 树冠高度模型进行训练的深度估计模型生成。与现有产品相比,CHMv2 显著提高了精度,减少了高森林中的偏差,并更好地保留了树冠边缘和空隙等细尺度结构。这些提升得益于地理多样性训练数据的大幅扩展、自动化的数据整理与配准,以及针对树冠高度分布量身定制的损失函数和数据采样策略。我们将 CHMv2 与独立的 ALS 测试集以及数千万条 GEDI 和 ICESat-2 观测数据进行验证,证明了其在主要森林生物群系中表现一致。

使用示例

使用以下代码对图像运行推理:

import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForDepthEstimation


processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head")
model = AutoModelForDepthEstimation.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head", device_map="auto")

image = Image.open("image.tif")
inputs = processor(images=image, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

depth = processor.post_process_depth_estimation(
    outputs, target_sizes=[(image.height, image.width)]
)[0]["predicted_depth"]

CHMv2Config

class transformers.CHMv2Config

< >

( 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 = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepatch_size: int = 16initializer_range: float = 0.02reassemble_factors: list[float | int] | None = Nonepost_process_channels: list[int] | None = Nonefusion_hidden_size: int = 256head_hidden_size: int = 128number_output_channels: int = 256readout_type: str = 'project'min_depth: float = 0.001max_depth: float = 96.0bins_strategy: typing.Literal['linear', 'log', 'chmv2_mixlog'] = 'chmv2_mixlog'norm_strategy: typing.Literal['linear', 'softmax', 'sigmoid', 'chmv2_mixlog'] = 'chmv2_mixlog' )

参数

  • backbone_config (Union[dict, "PreTrainedConfig"],可选) — 骨干模型的配置。目前仅支持 DINOv3ViTConfig。
  • patch_size (int,可选,默认为 16) — 骨干视觉 Transformer 使用的 patch 大小。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • reassemble_factors (list[float],可选,默认为 [4, 2, 1, 0.5]) — 重组层的上采样/下采样因子。
  • post_process_channels (list[int],可选,默认为 [128, 256, 512, 1024]) — 重组阶段中每个主干特征层级的输出通道大小。
  • fusion_hidden_size (int,可选,默认为 256) — 融合前的通道数。
  • head_hidden_size (int, 可选,默认为 128) — 深度估计头隐藏层的通道数。
  • number_output_channels (int, 可选,默认为 256) — CHMv2 头的输出通道数(即深度 bin 的数量)。
  • readout_type (str, 可选,默认为 "project") — CLS token 的读出操作类型。取值为 ["ignore", "add", "project"] 之一。
  • min_depth (float,可选,默认值为 0.001) — 用于深度分箱计算的最小深度值。
  • max_depth (float,可选,默认值为 96.0) — 用于深度分箱计算的最大深度值。
  • bins_strategy (str,可选,默认为 "chmv2_mixlog") — 深度分箱的分布策略。取值为 ["linear", "log", "chmv2_mixlog"] 之一。
  • norm_strategy (str,可选,默认为 "chmv2_mixlog") — 用于深度预测的归一化策略。取值为 ["linear", "softmax", "sigmoid", "chmv2_mixlog"] 之一。

这是用于存储 Chmv2Model 配置的类。它根据指定的参数实例化 Chmv2 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/dinov3-vitl16-chmv2-dpt-head 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> from transformers import CHMv2Config, CHMv2ForDepthEstimation

>>> configuration = CHMv2Config()
>>> model = CHMv2ForDepthEstimation(configuration)
>>> configuration = model.config

CHMv2ImageProcessor

class transformers.CHMv2ImageProcessor

< >

( **kwargs: *<class 'transformers.models.chmv2.image_processing_chmv2.CHMv2ImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 False) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 384, 'width': 384}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 None) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 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.42, 0.411, 0.296]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.213, 0.156, 0.143]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • 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,可选,默认为 None) — 是否对图像进行中心裁剪。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ensure_multiple_of (int,kwargs,可选,默认值为 1) — 如果 do_resize 为 True,图像将被调整为该值整数倍的尺寸。可通过 preprocess 中的 ensure_multiple_of 进行覆盖。
  • size_divisor (int, kwargs,默认为 16) — 用于确保高度和宽度都能被整除的数值。
  • keep_aspect_ratio (bool,kwargs,可选,默认为 False) — 如果为 True,图像将被调整为在保持宽高比不变的前提下尽可能大的尺寸。该设置可被 preprocess 中的 keep_aspect_ratio 覆盖。
  • do_reduce_labels (bool,kwargs,可选,默认为 self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。

构建一个 CHMv2ImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.chmv2.image_processing_chmv2.CHMv2ImageProcessorKwargs'> ) → ~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。
  • segmentation_maps (ImageInput,可选) — 要预处理的分割图。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ensure_multiple_of (int,kwargs,可选,默认值为 1) — 如果 do_resize 为 True,图像将被调整为该值整数倍的尺寸。可通过 preprocess 中的 ensure_multiple_of 进行覆盖。
  • size_divisor (int, kwargs) — 用于确保高度和宽度都能被整除的数值。
  • keep_aspect_ratio (bool,kwargs,可选,默认为 False) — 如果为 True,图像将被调整为在保持宽高比不变的前提下尽可能大的尺寸。该设置可被 preprocess 中的 keep_aspect_ratio 覆盖。
  • do_reduce_labels (bool,kwargs,可选,默认为 self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

post_process_depth_estimation

< >

( outputs: DepthEstimatorOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None ) → List[Dict[str, TensorType]]

参数

  • outputs (DepthEstimatorOutput) — 模型的原始输出。
  • target_sizes (TensorType 或 List[Tuple[int, int]],可选) — 形状为 (batch_size, 2) 的张量,或包含每个图像目标尺寸(高度、宽度)的元组列表(Tuple[int, int])。如果设为 None,则不会调整预测结果的尺寸。

返回值

List[Dict[str, TensorType]]

一个字典列表,其中每个字典包含表示处理后深度预测的张量。

将 DepthEstimatorOutput 的原始输出转换为最终的深度预测和深度 PIL 图像。 仅支持 PyTorch。

CHMv2ForDepthEstimation

class transformers.CHMv2ForDepthEstimation

< >

( config: CHMv2Config )

参数

  • config (CHMv2Config) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

在顶部添加深度估计头(由卷积层组成)的 CHMv2 模型,例如用于树冠高度估计。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DepthEstimatorOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 CHMv2ImageProcessor 获取像素值。有关详细信息,请参阅 CHMv2ImageProcessor.call()(processor_class 使用 CHMv2ImageProcessor 处理图像)。
  • labels(形状为 (batch_size, height, width) 的 torch.LongTensor,可选) — 用于计算损失的真实深度估计图。

返回值

DepthEstimatorOutput 或 tuple(torch.Tensor)

一个 DepthEstimatorOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(CHMv2Config)和输入。

CHMv2ForDepthEstimation 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • predicted_depth(形状为 (batch_size, height, width) 的 torch.Tensor)— 每个像素的预测深度。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, num_channels, height, width)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, patch_size, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import AutoImageProcessor, CHMv2ForDepthEstimation
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
    >>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")

>>> processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head")
>>> model = CHMv2ForDepthEstimation.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head")

>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
>>> model.to(device)

>>> # prepare image for the model
>>> inputs = processor(images=image, return_tensors="pt").to(device)

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

>>> # interpolate to original size
>>> post_processed_output = processor.post_process_depth_estimation(
...     outputs, [(image.height, image.width)],
... )
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
Update on GitHub