You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Grounding DINO多模态模型的结构摘要?

问题

我想获取Grounding DINO的模型结构摘要,用了torch-summary库,但这个库要求指定正确的输入尺寸。因为Grounding DINO是多模态模型(输入为图像+文本对),我不确定该给summary函数传什么输入尺寸和格式。

我试过几种input_size参数:

  • 仅传图像尺寸(比如(3, 244, 244))
  • 包含图像尺寸和文本提示的列表(比如[(3, 244, 244), 'some text'])
  • 扩展文本输入长度的图像尺寸(比如(3, 244, 244, 10))
  • 包含图像尺寸和文本输入长度的列表(比如[(3, 244, 244), 10]、[(3, 244, 244), (10,)])

但所有尝试都报错:只传图像尺寸会触发KeyError,提示缺少'captions'关键字输入;传实际图像和文本会触发TypeError,提示字符串索引必须为整数;传字典格式输入会被torch-summary判定为无效输入类型。

我查了Grounding DINO的预测代码和forward方法还是解决不了,需求是拿到类似torch-summary提供的模型结构信息,不一定非要用这个库,请问该怎么实现?

解决方案

方法1:用torchinfo替代torch-summary(支持多模态/字典输入)

torchinfo是torch-summary的升级版本,原生支持字典、多输入等复杂格式,完全适配Grounding DINO的输入要求。

步骤:

  1. 安装torchinfo:
pip install torchinfo
  1. 构造符合模型要求的输入字典,传入torchinfo生成结构摘要:
import torch
from groundingdino.models import build_model
from groundingdino.util.slconfig import SLConfig
from torchinfo import summary

# 加载Grounding DINO模型
config_path = "groundingdino/config/GroundingDINO_SwinT_OGC.py"
args = SLConfig.fromfile(config_path)
model = build_model(args)
model.eval()

# 构造模拟输入:图像张量+文本列表
batch_size = 1
# 图像输入:(batch_size, 3, H, W),示例用224x224
img_tensor = torch.randn(batch_size, 3, 224, 224)
# 文本输入:列表形式,每个元素对应一个batch的文本提示
text_prompts = ["cat, dog"] * batch_size

# 打包成模型forward需要的字典格式
input_dict = {
    "image": img_tensor,
    "caption": text_prompts
}

# 生成结构摘要,指定batch_dim=0对应图像的batch维度
summary(model, input_data=input_dict, batch_dim=0, verbose=2)

方法2:手动打印模型结构(简单直接)

如果只需要查看层级结构,不需要参数统计和输出形状,可以直接遍历模型子模块:

# 加载模型代码同上
print("Grounding DINO模型结构:")
for name, module in model.named_modules():
    if len(list(module.children())) == 0:  # 仅打印叶子模块
        param_count = sum(p.numel() for p in module.parameters())
        print(f"{name}: {type(module).__name__}, 参数总量: {param_count}")

或者直接打印整个模型的层级结构:

print(model)

这种方式能快速看到模型的层级划分,但没有torchinfo那样的详细参数统计和输出形状信息。

方法3:用torchviz可视化计算图(可选)

如果需要直观查看模型的数据流和参数依赖,可以用torchviz生成可视化图:

  1. 安装依赖:
pip install torchviz
# 系统依赖:Linux用sudo apt-get install graphviz,macOS用brew install graphviz
  1. 生成可视化图:
from torchviz import make_dot

# 前向传播一次获取输出
output = model(**input_dict)
# 生成计算图并保存为PDF
dot = make_dot(output, params=dict(model.named_parameters()))
dot.render("groundingdino_compute_graph")

执行后会生成一个PDF文件,清晰展示模型的计算流程和参数关联。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:04:49