Transformers documentation
Sapiens2
该模型于 2026-04-23 在 HF papers 上发布,并于 2026-06-03 贡献至 Hugging Face Transformers。
Sapiens2
概述
Sapiens2 模型由 Rawal Khirodkar、He Wen、Julieta Martinez、Yuan Dong、Zhaoen Su 和 Shunsuke Saito 在 Sapiens2 中提出。 Sapiens2 是一组高分辨率视觉 Transformer,在约 10 亿张经过精心筛选的人体图像上进行预训练,专为以人为中心的计算机视觉任务而设计,包括姿态估计、身体部位分割、表面法线估计和点图估计。
您可以在 Sapiens2 集合中找到所有原始的 Sapiens2 检查点。
该论文的摘要如下:
我们提出了 Sapiens2,这是一个专注于以人为中心的视觉任务的高分辨率 Transformer 模型家族,旨在实现泛化能力、多功能性以及高保真输出。我们在约 10 亿张经过精心筛选的高质量人体图像上进行预训练,并改进了任务标注,同时结合掩码图像重建与自蒸馏对比目标,以学习低层和语义特征。我们的模型参数规模从 0.4B 扩展到 5B,并在原生 1K 分辨率下进行训练,同时提供分层 4K 变体以支持扩展的空间推理。与上一代相比,Sapiens2 取得了显著提升:姿态估计的 mAP 提升 4 个点,身体部位分割的 mIoU 提升 24.3 个点,法线估计误差降低 45.6%,并扩展至点图(pointmap)和反照率(albedo)估计等新任务。代码已公开可用。
提示:
- Sapiens2 使用旋转位置嵌入(RoPE),并支持任意输入分辨率。默认的图像处理器会将图像调整为 1024×768(高×宽)。
- 该模型在中间层使用分组查询注意力(GQA),并在前 8 层和后 8 层使用完整的多头注意力。
- 注册 token(默认 8 个)可降低 patch token 中的高范数伪影,从而获得更清晰的注意力图,并在密集预测任务上取得更好的性能。
使用示例
以下示例展示了如何使用 Sapiens2Model 获取 CLS token(整图嵌入)。
import torch
from transformers import AutoImageProcessor, AutoModel
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
model = AutoModel.from_pretrained("facebook/sapiens2-pretrain-0.4b", device_map="auto")
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
# outputs.pooler_output is the CLS token (whole-image embedding)
cls_token = outputs.pooler_output
print("CLS token shape:", cls_token.shape) # [1, 1024]Sapiens2Backbone 直接在输出对象上暴露已重塑为空间维度的 patch token 和 CLS token。
import torch
from transformers import AutoBackbone, AutoImageProcessor
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
model = AutoBackbone.from_pretrained("facebook/sapiens2-pretrain-0.4b", device_map="auto")
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs, return_class_token=True)
# Patch tokens shaped (batch, height, width, channels)
patch_features = outputs.feature_maps[0]
cls_token = outputs.cls_tokens[0]
print("CLS token shape:", cls_token.shape) # [1, 1024]
print("Patch features shape:", patch_features.shape) # [1, 64, 48, 1024]以下示例展示了如何使用 Sapiens2ForNormalEstimation 来估计表面法线。
输出的法线是原始值(未归一化);请使用 post_process_normal_estimation 对其进行缩放和 L2 归一化。
import torch
from transformers import AutoImageProcessor, AutoModelForNormalEstimation
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-normal-0.4b")
model = AutoModelForNormalEstimation.from_pretrained("facebook/sapiens2-normal-0.4b", device_map="auto")
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
# outputs.normals shape: (batch_size, 3, height, width) — raw, unnormalized XYZ normals
print("Normals shape:", outputs.normals.shape) # [1, 3, 1024, 768]
# Remove preprocessing padding, resize to original size, and L2-normalize to unit vectors in [-1, 1]
original_size = (image.height, image.width)
result = image_processor.post_process_normal_estimation(
outputs, source_sizes=[original_size], target_sizes=[original_size]
)
normals = result[0]["normals"]
print("Normals shape:", normals.shape) # [3, original_height, original_width]
### Example code for visualization
# Convert L2-normalized normals in [-1, 1] to RGB in [0, 255]
normals_rgb = ((normals + 1.0) / 2.0 * 255.0).clamp(0, 255).to(torch.uint8)
# Apply background removal using the segmentation model output.
# `segmentation` is the output of `post_process_semantic_segmentation` — a (H, W) tensor
# of per-pixel class IDs, where class 0 is background.
background_mask = segmentation == 0
normals_rgb[:, background_mask] = 0
print("Normals RGB shape:", normals_rgb.shape) # [3, original_height, original_width]以下示例展示了如何使用 Sapiens2ForPointmapEstimation 估计逐像素的 3D 坐标。
使用 post_process_pointmap_estimation 移除预处理填充,调整至原始图像尺寸,并应用预测的焦距比例。
import torch
from transformers import AutoImageProcessor, AutoModelForPointmapEstimation
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pointmap-0.4b")
model = AutoModelForPointmapEstimation.from_pretrained("facebook/sapiens2-pointmap-0.4b", device_map="auto")
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
# outputs.pointmaps shape: (batch_size, 3, height, width) — raw XYZ in canonical camera space
print("Pointmaps shape:", outputs.pointmaps.shape) # [1, 3, 1024, 768]
# Remove preprocessing padding, resize to original size, and apply focal-length scale
original_size = (image.height, image.width)
result = image_processor.post_process_pointmap_estimation(
outputs, source_sizes=[original_size], target_sizes=[original_size]
)
pointmap = result[0]["pointmap"]
print("Pointmap shape:", pointmap.shape) # [3, original_height, original_width]
### Example code for visualization
# Visualize the pointmap as an RGB image using inverse-depth and the turbo colormap.
import matplotlib.pyplot as plt
# `segmentation` is the output of `post_process_semantic_segmentation` — a (H, W) tensor
# of per-pixel class IDs, where class 0 is background.
foreground_mask = segmentation != 0
depth = pointmap[2] # Z channel: depth in camera space, shape (H, W)
pointmap_rgb = torch.zeros(3, *depth.shape, dtype=torch.uint8)
foreground_depth = depth[foreground_mask]
if foreground_depth.numel() > 0:
depth_low, depth_high = torch.quantile(foreground_depth, torch.tensor([0.01, 0.99]))
inverse_depth = 1.0 / foreground_depth.clamp(min=1e-6)
inverse_depth_low = 1.0 / depth_high.clamp(min=1e-6)
inverse_depth_high = 1.0 / depth_low.clamp(min=1e-6)
inverse_depth_normalized = ((inverse_depth - inverse_depth_low) / (inverse_depth_high - inverse_depth_low + 1e-8)).clamp(0, 1)
turbo = plt.get_cmap("turbo")
foreground_colors = torch.from_numpy(turbo(inverse_depth_normalized.cpu().numpy())[..., :3] * 255).to(torch.uint8) # (N, 3)
pointmap_rgb[:, foreground_mask] = foreground_colors.T
print("Pointmap RGB shape:", pointmap_rgb.shape) # [3, original_height, original_width]以下示例展示了如何使用 Sapiens2ForPoseEstimation 运行姿态估计。
该模型预测每个关键点的热力图;使用 post_process_pose_estimation 将其解码回图像空间的关键点坐标。这需要 opencv-python(pip install opencv-python)。
import torch
from transformers import AutoImageProcessor, AutoModelForPoseEstimation
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
model = AutoModelForPoseEstimation.from_pretrained("facebook/sapiens2-pose-0.4b", device_map="auto")
# Provide bounding boxes in COCO format (x, y, width, height) for each person
boxes = [[[270.8, 0.6, 294.1, 379.5]]]
inputs = image_processor(image, boxes=boxes, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
# outputs.heatmaps shape: (num_persons, num_keypoints, heatmap_height, heatmap_width)
print("Heatmaps shape:", outputs.heatmaps.shape) # [1, 308, 256, 192]
# Decode heatmaps to image-space keypoint coordinates
results = image_processor.post_process_pose_estimation(outputs, boxes=boxes)[0]
keypoints = results[0]["keypoints"] # (num_keypoints, 2) — x/y in image coordinates
scores = results[0]["scores"] # (num_keypoints,) — per-keypoint confidence
print("Keypoints shape:", keypoints.shape)水平翻转增强(测试时增强)通过对原始图像和镜像图像的预测结果取平均来提高关键点精度。在第二次前向传播中传入 flip_pairs——一个由 [left_keypoint, right_keypoint] 对组成的张量。模型在返回热力图之前会将其翻转回原始方向,因此您可以直接对两个输出取平均。
import torch
from transformers import AutoImageProcessor, AutoModelForPoseEstimation
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
model = AutoModelForPoseEstimation.from_pretrained("facebook/sapiens2-pose-0.4b", device_map="auto")
boxes = [[[270.8, 0.6, 294.1, 379.5]]]
inputs = image_processor(image, boxes=boxes, return_tensors="pt").to(model.device)
pixel_values = inputs["pixel_values"]
flip_pairs = torch.tensor(model.config.flip_pairs, device=model.device)
with torch.inference_mode():
outputs = model(pixel_values)
outputs_flipped = model(pixel_values.flip(-1), flip_pairs=flip_pairs)
results = image_processor.post_process_pose_estimation(outputs, outputs_flipped=outputs_flipped, boxes=boxes)[0]
keypoints = results[0]["keypoints"]
scores = results[0]["scores"]以下示例展示了如何通过传入 labels 和可选的 label_weights,使用 Sapiens2ForPoseEstimation 计算有监督的 Masked Mean Squared Error (MSE) 损失。这在利用 Trainer API 进行微调时非常有用。
import torch
from transformers import AutoImageProcessor, AutoModelForPoseEstimation
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
model = AutoModelForPoseEstimation.from_pretrained("facebook/sapiens2-pose-0.4b", device_map="auto")
# Provide bounding boxes in COCO format (x, y, width, height) for each person
boxes = [[[270.8, 0.6, 294.1, 379.5]]]
inputs = image_processor(image, boxes=boxes, return_tensors="pt").to(model.device)
# Create dummy labels (heatmaps) and visibility weights to simulate ground truth
# 1.0 for visible keypoints, 0.0 for occluded/invisible keypoints
batch_size, num_keypoints = 1, 308
heatmap_height, heatmap_width = 1024, 768
labels = torch.randn(batch_size, num_keypoints, heatmap_height, heatmap_width, device=model.device)
label_weights = torch.ones(batch_size, num_keypoints, 1, 1, device=model.device)
# Forward pass with loss calculation
outputs = model(**inputs, labels=labels, label_weights=label_weights)
print("Loss:", outputs.loss.item())以下示例展示了如何使用 Sapiens2ForSemanticSegmentation 执行身体部位分割。
import torch
from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-seg-0.4b")
model = AutoModelForSemanticSegmentation.from_pretrained("facebook/sapiens2-seg-0.4b", device_map="auto")
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
# outputs.logits shape: (batch_size, num_labels, height, width)
print("Logits shape:", outputs.logits.shape) # [1, 29, 1024, 768]
# Get per-pixel class predictions, optionally resized to the original image size
original_size = (image.height, image.width)
segmentation = image_processor.post_process_semantic_segmentation(
outputs, target_sizes=[original_size]
)[0]
print("Segmentation map shape:", segmentation.shape) # [original_height, original_width]以下示例展示了如何使用 Sapiens2ForImageMatting 运行图像抠图。
输出已经过 sigmoid 激活,且取值范围在 [0, 1] 内;请使用 post_process_image_matting 进行缩放并拆分为
alphas、foregrounds 以及可选的 composite 图像。合成图像通过以下公式将前景叠加在背景上: composite = foreground * (1 - alpha) * background。
import torch
from transformers import AutoImageProcessor, AutoModelForImageMatting
from transformers.image_utils import load_image
image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-matting-1b")
model = AutoModelForImageMatting.from_pretrained("facebook/sapiens2-matting-1b", device_map="auto")
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
# outputs.foregrounds: (1, 3, H, W), outputs.alphas: (1, 1, H, W) — both in [0, 1]
original_size = (image.height, image.width)
# Pass an optional background to composite the foreground over it.
# A (3, 1, 1) tensor broadcasts as a uniform color; PIL images and numpy arrays are also accepted.
background = torch.tensor([0, 177, 64], dtype=torch.uint8).view(3, 1, 1) # chroma green in RGB
result = image_processor.post_process_image_matting(
outputs, target_sizes=[original_size], backgrounds=background
)[0]
print("Alpha shape:", result["alpha"].shape) # [1, original_height, original_width]
print("Foreground shape:", result["foreground"].shape) # [3, original_height, original_width]
print("Composite shape:", result["composite"].shape) # [3, original_height, original_width] — uint8 [0, 255]Sapiens2Config
class transformers.Sapiens2Config
< 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 = 1024intermediate_size: int = 4096num_hidden_layers: int = 24num_attention_heads: int = 16hidden_act: str = 'silu'attention_dropout: float | int = 0.0initializer_range: float = 0.02rope_theta: float = 100.0image_size: int | list[int] | tuple[int, int] = 224num_channels: int = 3query_bias: bool = Truekey_bias: bool = Truevalue_bias: bool = Trueproj_bias: bool = Truemlp_bias: bool = Truelayerscale_value: float = 1.0drop_path_rate: float | int = 0.0use_gated_mlp: bool = Truenum_register_tokens: int = 8pos_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 = Nonereshape_hidden_states: bool = Trueuse_mask_token: bool = Falserms_norm_eps: float = 1e-06normalize_backbone_outputs: bool = Trueuse_qk_norm: bool = Truenum_key_value_heads_per_layer: list[int] | None = Nonenum_key_value_attention_heads: int = 8num_first_full_attention_layers: int = 8num_last_full_attention_layers: int = 8semantic_loss_ignore_index: int = 255flip_pairs: list[list[int]] | None = Nonehead_config: transformers.models.sapiens2.configuration_sapiens2.Sapiens2HeadConfig | dict | None = None )
参数
- patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为16) — 每个 patch 的大小(分辨率)。 - hidden_size (
int,可选,默认为1024) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为4096) — MLP 表示的维度。 - num_hidden_layers (
int,可选,默认为24) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - 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] 范围内按对数均匀分布采样。 - reshape_hidden_states (
bool,可选,默认为True) — 当用作 backbone 时,是否将 hidden states 重塑为空间维度。 - use_mask_token (
bool,可选,默认为False) — 是否在嵌入中使用掩码 token(掩码图像建模预训练所需)。 - rms_norm_eps (
float,可选,默认值为 1e-6) — RMS 归一化层的 epsilon 值。 - normalize_backbone_outputs (
bool,可选,默认为True) — 是否在从 forward 返回之前,对 backbone 的feature_maps和cls_tokens输出应用 RMSNorm。仅当模型作为 backbone 使用时生效。 - use_qk_norm (
bool,可选,默认为True) — 是否在注意力层的 RoPE 之前对查询和键应用 RMSNorm。 - num_key_value_heads_per_layer (
list[int], 可选) — 每个 Transformer 层的 key/value 头数。将某层的值设置为与num_attention_heads相等,即可获得完整的 multi-head attention;设置较小的值则可获得 grouped-query attention。默认情况下,前num_first_full_attention_layers层和后num_last_full_attention_layers层的值为num_attention_heads,其余所有层的值为num_key_value_attention_heads。 - num_key_value_attention_heads (
int,可选,默认为8) — 当未设置num_key_value_heads_per_layer时,使用分组查询注意力的层所使用的键/值头数。当设置了num_key_value_heads_per_layer时,此参数将被忽略。 - num_first_full_attention_layers (
int,可选,默认为 8) — 使用完整多头注意力的前导 Transformer 层数。 仅在num_key_value_heads_per_layer为None时使用。 - num_last_full_attention_layers (
int,可选,默认为 8) — 使用完整多头注意力的末尾 Transformer 层数。 仅在num_key_value_heads_per_layer为None时使用。 - semantic_loss_ignore_index (
int,可选,默认为 255) — 在计算分割损失时忽略的标签索引。 - flip_pairs (
list[list[int]], 可选) — 水平镜像的关键点索引对(例如,左耳 ↔ 右耳)。 每对是一个包含两个元素的列表[left_index, right_index]。用于姿态估计中的测试时水平翻转增强:将这些对传递给第二次前向调用,以便模型在返回热图之前将其翻转回来。 - head_config (
Sapiens2HeadConfig,可选) — 解码头的配置。有关可用选项,请参阅 Sapiens2HeadConfig。
这是用于存储 Sapiens2Model 配置的类。它根据指定的参数实例化 Sapiens2 模型,并定义模型架构。使用默认值实例化配置将得到与 facebook/sapiens2-pretrain-0.4b 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Sapiens2HeadConfig
class transformers.Sapiens2HeadConfig
< 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 = Noneupsample_out_channels: list[int] | None = Noneupsample_kernel_sizes: list[int] | None = Noneupsample_kernel_size: int = 4use_pixel_shuffle: bool | None = Noneconv_out_channels: list[int] | None = Noneconv_kernel_sizes: list[int] | None = Noneconv_kernel_size: int = 1scale_conv_out_channels: list[int] | None = Nonescale_conv_kernel_sizes: list[int] | None = Nonescale_conv_kernel_size: int = 1scale_final_input_size: int | None = Nonescale_final_hidden_sizes: list[int] | None = None )
参数
- upsample_out_channels (
list[int], 可选) — 每个上采样块的输出通道数。 第一个块以hidden_size个通道作为输入;后续块使用上一个块的输出。 - upsample_kernel_sizes (
list[int], 可选) — 每个上采样块的卷积核大小。当设置了upsample_out_channels但此项为None时,会自动填充为[4, ...]。 其长度必须与upsample_out_channels相同。 - upsample_kernel_size (
int,默认为 4) — 当未设置upsample_kernel_sizes时,上采样块的默认卷积核大小。 - use_pixel_shuffle (
bool, 可选) — 是否在上采样头中使用像素重排上采样,而非转置卷积。 当None(默认值)时,该头使用转置卷积。 - conv_out_channels (
list[int], 可选) — 上采样块之后的细化卷积层的输出通道数。 - conv_kernel_sizes (
list[int], 可选) — 每个细化卷积层的卷积核大小。当设置了conv_out_channels但此项为None时,会自动填充为[1, ...]。 其长度必须与conv_out_channels相同。 - conv_kernel_size (
int,默认为 1) — 当未设置conv_kernel_sizes时,卷积层的默认核大小。 - scale_conv_out_channels (
list[int],可选) — 用于预测焦距尺度的步长为 2 的卷积层的输出通道数。 当None(默认值)时,不会构建尺度分支。 - scale_conv_kernel_sizes (
list[int], 可选) — 每个 scale conv 层的卷积核大小。当设置了scale_conv_out_channels但此项为None时,会自动填充为[1, ...]。 其长度必须与scale_conv_out_channels相同。 - scale_conv_kernel_size (
int,默认为 1) — 当未设置scale_conv_kernel_sizes时,scale conv 层的默认 kernel size。 - scale_final_input_size (
int, 可选) — 传入 scale MLP 的展平特征尺寸。 当None(默认值)时,会根据父级 Sapiens2Config 中的image_size和patch_size自动推断。 - scale_final_hidden_sizes (
list[int], 可选) — 用于将展平的 scale 特征映射到标量 scale 输出的 MLP 的隐藏层大小。 当None(默认值)时,不会构建 scale 分支。
这是用于存储 Sapiens2Model 配置的类。它根据指定的参数实例化 Sapiens2 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/sapiens2-seg-0.4b 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Sapiens2ImageProcessor
class transformers.Sapiens2ImageProcessor
< source >( **kwargs: *<class 'transformers.models.sapiens2.image_processing_sapiens2.Sapiens2ImageProcessorKwargs'> )
参数
- 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' -- 1024, 'width': 768}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 224, 'width': 224}): 应用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,可选,默认为False) — 是否对图像进行填充。填充方式是将图像填充到批次中的最大尺寸,或填充到每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - 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,可选,默认为False) — 是否对图像进行中心裁剪。 - 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - do_reduce_labels (
bool,kwargs,可选,默认为self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。 - keypoint_heatmap_downscale_factor (
int,kwargs,可选,默认值为 4) — 相对于模型输入尺寸,目标热力图尺寸的缩小因子。 - keypoint_heatmap_sigma (
float, kwargs, 可选,默认值为 6.0) — 用于生成热力图的二维高斯分布的标准差(sigma)。
构建 Sapiens2ImageProcessor 图像处理器。
预处理
< source >( 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] = Noneboxes: list[list[list[float]]] | None = Nonekeypoints: list[list[list[list[float]]]] | None = None**kwargs: *<class 'transformers.models.sapiens2.image_processing_sapiens2.Sapiens2ImageProcessorKwargs'> ) → ~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,可选) — 要预处理的分割图。 - boxes (
list[list[list[float]]]或np.ndarray,可选) — 每张图像的边界框列表或数组。每个边界框应为包含 4 个浮点数的列表,表示 COCO 格式下的边界框坐标 (top_left_x, top_left_y, width, height)。提供该参数时,每个人物裁剪区域将经过仿射变换以适配模型输入尺寸,而不是对整张图像进行缩放。 - keypoints (
list[list[list[list[float]]]], 可选) — 每张图片中每个人的关键点列表。预期格式为 COCO 风格的[x, y, visibility]。x和y值预期为绝对图像像素坐标。 格式为[images -> persons -> keypoints -> [x, y, visibility]]。用于生成 姿态估计微调所需的真值热图和可见性权重。 - 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - do_reduce_labels (
bool,kwargs,可选,默认为self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。 - keypoint_heatmap_downscale_factor (
int,kwargs,可选,默认值为 4) — 相对于模型输入尺寸,目标热力图尺寸的缩小因子。 - keypoint_heatmap_sigma (
float, kwargs, 可选,默认值为 6.0) — 用于生成热力图的二维高斯分布的标准差(sigma)。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_image_matting
< source >( outputstarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = Nonebackgrounds: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None ) → list[dict] of length batch_size. Each dict has
参数
- outputs (
Sapiens2ImageMattingOutput) — 模型的原始输出。 - target_sizes (
torch.Tensor或长度为batch_size的list[tuple[int, int]],可选) — 每个预测所需的最终(height, width)。使用双线性插值进行缩放。如果未设置,预测将以模型输出分辨率返回。 - backgrounds (
ImageInput, 可选) — 用于合成的背景图像。可以是单张图像(应用于批次中的每个元素),也可以是图像列表,每个批次元素对应一张。接受任意 dtype 的 PIL 图像、numpy 数组或 torch 张量;整数类型(例如 uint8)会自动缩放到[0, 1]。提供该参数时,每个结果字典会新增一个"composite"键,其值为合成后的图像,表示为[0, 255]范围内的 uint8 张量。
返回值
长度为 batch_size 的 list[dict]。每个 dict 包含
"alpha"(形状为(1, height, width)的torch.Tensor):[0, 1]范围内的 alpha 值。"foreground"(形状为(3, height, width)的torch.Tensor):位于[0, 1]区间内的预乘 RGB。"composite"(形状为(3, height, width)的torch.Tensor或None):以[0, 255]范围内的 uint8 张量形式,将前景合成到backgrounds之上;当未提供backgrounds时为None。
将 Sapiens2ForImageMatting 的输出转换为 alpha 蒙版和前景图。
post_process_normal_estimation
< source >( outputssource_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = Nonetarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = Nonedo_remove_padding: bool | None = None )
参数
- outputs (
Sapiens2NormalEstimatorOutput) — 模型的原始输出。 - source_sizes (
torch.Tensor或长度为batch_size的list[tuple[int, int]],可选) — 预处理之前每张图像的原始(height, width)。如果提供该参数,预处理过程中添加的填充将被移除,并且预测结果会被缩放回原始图像尺寸(除非target_sizes覆盖了最终尺寸)。 - target_sizes (
torch.Tensor或长度为batch_size的list[tuple[int, int]],可选) — 每个预测所需的最终(height, width)。如果提供,将用作调整大小的目标,而不是source_sizes。在 L2 归一化之后,使用双线性插值进行缩放。 - do_remove_padding (
bool, 可选) — 是否在调整大小之前,裁剪掉预处理过程中添加的零填充。 当提供source_sizes时,默认值为True;否则为False。
将 Sapiens2ForNormalEstimation 的输出转换为 L2 归一化的表面法线图。
post_process_pointmap_estimation
< source >( outputssource_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = Nonetarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = Nonedo_remove_padding: bool | None = None )
参数
- outputs (
Sapiens2PointmapEstimatorOutput) — 模型的原始输出。 - source_sizes (
torch.Tensor或长度为batch_size的list[tuple[int, int]],可选) — 预处理之前每张图像的原始(height, width)。如果提供该参数,预处理过程中添加的填充将被移除,并且预测结果会被缩放回原始图像尺寸(除非target_sizes覆盖了最终尺寸)。 - target_sizes (
torch.Tensor或长度为batch_size的list[tuple[int, int]],可选) — 每个预测所需的最终(height, width)。将覆盖source_sizes作为调整大小的目标。 - do_remove_padding (
bool, 可选) — 是否在调整大小之前,裁剪掉预处理过程中添加的零填充。 当提供source_sizes时,默认值为True;否则为False。
将 Sapiens2ForPointmapEstimation 的输出转换为图像空间中的 pointmap 张量。
post_process_pose_estimation
< source >( outputsboxes: listoutputs_flipped = Nonekernel_size: int = 11threshold: float | None = Nonesource_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = Nonetarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None ) → list[list[dict]]
参数
- outputs (
Sapiens2PoseEstimatorOutput) — 模型的原始输出。outputs.heatmaps的形状必须为(N_total, num_keypoints, heatmap_height, heatmap_width),其中N_total = sum(len(b) for b in boxes)。 - boxes (
list[list[list[float]]]或np.ndarray) — 每张图像的边界框列表或数组,使用绝对像素坐标。每个边界框应为包含 4 个浮点数的列表,表示 COCO 格式下的边界框坐标(top_left_x, top_left_y, width, height)。必须与传递给preprocess的boxes参数相匹配。 - outputs_flipped (
Sapiens2PoseEstimatorOutput,可选) — 在水平翻转的输入上运行模型得到的输出。如果提供该参数,在提取关键点之前,会将热力图与outputs进行平均以提高精度:avg_heatmaps = (outputs.heatmaps + outputs_flipped.heatmaps) / 2。 - kernel_size (
int,可选,默认为 11) — 用于 UDP Dark Pose 细化的高斯模糊的核大小。 - threshold (
float, 可选) — 分数阈值。得分小于或等于该值的关键点将从结果字典中被过滤掉。 - source_sizes (
torch.Tensor或长度为batch_size的list[tuple[int, int]],可选) — 每张图片的原始(height, width)(以像素为单位)。当提供target_sizes时,此参数为必需项,用作缩放关键点与边界框的源坐标空间。 - target_sizes (
torch.Tensor或长度为batch_size的list[tuple[int, int]],可选) — 每张图片期望的输出(height, width)坐标空间。当与source_sizes一起提供时,关键点坐标和边界框将从源空间缩放到目标空间。
返回值
list[list[dict]]
外层列表遍历图像,内层列表遍历人物。 每个字典包含:
keypoints(形状为(num_keypoints, 2)的torch.Tensor):源图像空间中的绝对 x/y 坐标;如果提供了target_sizes,则为目标空间中的坐标。scores(形状为(num_keypoints,)的torch.Tensor):每个关键点的置信度。labels(形状为(num_keypoints,)的torch.LongTensor):关键点索引。bbox(torch.Tensor,形状为(4,)):以绝对坐标 (x_min, y_min, x_max, y_max) 格式表示的边界框,与keypoints处于同一坐标空间。
将 Sapiens2ForPoseEstimation 的输出转换为图像空间中的关键点预测。
post_process_semantic_segmentation
< source >( outputstarget_sizes: list[tuple] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (Sapiens2ForSemanticSegmentation) — 模型的原始输出。
- target_sizes(长度为
batch_size的list[Tuple],可选) — 一个元组列表,对应每个预测所需的最终尺寸(高度、宽度)。如果未设置,预测结果将不会被调整大小。 - return_segmentation_scores (
bool,可选,默认为False) — 是否随分割图一起返回分割分数。当True时,返回列表中的每个元素都是一个SemanticSegmentationPostProcessorOutput,包含字段segmentation(类别 ID,形状为(height, width))和segmentation_scores(形状为(num_classes, height, width))。
返回值
list[torch.Tensor] 或 list[SemanticSegmentationPostProcessorOutput]
当 return_segmentation_scores=False(默认值)时,返回一个长度为 batch_size 的列表,其中每个元素都是形状为 (height, width) 的分割图,包含类别 ID。当 return_segmentation_scores=True 时,返回一个 SemanticSegmentationPostProcessorOutput 列表,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_classes, height, width))。在这两种情况下,(height, width) 对应于目标尺寸(如果指定了 target_sizes)。
将 Sapiens2ForSemanticSegmentation 的输出转换为语义分割图。
Sapiens2Model
class transformers.Sapiens2Model
< source >( config: Sapiens2Config )
参数
- config (Sapiens2Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Sapiens2 模型,直接输出原始隐藏状态。
该模型继承自 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)) — 对应输入图像的张量。可以使用 Sapiens2ImageProcessor 获取像素值。有关详细信息,请参阅 Sapiens2ImageProcessor.call()(processor_class使用 Sapiens2ImageProcessor 处理图像)。 - bool_masked_pos (
torch.BoolTensor,形状为(batch_size, sequence_length),可选) — 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。仅与预训练相关。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Sapiens2Config)和输入。
Sapiens2Model 的 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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch
>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-pretrain-0.4b")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> cls_token = outputs.pooler_output
>>> cls_token.shape
torch.Size([1, 1024])Sapiens2Backbone
class transformers.Sapiens2Backbone
< source >( config: Sapiens2Config )
参数
- config (Sapiens2Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Sapiens2 骨干网络。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sapiens2BackboneOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Sapiens2ImageProcessor 获取像素值。有关详细信息,请参阅 Sapiens2ImageProcessor.call()(processor_class使用 Sapiens2ImageProcessor 处理图像)。
返回值
Sapiens2BackboneOutput 或 tuple(torch.Tensor)
Sapiens2BackboneOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Sapiens2Config)和输入。
Sapiens2Backbone 的 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时存在。
示例:
>>> from transformers import AutoBackbone, AutoImageProcessor
>>> from transformers.image_utils import load_image
>>> import torch
>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
>>> model = AutoBackbone.from_pretrained("facebook/sapiens2-pretrain-0.4b")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs, return_class_token=True)
>>> outputs.feature_maps[0].shape
torch.Size([1, 1024, 64, 48])
>>> outputs.cls_tokens[0].shape
torch.Size([1, 1024])Sapiens2ForImageMatting
class transformers.Sapiens2ForImageMatting
< source >( config: Sapiens2Config )
参数
- config (Sapiens2Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
带有抠图头(一个基于 PixelShuffle 的解码器,用于预测预乘 RGB 前景和 alpha 蒙版)的 Sapiens2 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorlabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sapiens2ImageMattingOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Sapiens2ImageProcessor 获取像素值。有关详细信息,请参阅 Sapiens2ImageProcessor.call()(processor_class使用 Sapiens2ImageProcessor 处理图像)。 - labels(形状为
(batch_size, 4, height, width)的torch.Tensor,可选)— 用于计算损失的真实抠图目标。
返回值
Sapiens2ImageMattingOutput 或 tuple(torch.Tensor)
Sapiens2ImageMattingOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Sapiens2Config)和输入。
Sapiens2ForImageMatting 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss(形状为
(1,)的torch.Tensor,可选,在提供labels时返回)— 损失。alphas(形状为
(batch_size, 1, height, width)的torch.Tensor)— 估计的 alpha 值。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 之后的权重,用于在自注意力头中计算加权平均值。
前景(形状为
(batch_size, 3, height, width)的torch.Tensor)— 在[0, 1]范围内(经过 sigmoid 激活)的预乘 RGB 前景预测。
示例:
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch
>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-matting-1b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-matting-1b")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> outputs.alphas.shape
torch.Size([1, 1, 1024, 768])
>>> outputs.foregrounds.shape
torch.Size([1, 3, 1024, 768])Sapiens2ForNormalEstimation
class transformers.Sapiens2ForNormalEstimation
< source >( config: Sapiens2Config )
参数
- config (Sapiens2Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Sapiens2 模型顶部带有一个法线估计头(一个基于 PixelShuffle 的解码器,用于预测表面法线图)。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorlabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sapiens2NormalEstimatorOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Sapiens2ImageProcessor 获取像素值。有关详细信息,请参阅 Sapiens2ImageProcessor.call()(processor_class使用 Sapiens2ImageProcessor 处理图像)。 - labels(形状为
(batch_size, num_labels, height, width)的torch.Tensor,可选)— 用于计算损失的真实表面法线图。
返回值
Sapiens2NormalEstimatorOutput 或 tuple(torch.Tensor)
Sapiens2NormalEstimatorOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Sapiens2Config)和输入。
Sapiens2ForNormalEstimation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回) — 法线估计损失。 - normals(形状为
(batch_size, num_labels, height, width)的torch.Tensor)— 模型输出的原始法线贴图预测值(未归一化)。 - 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 之后的注意力权重。
示例:
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch
>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-normal-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-normal-0.4b")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> outputs.normals.shape
torch.Size([1, 3, 1024, 768])Sapiens2ForPointmapEstimation
class transformers.Sapiens2ForPointmapEstimation
< source >( config: Sapiens2Config )
参数
- config (Sapiens2Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Sapiens2 模型顶部配备了一个 pointmap 头(一个基于 PixelShuffle 的解码器,用于预测每个像素的 3D XYZ 坐标,并包含一个可选的尺度分支,用于焦距归一化)。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorlabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sapiens2PointmapEstimatorOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Sapiens2ImageProcessor 获取像素值。有关详细信息,请参阅 Sapiens2ImageProcessor.call()(processor_class使用 Sapiens2ImageProcessor 处理图像)。 - labels(形状为
(batch_size, 3, height, width)的torch.Tensor,可选)— 用于计算损失的真实点图。
返回值
Sapiens2PointmapEstimatorOutput 或 tuple(torch.Tensor)
Sapiens2PointmapEstimatorOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Sapiens2Config)和输入。
Sapiens2ForPointmapEstimation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回) — Pointmap 估计损失。 - pointmaps(形状为
(batch_size, 3, height, width)的torch.Tensor)— 在标准相机空间中的逐像素 3D XYZ 坐标预测。 - scales (
torch.Tensor,形状为(batch_size, 1),可选) — 标准焦距与实际焦距的比值。当未配置缩放分支时为None。 - 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 之后的注意力权重。
示例:
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch
>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pointmap-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-pointmap-0.4b")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> outputs.pointmaps.shape
torch.Size([1, 3, 1024, 768])Sapiens2ForPoseEstimation
class transformers.Sapiens2ForPoseEstimation
< source >( config: Sapiens2Config )
参数
- config (Sapiens2Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
在顶部带有姿态估计头的 Sapiens2 模型(在隐藏状态输出之上的一组热图预测器)。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorflip_pairs: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Nonelabel_weights: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sapiens2PoseEstimatorOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Sapiens2ImageProcessor 获取像素值。有关详细信息,请参阅 Sapiens2ImageProcessor.call()(processor_class使用 Sapiens2ImageProcessor 处理图像)。 - flip_pairs(形状为
(num_pairs, 2)的torch.Tensor,可选) — 互为镜像的关键点对(例如,左耳 — 右耳),用于测试时的翻转增强。如果提供了该参数,模型会假设pixel_values包含水平翻转后的图像,并对输出热力图调用flip_back以恢复原始方向。 - labels(形状为
(batch_size, num_keypoints, height, width)的torch.Tensor,可选)— 用于计算损失的热图真值。 - label_weights (
torch.Tensor,形状为(batch_size, num_labels, 1, 1)或(batch_size, num_labels, height, width),可选) — 每个关键点的可见性权重。必须能够广播到labels的形状。
返回值
Sapiens2PoseEstimatorOutput 或 tuple(torch.Tensor)
Sapiens2PoseEstimatorOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Sapiens2Config)和输入。
Sapiens2ForPoseEstimation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回) — 姿态估计损失。热图(形状为
(batch_size, num_keypoints, height, width)的torch.Tensor)— 模型预测的热图。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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch
>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-pose-0.4b")
>>> boxes = [[[270.8, 0.6, 294.1, 379.5]]]
>>> inputs = image_processor(image, boxes=boxes, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> outputs.heatmaps.shape
torch.Size([1, 308, 256, 192])Sapiens2ForSemanticSegmentation
class transformers.Sapiens2ForSemanticSegmentation
< source >( config: Sapiens2Config )
参数
- config (Sapiens2Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
在 Sapiens2 模型顶部添加语义分割头,例如用于 ADE20K、CityScapes。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SemanticSegmenterOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Sapiens2ImageProcessor 获取像素值。有关详细信息,请参阅 Sapiens2ImageProcessor.call()(processor_class使用 Sapiens2ImageProcessor 处理图像)。 - labels(形状为
(batch_size, height, width)的torch.LongTensor,可选) — 用于计算损失的语义分割真值图。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels > 1,则计算分类损失(交叉熵)。
返回值
SemanticSegmenterOutput 或 tuple(torch.Tensor)
一个 SemanticSegmenterOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Sapiens2Config)和输入。
Sapiens2ForSemanticSegmentation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。logits(形状为
(batch_size, config.num_labels, logits_height, logits_width)的torch.Tensor)— 每个像素的分类分数。返回的 logits 的大小不一定与作为输入传入的
pixel_values相同。这样做的目的是避免进行两次插值,从而在用户需要作为后处理将 logits 调整回原始图像大小时损失一些质量。您应始终检查 logits 的形状,并根据需要进行调整。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, patch_size, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
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, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch
>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-seg-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-seg-0.4b")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> outputs.logits.shape
torch.Size([1, 29, 1024, 768])