Sapiens2 视觉骨干与人体任务模型在 🤗 Transformers 中的完整使用指南
【免费下载链接】transformers🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers
导读
Sapiens2 是 Meta 提出的一族以人为中心(human-centric)的高分辨率视觉 Transformer,面向姿态估计、人体部位分割、表面法线估计、点图(pointmap)估计等密集预测任务。本文基于 sapiens2 官方文档,并结合仓库内的 configuration_sapiens2.py、modeling_sapiens2.py、image_processing_sapiens2.py 三个核心源文件,逐项讲解模型架构设计、AutoModel/AutoBackbone/各任务头(Pose/Seg/Normal/Pointmap/Matting)的推理代码、后处理管线以及配置参数语义。读完本文,你将能独立加载官方 checkpoint、完成七类典型调用并理解其后处理与损失计算原理。
模型概览:Sapiens2 是什么
Sapiens2 模型出自论文Sapiens2(Rawal Khirodkar, He Wen, Julieta Martinez, Yuan Dong, Zhaoen Su, Shunsuke Saito)。它是在约 10 亿张经过人工筛选标注的高质量人体图像上预训练的人体视觉模型家族,将掩码图像重建与自蒸馏对比目标结合,同时学习低层与语义特征。按论文摘要,其参数规模从 0.4B 覆盖到 5B,以原生 1K 分辨率训练,并提供用于扩展空间推理的分层 4K 变体;相较前代在姿态估计(+4 mAP)、身体部位分割(+24.3 mIoU)、法线估计(误差降低 45.6%)等指标上均有显著提升,并扩展到 pointmap 与 albedo 估计等新任务。
需要强调的是,上述改进数值均来自论文摘要表述,属于模型自证的结果;在仓库证据层面,你可以直接验证的是:模型于 2026-06-03 被贡献进 Transformers(模型文档 记录了 HF papers 发布于 2026-04-23),官方 checkpoint 均以facebook/sapiens2-*命名存放于 Hub,本仓库的sapiens2模型代码位于 src/transformers/models/sapiens2,由其modular_sapiens2.py模块化源生成modeling_sapiens2.py、configuration_sapiens2.py、image_processing_sapiens2.py三个落地文件。
使用要点(Tips)
- Sapiens2 使用旋转位置编码(RoPE),支持任意输入分辨率;默认图像处理器会把图像缩放到 1024×768(高×宽)。
- 注意力采用分组查询注意力(GQA)用于中间层,首尾各 8 层使用完整多头注意力。
- 默认 8 个register tokens可降低 patch token 上的高范数伪影,产生更干净的注意力图,利于密集预测任务。
架构设计:从源码读懂四个关键设计
理解 Sapiens2Config 中的默认值与 modeling_sapiens2.py 的实现,是后续调参与二次开发的前提。
1. 输入嵌入:CLS + Register + 卷积 Patch
Sapiens2Embeddings 将输入序列构造为[CLS] + register_tokens + patch_embeddings:cls_token作为全局表征;register_tokens(默认 8 个)作为可学习"寄存器"承载冗余信息;patch 投影是一个 kernel 与 stride 均等于patch_size(默认 16)的 Conv2d。此外,当config.use_mask_token=True时还会加入 mask token,配合bool_masked_pos供掩码图像建模(MIM)预训练使用——注意这是预训练专用开关,绝大多数发布的 checkpoint 没有该权重,模型在加载时会忽略缺失的mask_token。
2. 二维连续坐标 RoPE:动态适配任意分辨率
与固定绝对位置编码不同,Sapiens2RopePositionEmbedding 先按输入的实际分辨率动态计算每个 patch 中心的二维归一化坐标[-1, +1](见get_patches_center_coordinates,结果带 lru_cache),再结合inv_freq(基频由rope_theta控制)生成 cos/sin。训练期还支持坐标增强(pos_embed_shift/pos_embed_jitter/pos_embed_rescale,其中pos_embed_rescale默认 2.0),这正是模型"训练时带随机尺度、推理时可处理任意分辨率"的机制来源。RoPE 只施加到 patch token 上,CLS 与 register 前缀 token 不参与旋转(见apply_rotary_pos_emb)。
3. 每层可配置的注意力头数(GQA ↔ MHA)
Sapiens2Config通过num_key_value_heads_per_layer精细控制每一层 KV 头数:等于num_attention_heads即完整多头注意力,更小值即分组查询注意力。若未显式给出,__post_init__会自动填充——首num_first_full_attention_layers(默认 8)与末num_last_full_attention_layers(默认 8)层使用全部注意力头,其余层使用num_key_value_attention_heads(默认 8)。use_qk_norm=True时还会对 Q/K 施加 RMSNorm(eps 默认 1e-6)再进入 RoPE。模型类通过_supports_sdpa / _supports_flash_attn / _supports_flex_attn声明同时支持 SDPA、Flash Attention 与 Flex Attention 后端,可用attn_implementation参数按硬件选择。此外 LayerScale(layerscale_value)与 SiLU 门控 MLP(use_gated_mlp=True,hidden act 为 silu)共同构成了每个 Transformer 层。
4. 统一解码头Sapiens2Head与子配置Sapiens2HeadConfig
所有密集预测任务都复用 Sapiens2Head 作为上采样解码器,其结构参数收敛在 Sapiens2HeadConfig 中,通过head_config子配置注入(sub_configs = {"head_config": Sapiens2HeadConfig})。主要包括三组:
upsample_*:逐级上采样块的输出通道数(首个块输入为hidden_size),kernel 默认 4;也可改用 pixel-shuffle 上采样(use_pixel_shuffle);conv_*:上采样后的精修卷积层,kernel 默认 1;scale_*:用于 pointmap 的焦距尺度分支(stride-2 卷积 + MLP 预测标量),其 MLP 输入维度scale_final_input_size会在配置初始化时依据image_size与patch_size自动推算(_init_scale_final_input_size)。
任务头与输出结构一览
| 任务模型类 | 输出字段 | 说明 |
|---|---|---|
Sapiens2ForPoseEstimation | loss/heatmaps | 308 个关键点高斯热图;支持flip_pairs与可见性加权 MSE |
Sapiens2ForSemanticSegmentation | loss/logits | 29 类人体部位分割 logits;交叉熵 +semantic_loss_ignore_index(255) |
Sapiens2ForNormalEstimation | loss/normals | 原始未归一化 XYZ 法线图 |
Sapiens2ForPointmapEstimation | loss/pointmaps/scales | 相机空间逐像素 XYZ 坐标与焦距比例 |
Sapiens2ForImageMatting | loss/alphas/foregrounds | sigmoid 激活的 alpha 与前/背景分离结果 |
Sapiens2Backbone | feature_maps/cls_tokens | 多阶段空间特征 + 各阶段 CLS |
自动映射关系可在 modeling_auto.py 中确认:sapiens2同时注册了AutoModelForSemanticSegmentation / AutoModelForImageMatting / AutoModelForNormalEstimation / AutoModelForPointmapEstimation / AutoModelForPoseEstimation等入口。
快速上手:checkpoint 与基础环境
所有示例均以官方 0.4B checkpoint 为例,命名规律为facebook/sapiens2-{pretrain|seg|pose|normal|pointmap|matting}-{0.4b|1b|...}。模型与图像处理器通过Auto*接口加载,device_map="auto"便于异构设备推理。代码中的load_image同时支持本地图片路径与网络图片 URL 输入(本地路径建议使用绝对路径,例如load_image("/path/to/your_image.jpg"))。若运行姿态估计相关后处理,还需安装opencv-python(pip install opencv-python)。
1. AutoModel:获取整图嵌入(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]从 Sapiens2Model.forward 的实现看,pooler_output即最终sequence_output[:, 0, :]——取经过层归一化的序列中第一个位置(CLS token),维度等于hidden_size(1024)。
2. AutoBackbone:直接取空间特征图
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]代码层面,Backbone 会去掉每阶段序列中的前缀 token(num_prefix = 1 + num_register_tokens)后按num_patches_h × num_patches_w重塑并转置到(B, C, H, W)布局。是否整形由reshape_hidden_states(默认 True)控制,输出前还可按normalize_backbone_outputs(默认 True)对特征施加 RMSNorm;stage_names = ["stem", "stage1", ..., "stageN"]可用于选择输出阶段。
3. 表面法线估计(Normal Estimation)
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]可视化片段(法线值域[-1,1]→ RGB[0,255],并用分割结果去背景):
# 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]模型输出的normals是未经归一化的原始 XYZ 向量(归一化在训练中以监督信号形式存在),因此文档示例通过post_process_normal_estimation统一完成"去 padding、缩放回原尺寸、L2 归一化到单位向量"三步,target_sizes传入原图尺寸即可。
4. 点图估计(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]可视化片段(用逆深度 + turbo 色带渲染 pointmap):
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]pointmap 输出包含"人体在规范相机空间中的逐像素三维坐标"。模型配置为 pointmap 任务额外构造了Sapiens2PointmapScaleHead(对应head_config中的scale_*配置组)以回归"规范焦距/真实焦距"比例,因此post_process_pointmap_estimation会把该尺度应用到预测坐标上,得到更接近真实尺度的三维结构。
5. 姿态估计:单人框关键点检测
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)姿态推理的预处理是"检测框驱动"的:从 image_processing_sapiens2.py 可见,boxes(COCO 格式 x/y/w/h)会先经boxes_to_crop_params计算裁剪中心与尺度(默认外扩 padding=1.25,并按目标长宽比校正),再经crop_and_resize完成仿射等效裁剪缩放(等价于原版 Sapiens2 代码库中 rotation=0 的 cv2 仿射 warp,缩小用双线性、放大用双三次)。返回的 heatmaps 是"每人每关键点"的高斯热图(0.4B 姿态模型为 308 关键点)。
6. 姿态估计增强:水平翻转测试时增强
翻转增强(TTA)通过平均原图与镜像图的预测来提升关键点精度。将[left_keypoint, right_keypoint]配对张量flip_pairs传给第二次前向,模型会先把热图翻回原方向再返回(内部调用flip_back),因此两份输出可直接平均:
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"]flip_pairs存放于config(形如[[左耳, 右耳], ...])。参考 flip_back 的实现可知:镜像热图会按左右对交换关键点通道,再沿宽轴翻转回原方向(若为回归型 target 还需把 offset 通道取负)。把两次前向的结果同时交给post_process_pose_estimation,后处理内部完成平均后再解码。
7. 姿态估计训练:带可见性权重的掩码 MSE
将labels(GT 热图)与可选的label_weights传给模型即可在 forward 中直接得到损失,方便接入Trainer微调:
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())从 Sapiens2ForPoseEstimation.forward 可见损失即F.mse_loss(heatmaps, labels, weight=label_weights):label_weights形状(B, K, 1, 1)或与热图同尺寸均可,对遮挡/不可见关键点置 0 即可屏蔽其梯度贡献。其余各任务(分割、法线、pointmap、matting)也都支持传入labels返回loss字段。
8. 语义分割:人体部位解析
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]0.4B 分割 checkpoint 输出 29 类人体部位 logits(num_labels=29),即前面法线/pointmap 可视化示例中所使用的背景掩码来源(class 0 为背景)。该模型还支持在预处理时同时传入segmentation_maps(配合do_reduce_labels处理 ADE20k 等数据集的背景标签移位),训练损失使用带semantic_loss_ignore_index(默认 255)的交叉熵。
9. 图像抠像(Matting)
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]Matting 任务输出 sigmoid 激活、值域[0,1]的 alpha 与"预乘"前景(Sapiens2ImageMattingOutput中的alphas/foregrounds)。post_process_image_matting负责把结果缩放回目标尺寸,并按公式composite = foreground * (1 - alpha) * background合成抠像预览图——背景既可以是(3,1,1)纯色张量,也接受 PIL 图像或 numpy 数组。
ImageProcessor 后处理能力速查
Sapiens2ImageProcessor 的默认配置为size = {"height": 1024, "width": 768}、do_resize=True,均值方差采用 ImageNet 默认值。除了各示例中用到的方法,预处理还支持segmentation_maps(语义分割标注)与boxes(姿态检测框)输入。任务级后处理方法如下:
| 后处理方法 | 对应任务 | 主要行为 |
|---|---|---|
post_process_semantic_segmentation | 分割 | argmax 得到逐像素类别,可选target_sizes回缩原尺寸 |
post_process_pose_estimation | 姿态 | 解码热图为坐标(kernel_size默认 11 的高斯模糊去偏 + 阈值),支持 TTA 平均,返回{keypoints, scores} |
post_process_normal_estimation | 法线 | 去 padding、重采样、L2 归一化到[-1,1] |
post_process_pointmap_estimation | 点图 | 去 padding、重采样、施加焦距尺度 |
post_process_image_matting | 抠像 | 拆分alpha/foreground,可选背景合成composite |
其中姿态解码属于 DARK(无偏数据处理)风格:先对热图做保留峰值的gaussian_blur_preserve_max模糊,再基于泰勒展开做亚像素偏移修正(post_dark_unbiased_data_processing),因此post_process_pose_estimation返回的关键点坐标是浮点精度的图像空间坐标。
配置速查:关键参数一览
下表汇总 Sapiens2Config 的高频参数(model_type = "sapiens2",并集成BackboneConfigMixin,可通过out_features/out_indices选择骨干阶段):
| 参数 | 默认值 | 语义 |
|---|---|---|
hidden_size/intermediate_size | 1024 / 4096 | 隐藏维度与 MLP 中间维度 |
num_hidden_layers/num_attention_heads | 24 / 16 | Transformer 层数与注意力头数 |
patch_size/image_size | 16 / 224 | patch 尺寸与预训练图像尺寸 |
num_register_tokens | 8 | register token 数量 |
rope_theta | 100.0 | RoPE 基频 |
use_gated_mlp/hidden_act | True /silu | SwiGLU 门控 MLP |
num_key_value_attention_heads | 8 | GQA 层 KV 头数 |
num_first/last_full_attention_layers | 8 / 8 | 首尾使用完整注意力的层数 |
use_qk_norm/rms_norm_eps | True / 1e-6 | QK 归一化与 RMSNorm eps |
layerscale_value | 1.0 | LayerScale 初值 |
pos_embed_rescale | 2.0 | 训练期 RoPE 坐标随机缩放幅度 |
semantic_loss_ignore_index | 255 | 分割损失的忽略标签 |
flip_pairs | None | 姿态 TTA 的左右关键点配对 |
head_config | None | 解码头子配置Sapiens2HeadConfig |
小结
Sapiens2 在 Transformers 中的集成是"编码器 + 统一解码头 + 任务后处理"的清晰范式:主干支持任意分辨率推理、register tokens 与 QK-norm,解码头由 Sapiens2HeadConfig 声明式配置,五个任务通过各自的AutoModelFor*入口开箱即用,法线、pointmap 等原始输出再经 ImageProcessor 的后处理方法完成坐标/通道语义的还原。你可以基于本文示例直接替换 checkpoint 名进行实验,也可以从 modular_sapiens2.py 出发了解官方模型是如何以模块化方式维护与生成代码的。该模型代码版权归属 Meta Platforms, Inc. 与 HuggingFace Inc.,遵循 Sapiens2 License,使用时请留意对应许可条款。
【免费下载链接】transformers🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考