Transformers 文档

CHMv2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2026 年 3 月 6 日在 HF papers 上发布,并于 2026 年 3 月 11 日贡献给 Hugging Face Transformers。

CHMv2

FlashAttention SDPA

概述

冠层高度图 v2 (CHMv2) 模型在 CHMv2: 使用 DINOv3 改进全球冠层高度测绘 一文中提出。基于我们在 2024 年发布的 原始高分辨率冠层高度图,CHMv2 利用 Meta 的自监督视觉模型 DINOv3,在准确性、细节和全球一致性方面实现了显著提升。

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

论文摘要如下:

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

使用示例

使用以下代码在图像上运行推理

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 = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None patch_size: int = 16 initializer_range: float = 0.02 reassemble_factors: list[float | int] | None = None post_process_channels: list[int] | None = None fusion_hidden_size: int = 256 head_hidden_size: int = 128 number_output_channels: int = 256 readout_type: str = 'project' min_depth: float = 0.001 max_depth: float = 96.0 bins_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]) — 重组层(reassemble layers)的上/下采样因子。
  • 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 头的输出通道数(深度箱的数量)。
  • 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: typing_extensions.Unpack[transformers.models.chmv2.image_processing_chmv2.CHMv2ImageProcessorKwargs] )

参数

  • ensure_multiple_of (int, 关键字参数, 可选,默认为 1) — 如果 do_resizeTrue,图像将被调整大小为该值的倍数。可以被 preprocess 中的 ensure_multiple_of 参数覆盖。
  • keep_aspect_ratio (bool, 关键字参数, 可选,默认为 False) — 如果为 True,图像将被调整为在保持纵横比的前提下可能的最大尺寸。可以被 preprocess 中的 keep_aspect_ratio 参数覆盖。
  • do_reduce_labels (bool, 关键字参数, 可选,默认为 self.do_reduce_labels) — 是否将分割图的所有标签值减 1。通常用于 0 被用作背景,且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。模型特定的 kwargs 列在上方;有关支持的参数的完整列表,请参见 TypedDict 类。

构建一个 CHMv2ImageProcessor 图像处理器。

preprocess

< >

( 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: typing_extensions.Unpack[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, 可选) — 待预处理的分割图。
  • ensure_multiple_of (int, kwargs, 可选, 默认为 1) — 如果 do_resizeTrue,图像将被调整大小至该值的倍数。可以通过 preprocess 中的 ensure_multiple_of 进行覆盖。
  • keep_aspect_ratio (bool, kwargs, 可选, 默认为 False) — 如果为 True,图像将在保持纵横比的前提下调整至尽可能大的尺寸。可以通过 preprocess 中的 keep_aspect_ratio 进行覆盖。
  • do_reduce_labels (bool, kwargs, 可选, 默认为 self.do_reduce_labels) — 是否将分割图中的所有标签值减 1。通常用于背景标签为 0 且背景本身不包含在数据集所有类别中的情况(例如 ADE20k)。背景标签将被替换为 255。
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠后的张量;否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。模型特定的 kwargs 在上面列出;请查看 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

后处理深度估计

< >

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

参数

  • outputs (DepthEstimatorOutput) — 模型的原始输出。
  • target_sizes (TensorTypeList[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: FloatTensor labels: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) DepthEstimatorOutputtuple(torch.FloatTensor)

参数

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

返回

DepthEstimatorOutputtuple(torch.FloatTensor)

一个 DepthEstimatorOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(CHMv2Config)和输入包含不同的元素。

CHMv2ForDepthEstimation 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

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

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

  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为 (batch_size, num_channels, height, width)

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

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

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

示例

>>> from transformers import AutoImageProcessor, CHMv2ForDepthEstimation
>>> import torch
>>> from PIL import Image
>>> 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"]
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.