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

OpenVINO多输入模型调用set_input_tensor报错:inputs.size() == 1

问题原因
  1. 未指定输入目标:你的模型有图像、文本多个输入,直接调用set_input_tensor()时,OpenVINO无法确定要给哪个输入赋值,因此触发"输入数量需为1"的错误。
  2. 输入逻辑错误:CLIP类模型要求同时传入图像和文本输入才能正常推理,你分开单独输入图像或文本的方式不符合模型设计逻辑。
  3. 冗余资源消耗:循环里每次创建新的InferRequest完全没必要,复用一个推理请求就能完成所有样本处理。
修正后的代码
from openvino.runtime import Core, Tensor
import torch

def toto(model, processor, image1, image2, image3, text1, text2, text3, is_openvino=False):
    # 统一生成模型输入格式
    inputs = processor(text=[text1, text2, text3], images=[image1, image2, image3], return_tensors="pt", padding=True)

    if is_openvino:
        # 获取模型输入节点名称(提前确认输入名,避免匹配错误)
        input_names = [inp.get_any_name() for inp in model.inputs]
        pixel_values_name = next(name for name in input_names if "pixel_values" in name)
        input_ids_name = next(name for name in input_names if "input_ids" in name)
        
        # 转换为OpenVINO兼容的numpy数组
        pixel_values_np = inputs["pixel_values"].numpy()
        input_ids_np = inputs["input_ids"].numpy()
        
        image_embeddings = []
        infer_request = model.create_infer_request()  # 仅创建一次推理请求
        
        # 逐个处理样本:图像+文本配对输入
        for idx in range(3):
            # 分别设置图像和文本输入张量
            infer_request.set_input_tensor(pixel_values_name, Tensor(pixel_values_np[idx]))
            infer_request.set_input_tensor(input_ids_name, Tensor(input_ids_np[idx]))
            # 执行推理
            infer_request.infer()
            
            # 获取图像嵌入(可通过model.outputs确认输出顺序或名称)
            image_embed = infer_request.get_output_tensor(0).data
            image_embeddings.append(image_embed)
        
        x1 = image_embeddings[0]
        x2 = image_embeddings[1]
        x3 = image_embeddings[2]
    else:
        # PyTorch原生逻辑保持不变
        outputs = model(**inputs)
        x1 = outputs.image_embeds[0]
        x2 = outputs.image_embeds[1]
        x3 = outputs.image_embeds[2]

    # 计算余弦相似度并返回结果
    sim_x1_x2 = torch.nn.functional.cosine_similarity(torch.tensor(x1), torch.tensor(x2), dim=0)
    sim_x1_x3 = torch.nn.functional.cosine_similarity(torch.tensor(x1), torch.tensor(x3), dim=0)

    return sim_x1_x2 > sim_x1_x3
关键调整说明
  • 明确输入目标:通过输入节点名称调用set_input_tensor(name, tensor),让OpenVINO清楚要给哪个输入赋值。
  • 配对输入数据:每次推理同时传入对应样本的图像和文本,符合CLIP模型的输入要求。
  • 复用推理请求:避免重复创建推理请求,减少资源开销。
  • 提取输出数据:调用.data获取张量的numpy格式数据,方便后续转换为PyTorch张量计算相似度。
额外检查点
  • 可以通过print([inp.get_any_name() for inp in model.inputs])打印所有输入名称,确保和代码中的匹配。
  • 如果你的模型还需要attention_mask输入,需额外添加该张量的设置逻辑,参考processor输出是否包含此键。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:09:59