Transformers documentation

HGNet-V2

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2025-04-29 贡献至 Hugging Face Transformers。

HGNet-V2

HGNetV2 是一款专为在 NVIDIA GPU 上实现精度与延迟的最佳平衡而构建的下一代卷积神经网络(CNN)骨干网络。在原始HGNet的基础上,HGNetV2 以快速的推理速度实现了高精度,并在图像分类、目标检测和分割等任务中表现出色,是 GPU 计算机视觉应用的实用选择。

您可以在 USTC 组织下找到所有原始的 HGNet V2 模型。

该模型由 VladOS95-cyber 贡献。 点击右侧边栏中的 HGNet V2 模型,以查看将 HGNet V2 应用于不同计算机视觉任务的更多示例。

下面的示例演示了如何使用 Pipeline 或 AutoModel 类对图像进行分类。

Pipeline
AutoModel
from transformers import pipeline


pipeline = pipeline(
    task="image-classification",
    model="ustc-community/hgnet-v2",
    device=0
)
pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")

HGNetV2Config

class transformers.HGNetV2Config

< >

( 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 = 3embedding_size: int = 64depths: list[int] | tuple[int, ...] = (3, 4, 6, 3)hidden_sizes: list[int] | tuple[int, ...] = (256, 512, 1024, 2048)hidden_act: str = 'relu'_out_features: list[str] | None = None_out_indices: list[int] | None = Nonestem_channels: list[int] | tuple[int, ...] = (3, 32, 48)stem_strides: collections.abc.Sequence[int | list[int] | tuple[int, ...]] = (2, 1, 1, 2, 1)stage_in_channels: list[int] | tuple[int, ...] = (48, 128, 512, 1024)stage_mid_channels: list[int] | tuple[int, ...] = (48, 96, 192, 384)stage_out_channels: list[int] | tuple[int, ...] = (128, 512, 1024, 2048)stage_num_blocks: list[int] | tuple[int, ...] = (1, 1, 3, 1)stage_downsample: list[bool] | tuple[bool, ...] = (False, True, True, True)stage_downsample_strides: collections.abc.Sequence[int | list[int] | tuple[int, ...]] = (2, 2, 2, 2)stage_light_block: list[bool] | tuple[bool, ...] = (False, False, True, True)stage_kernel_size: list[int] | tuple[int, ...] = (3, 3, 5, 5)stage_numb_of_layers: list[int] | tuple[int, ...] = (6, 6, 6, 6)use_learnable_affine_block: bool = Falseinitializer_range: float = 0.02 )

参数

  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • embedding_size (int,可选,默认为 64) — 嵌入和隐藏状态的维度。
  • depths (Union[list[int], tuple[int, ...]],可选,默认为 (3, 4, 6, 3)) — Transformer 中每一层的深度。
  • hidden_sizes (Union[list[int], tuple[int, ...]],可选,默认为 (256, 512, 1024, 2048)) — 模型每个阶段的维度(隐藏层大小)。
  • hidden_act (str,可选,默认为 relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • stem_channels (list[int], 可选, 默认为 [3, 32, 48]) — stem 层的通道维度:
    • 第一个数字(3)是输入图像的通道数
    • 第二个数字(32)是中间茎通道
    • 第三个数字(48)是输出茎通道数
  • stem_strides (Sequence[int | list[int] | tuple[int, ...]],可选,默认为 (2, 1, 1, 2, 1)) — Stem 层的步长模式。
  • stage_in_channels (list[int],可选,默认为 [48, 128, 512, 1024]) — 骨干网络每个阶段的输入通道维度。 这定义了每个阶段的输入将具有多少个通道。
  • stage_mid_channels (list[int],可选,默认为 [48, 96, 192, 384]) — 骨干网络每个阶段的中间通道维度。 这定义了每个阶段的中间层所使用的通道数。
  • stage_out_channels (list[int],可选,默认为 [128, 512, 1024, 2048]) — 骨干网络每个阶段的输出通道维度。 这定义了每个阶段输出将包含的通道数。
  • stage_num_blocks (list[int],可选,默认为 [1, 1, 3, 1]) — 主干网络每个阶段使用的块数量。 通过指定堆叠多少个卷积块来控制每个阶段的深度。
  • stage_downsample (list[bool],可选,默认为 [False, True, True, True]) — 指示是否在每个阶段对特征图进行下采样。 如果为 True,则特征图的空间维度将被缩减。
  • stage_downsample_strides (Sequence[int | list[int] | tuple[int, ...]],可选,默认为 (2, 2, 2, 2)) — 每个阶段层的步长模式。
  • stage_light_block (list[bool],可选,默认为 [False, False, True, True]) — 指示是否在每个阶段中使用轻量级块。 轻量级块是卷积块的一种变体,其参数量可能更少。
  • stage_kernel_size (list[int],可选,默认为 [3, 3, 5, 5]) — 每个阶段中卷积层的卷积核大小。
  • stage_numb_of_layers (list[int],可选,默认为 [6, 6, 6, 6]) — 每个 stage 块中使用的层数。
  • use_learnable_affine_block (bool,可选,默认为 False) — 是否在网络中使用 Learnable Affine Blocks (LAB)。 LAB 会在某些操作之后添加可学习的缩放和偏置参数。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 HGNetV2Backbone 配置的类。它根据指定的参数实例化 Hgnet V2 模型,并定义模型架构。使用默认值实例化配置将得到与 ustc-community/dfine_x_coco 类似的配置。

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

HGNetV2Backbone

class transformers.HGNetV2Backbone

< >

( config: HGNetV2Config )

forward

< >

( pixel_values: Tensoroutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**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 来处理图像)。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

BackboneOutput 或 tuple(torch.Tensor)

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

HGNetV2Backbone 的 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import HGNetV2Config, HGNetV2Backbone
>>> import torch

>>> config = HGNetV2Config()
>>> model = HGNetV2Backbone(config)

>>> pixel_values = torch.randn(1, 3, 224, 224)

>>> with torch.no_grad():
...     outputs = model(pixel_values)

>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 2048, 7, 7]

HGNetV2ForImageClassification

class transformers.HGNetV2ForImageClassification

< >

( config: HGNetV2Config )

参数

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

在顶部添加图像分类头的 HGNetV2 模型(在池化特征之上添加一个线性层),例如用于 ImageNet。

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutputWithNoAttention 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 来处理图像)。
  • labels(形状为 (batch_size,) 的 torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

ImageClassifierOutputWithNoAttention 或 tuple(torch.Tensor)

一个 ImageClassifierOutputWithNoAttention 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(HGNetV2Config)和输入。

HGNetV2ForImageClassification 的 forward 方法会重写 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。
  • logits(形状为 (batch_size, config.num_labels) 的 torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。
  • hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个阶段输出的一个张量),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出处的隐藏状态(也称为特征图)。

示例:

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

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

>>> model = HGNetV2ForImageClassification.from_pretrained("ustc-community/hgnet-v2")
>>> processor = AutoImageProcessor.from_pretrained("ustc-community/hgnet-v2")

>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> outputs.logits.shape
torch.Size([1, 2])
Update on GitHub