YoloSharp icon indicating copy to clipboard operation
YoloSharp copied to clipboard

你好,我在训练 TaskType="Detection" 时 当标注的图像,标注内容为空时(本意想在训练集中加入正样本),会报这个异常!,请修复它。

Open YN00315 opened this issue 5 months ago • 8 comments

Sizes of tensors must match except in dimension 0. Expected size 640 but got size 1280 for tensor number 4 in the list. Exception raised from check_cat_shape_except_dim at C:\actions-runner_work\pytorch\pytorch\pytorch\aten\src\ATen/native/TensorShape.h:45 (most recent call first): 00007FFC1F88220900007FFC1F882160 c10.dll!c10::Error::Error [ @ ] 00007FFC1F880C7A00007FFC1F880C20 c10.dll!c10::detail::torchCheckFail [ @ ] 00007FFBD9AA3F6400007FFBD9AA36B0 torch_cpu.dll!at::meta::structured_cat::meta [ @ ] 00007FFBDA5421E400007FFBDA53DC90 torch_cpu.dll!at::cpu::var_outf [ @ ] 00007FFBDA533EB600007FFBDA51EE00 torch_cpu.dll!at::cpu::bitwise_or_outf [ @ ] 00007FFBD9F3286500007FFBD9F327E0 torch_cpu.dll!at::_ops::cat::redispatch [ @ ] 00007FFBDBA2F8EB00007FFBDBA115D0 torch_cpu.dll!torch::autograd::UndefinedGradBackward::apply_with_saved [ @ ] 00007FFBDBA2CE4C00007FFBDBA115D0 torch_cpu.dll!torch::autograd::UndefinedGradBackward::apply_with_saved [ @ ] 00007FFBD9EA8AC600007FFBD9EA89C0 torch_cpu.dll!at::_ops::cat::call [ @ ] 00007FFC4A2BB06900007FFC4A2BAF50 LibTorchSharp.DLL!THSTensor_cat [ @ ] 00007FFBAA643256 ! [ @ ]

YN00315 avatar Jun 05 '26 08:06 YN00315

另外可以把 yolov11n-cls.bin yolov11n-obb.bin yolov11n-pose.bin 这几个也加入到PreTrainedModels文件夹内吗

YN00315 avatar Jun 05 '26 08:06 YN00315

我在 private static Dictionary<string, torch.Tensor> Collate(IEnumerable<Dictionary<string, torch.Tensor>> dic, torch.Device device) { using (torch.NewDisposeScope()) using (torch.no_grad()) { Dictionary<string, torch.Tensor> dictionary = new Dictionary<string, torch.Tensor>(); torch.Tensor[] classes = dic.Select((Dictionary<string, torch.Tensor> k) => k["cls"].unsqueeze(0)).ToArray(); Tensor[] batch_ids = new Tensor[classes.Length]; for (int i = 0; i < classes.Length; i++) { batch_ids[i] = torch.full(new long[] { classes[i].shape[1] }, i, classes[i].dtype, device); } dictionary["batch_idx"] = torch.cat(batch_ids, 0).unsqueeze(-1).MoveToOuterDisposeScope();

            foreach (string x in dic.First().Keys)
            {
                Console.WriteLine($"Collating key: {x}");
                var tensorList = dic.Select(k => k[x]).ToList();
                for (int i = 0; i < tensorList.Count; i++)
                {
                    Console.WriteLine($"  sample {i} shape: [{string.Join(",", tensorList[i].shape.ToArray())}]");
                }
                torch.Tensor tensor = torch.cat(dic.Select((Dictionary<string, torch.Tensor> k) => k[x]).ToArray(), 0);
                if (tensor.device_type != device.type || tensor.device_index != device.index)
                {
                    tensor = tensor.to(device);
                }

                dictionary[x] = tensor.MoveToOuterDisposeScope();
            }
            return dictionary;
        }
    }

这个方法中打印了输出 得到了报错时的输出内容如下 Collating key: cls sample 0 shape: [1,1] sample 1 shape: [5,1] sample 2 shape: [2,1] sample 3 shape: [6,1] sample 4 shape: [2,1] sample 5 shape: [3,1] sample 6 shape: [9,1] sample 7 shape: [6,1] Collating key: bboxes sample 0 shape: [1,4] sample 1 shape: [5,4] sample 2 shape: [2,4] sample 3 shape: [6,4] sample 4 shape: [2,4] sample 5 shape: [3,4] sample 6 shape: [9,4] sample 7 shape: [6,4] Collating key: images sample 0 shape: [1,3,640,640] sample 1 shape: [1,3,640,640] sample 2 shape: [1,3,640,640] sample 3 shape: [1,3,640,640] sample 4 shape: [1,3,640,640] sample 5 shape: [1,3,640,640] sample 6 shape: [1,3,640,640] sample 7 shape: [1,3,640,640] Collating key: cls sample 0 shape: [6,1] sample 1 shape: [11,1] sample 2 shape: [4,1] sample 3 shape: [3,1] sample 4 shape: [4,1] sample 5 shape: [0,1] Collating key: bboxes sample 0 shape: [6,4] sample 1 shape: [11,4] sample 2 shape: [4,4] sample 3 shape: [3,4] sample 4 shape: [4,4] sample 5 shape: [0,4] Collating key: images sample 0 shape: [1,3,640,640] sample 1 shape: [1,3,640,640] sample 2 shape: [1,3,640,640] sample 3 shape: [1,3,640,640] sample 4 shape: [1,3,640,640] sample 5 shape: [1,3,1280,1280] 希望有助于你找到问题所在

YN00315 avatar Jun 05 '26 12:06 YN00315

我在 private static Dictionary<string, torch.Tensor> Collate(IEnumerable<Dictionary<string, torch.Tensor>> dic, torch.Device device) { using (torch.NewDisposeScope()) using (torch.no_grad()) { Dictionary<string, torch.Tensor> dictionary = new Dictionary<string, torch.Tensor>(); torch.Tensor[] classes = dic.Select((Dictionary<string, torch.Tensor> k) => k["cls"].unsqueeze(0)).ToArray(); Tensor[] batch_ids = new Tensor[classes.Length]; for (int i = 0; i < classes.Length; i++) { batch_ids[i] = torch.full(new long[] { classes[i].shape[1] }, i, classes[i].dtype, device); } dictionary["batch_idx"] = torch.cat(batch_ids, 0).unsqueeze(-1).MoveToOuterDisposeScope();

            foreach (string x in dic.First().Keys)
            {
                Console.WriteLine($"Collating key: {x}");
                var tensorList = dic.Select(k => k[x]).ToList();
                for (int i = 0; i < tensorList.Count; i++)
                {
                    Console.WriteLine($"  sample {i} shape: [{string.Join(",", tensorList[i].shape.ToArray())}]");
                }
                torch.Tensor tensor = torch.cat(dic.Select((Dictionary<string, torch.Tensor> k) => k[x]).ToArray(), 0);
                if (tensor.device_type != device.type || tensor.device_index != device.index)
                {
                    tensor = tensor.to(device);
                }

                dictionary[x] = tensor.MoveToOuterDisposeScope();
            }
            return dictionary;
        }
    }

这个方法中打印了输出 得到了报错时的输出内容如下 Collating key: cls sample 0 shape: [1,1] sample 1 shape: [5,1] sample 2 shape: [2,1] sample 3 shape: [6,1] sample 4 shape: [2,1] sample 5 shape: [3,1] sample 6 shape: [9,1] sample 7 shape: [6,1] Collating key: bboxes sample 0 shape: [1,4] sample 1 shape: [5,4] sample 2 shape: [2,4] sample 3 shape: [6,4] sample 4 shape: [2,4] sample 5 shape: [3,4] sample 6 shape: [9,4] sample 7 shape: [6,4] Collating key: images sample 0 shape: [1,3,640,640] sample 1 shape: [1,3,640,640] sample 2 shape: [1,3,640,640] sample 3 shape: [1,3,640,640] sample 4 shape: [1,3,640,640] sample 5 shape: [1,3,640,640] sample 6 shape: [1,3,640,640] sample 7 shape: [1,3,640,640] Collating key: cls sample 0 shape: [6,1] sample 1 shape: [11,1] sample 2 shape: [4,1] sample 3 shape: [3,1] sample 4 shape: [4,1] sample 5 shape: [0,1] Collating key: bboxes sample 0 shape: [6,4] sample 1 shape: [11,4] sample 2 shape: [4,4] sample 3 shape: [3,4] sample 4 shape: [4,4] sample 5 shape: [0,4] Collating key: images sample 0 shape: [1,3,640,640] sample 1 shape: [1,3,640,640] sample 2 shape: [1,3,640,640] sample 3 shape: [1,3,640,640] sample 4 shape: [1,3,640,640] sample 5 shape: [1,3,1280,1280] 希望有助于你找到问题所

Thanks for raising the issue. Are you trying to say that there are background images in your dataset (just images, but no label txt files in the labels folder)?

IntptrMax avatar Jun 05 '26 13:06 IntptrMax

另外可以把 yolov11n-cls.bin yolov11n-obb.bin yolov11n-pose.bin 这几个也加入到PreTrainedModels文件夹内吗

The total size of files that can be uploaded to GitHub code is limited, so not all nano models were included. However, these weight files can be uploaded in the releases later. I will organize these pre-trained weights and update the releases soon. If you need to use these weights now, you can refer to the following URLs. https://github.com/IntptrMax/YoloSharp/issues/25 https://github.com/IntptrMax/YoloSharp/releases

IntptrMax avatar Jun 05 '26 13:06 IntptrMax

我在私人静态字典<string, torch.Tensor> 整理(IEnumerable<Dictionary<string, torch.Tensor>> dic, torch.Device device) {使用(torch.NewDisposeScope()) 使用(torch.no_grad()) { Dictionary<string, torch.Tensor> dictionary = new Dictionary<string, torch.Tensor>(); torch.Tensor[] classes = dic.Select((Dictionary<string, torch.Tensor> k) => k["cls"].unsqueeze(0))。ToArray();张量[] batch_ids = new Tensor[classes.Length];for (int i = 0; i < classes.Length; i++) { batch_ids[i] = torch.full(new long[] { classes[i].shape[1] }, i, classes[i].dtype, device); } dictionary[“batch_idx”] = torch.cat(batch_ids, 0).unsqueeze(-1)。MoveToOuterDisposeScope();

            foreach (string x in dic.First().Keys)
            {
                Console.WriteLine($"Collating key: {x}");
                var tensorList = dic.Select(k => k[x]).ToList();
                for (int i = 0; i < tensorList.Count; i++)
                {
                    Console.WriteLine($"  sample {i} shape: [{string.Join(",", tensorList[i].shape.ToArray())}]");
                }
                torch.Tensor tensor = torch.cat(dic.Select((Dictionary<string, torch.Tensor> k) => k[x]).ToArray(), 0);
                if (tensor.device_type != device.type || tensor.device_index != device.index)
                {
                    tensor = tensor.to(device);
                }

                dictionary[x] = tensor.MoveToOuterDisposeScope();
            }
            return dictionary;
        }
    }

这个方法中打印了输出报错时的输出内容如下整理键:cls样本0形状:[1,1]样本1形状:[5,1]样本2形状:[2,1]样本3形状:[6,1]样本4形状:[2,1]样本5形状:[3,1]样本6形状:[9,1]样本7形状:[6,1]整理键:bboxes样本0形状:[1,4]样本1形状:[5,4]样本2形状:[2,4]样本3形状:[6,4]样本4]样本4形状:[3,4]样本7形状:[9,4]样本7形状:[6,4]整理密钥:图像样本0形状:[1,3,3,640,640]样本1形状:[1,640]样本2形状:[1,3,640,6形状:[1,3,640,640]样本7形状:[1,3,640,640] 整理键:cls样本0形状:[6,1]样本1形状:[11,1]样本2形状:[4,1]样本3形状:[3,1]样本4形状:[4,1]样本5形状:[0,1]整理键:bboxs样本0形状:[6,4]样本1形状:[11,4]样本2形状:[4,4]样本3形状:[4]样本5形状:[4,4]样本5形状:[0,4]整理键:图像样本0形状:[1,3,3,640,640]样本1形状:[1,3,640,640]样本3形状:[1,640,640]样本4形状:[1,640]样本4形状:[

感谢您提出这个问题。您是想说您的数据集中有背景图像(只有图像,但标签文件夹中没有标签txt文件)吗?

有对应的txt文件,但是文件里面是空的没有标注数据,我现在也不知道这个bug是不是这个原因

YN00315 avatar Jun 05 '26 13:06 YN00315

我在私人静态字典<string, torch.Tensor> 整理(IEnumerable<Dictionary<string, torch.Tensor>> dic, torch.Device device) {使用(torch.NewDisposeScope()) 使用(torch.no_grad()) { Dictionary<string, torch.Tensor> dictionary = new Dictionary<string, torch.Tensor>(); torch.Tensor[] classes = dic.Select((Dictionary<string, torch.Tensor> k) => k["cls"].unsqueeze(0))。ToArray();张量[] batch_ids = new Tensor[classes.Length];for (int i = 0; i < classes.Length; i++) { batch_ids[i] = torch.full(new long[] { classes[i].shape[1] }, i, classes[i].dtype, device); } dictionary[“batch_idx”] = torch.cat(batch_ids, 0).unsqueeze(-1)。MoveToOuterDisposeScope();

            foreach (string x in dic.First().Keys)
            {
                Console.WriteLine($"Collating key: {x}");
                var tensorList = dic.Select(k => k[x]).ToList();
                for (int i = 0; i < tensorList.Count; i++)
                {
                    Console.WriteLine($"  sample {i} shape: [{string.Join(",", tensorList[i].shape.ToArray())}]");
                }
                torch.Tensor tensor = torch.cat(dic.Select((Dictionary<string, torch.Tensor> k) => k[x]).ToArray(), 0);
                if (tensor.device_type != device.type || tensor.device_index != device.index)
                {
                    tensor = tensor.to(device);
                }

                dictionary[x] = tensor.MoveToOuterDisposeScope();
            }
            return dictionary;
        }
    }

这个方法中打印了输出报错时的输出内容如下整理键:cls样本0形状:[1,1]样本1形状:[5,1]样本2形状:[2,1]样本3形状:[6,1]样本4形状:[2,1]样本5形状:[3,1]样本6形状:[9,1]样本7形状:[6,1]整理键:bboxes样本0形状:[1,4]样本1形状:[5,4]样本2形状:[2,4]样本3形状:[6,4]样本4]样本4形状:[3,4]样本7形状:[9,4]样本7形状:[6,4]整理密钥:图像样本0形状:[1,3,3,640,640]样本1形状:[1,640]样本2形状:[1,3,640,6形状:[1,3,640,640]样本7形状:[1,3,640,640] 整理键:cls样本0形状:[6,1]样本1形状:[11,1]样本2形状:[4,1]样本3形状:[3,1]样本4形状:[4,1]样本5形状:[0,1]整理键:bboxs样本0形状:[6,4]样本1形状:[11,4]样本2形状:[4,4]样本3形状:[4]样本5形状:[4,4]样本5形状:[0,4]整理键:图像样本0形状:[1,3,3,640,640]样本1形状:[1,3,640,640]样本3形状:[1,640,640]样本4形状:[1,640]样本4形状:[

感谢您提出这个问题。您是想说您的数据集中有背景图像(只有图像,但标签文件夹中没有标签txt文件)吗?

有对应的txt文件,但是文件里面是空的没有标注数据,我现在也不知道这个bug是不是这个原因

A txt file with no content is not valid in the dataset itself. If you just want to have a background image, you shouldn’t add a corresponding txt file in the labels folder.
However, the issue you encountered is something others might run into as well, and it probably isn’t too hard to fix. I can try to fix it in the next version. Thanks again for raising this issue.

IntptrMax avatar Jun 05 '26 13:06 IntptrMax

我在私人静态字典<string, torch.Tensor> 整理(IEnumerable<Dictionary<string, torch.Tensor>> dic, torch.Device device) {使用(torch.NewDisposeScope()) 使用(torch.no_grad()) { Dictionary<string, torch.Tensor> dictionary = new Dictionary<string, torch.Tensor>(); torch.Tensor[] classes = dic.Select((Dictionary<string, torch.Tensor> k) => k["cls"].unsqueez(0))。ToArray();张量[] batch_ids = new Tensor[classes.Length];for (int i = 0; i < classes.Length; i++) { batch_ids[i] = torch.full(new long[] { classes[i].shape[1] }, i, classes[i].dtype, device); } dictionary[“batch_idx”] = torch.cat(batch_ids, 0).unsqueeze(-1)。MoveToOuterDisposeScope();

            foreach (string x in dic.First().Keys)
            {
                Console.WriteLine($"Collating key: {x}");
                var tensorList = dic.Select(k => k[x]).ToList();
                for (int i = 0; i < tensorList.Count; i++)
                {
                    Console.WriteLine($"  sample {i} shape: [{string.Join(",", tensorList[i].shape.ToArray())}]");
                }
                torch.Tensor tensor = torch.cat(dic.Select((Dictionary<string, torch.Tensor> k) => k[x]).ToArray(), 0);
                if (tensor.device_type != device.type || tensor.device_index != device.index)
                {
                    tensor = tensor.to(device);
                }

                dictionary[x] = tensor.MoveToOuterDisposeScope();
            }
            return dictionary;
        }
    }

在这种方法中打印输出错误时的输出内容如下整理键:cls样本0形状:[1,1]样本1形状:[5,1]样本2形状:[2,1]样本3:[6,1]样本4形状:[2,1]样本5形状:[3,1]样本6形状:[9,1]样本7形状:[6,1]整理键:bboxes样本0形状:[1,4]样本1形状[5,4]形状样本2:[2,4]样本4]样本4形状:[3,4]样本7形状:[9,4]样本7形状:[6,4]样本整理样本样本样本样本0形状:[1,3,640]样本样本1形状:[1,640]样本2形状:[1,3,640,640,6形状:[1,640]样本7形状:

感谢您提出这个问题。您是想说您的数据集中有背景图像(只有图像,但标签文件夹中没有标签txt文件)吗?

有对应的txt文件,但是文件里面是空的没有标注数据,我现在也不知道这个bug是不是这个原因

没有内容的txt文件在数据集本身中无效。如果您只想拥有背景图像,您不应在标签文件夹中添加相应的txt文件。然而,您遇到的问题是其他人也可能遇到的问题,而且可能解决并不难。我可以尝试在下一个版本中修复它。再次感谢您提出这个问题。

我的数据集有14张图片,验证集有4张,我训练设置轮数100,每次不是训练完整周期都会报错,但报错的次数也挺频繁的,我觉得可能不是你说的空文件原因,另外想要添加背景图片只要不添加对应的txt文件就好了吗?

YN00315 avatar Jun 05 '26 13:06 YN00315

【1】:从标签的数据获取上: var labelPath = GetLabelPathByImagePath(ImagePaths[(int)index]); if (File.Exists(labelPath) == false) { return (image.MoveToOuterDisposeScope(), torch.zeros(new long[] { 0, 5 }, dtype, device).MoveToOuterDisposeScope()); }

string[] lines = File.ReadAllLines(labelPath);

if (lines.Length == 0) { return (image.MoveToOuterDisposeScope(), torch.zeros(new long[] { 0, 5 }, dtype, device).MoveToOuterDisposeScope()); }

【2】:可能问题出现在训练这里: Tensor imageTensor = concat(images); Tensor labelTensor = concat(labels); if (labelTensor.shape[0] == 0) { continue; }

/*=======================================================

模型向前传播和计算损失 =========================================================*/ Tensor[] list = yolo.forward(imageTensor); var (ls, ls_item) = objloss.forward(list, labelTensor); 理论上应该是if (labelTensor.shape[0] == 0) 图像要向前传播,只是不做loss的计算,因为原版中特别强调1%左右的背景图像,也是标注文件为空的情况,如果不处理的话,模型是不能学习单例(就1个类别的模型的) 【3】应该是: 图像要向前传播,无标签的不做loss计算,如下:

Tensor[] list = yolo.forward(imageTensor); if (labelTensor.shape[0] > 0) { var (ls, ls_item) = objloss.forward(list, labelTensor); var lr = optimizer.ParamGroups.Select(x => x.LearningRate).FirstOrDefault(); trainRecord.GetTrainLoss(ls_item, epoch, trainStep, trainDataLoader.Count, lr);

 /*=======================================================
  * 优化器反向传播
 =========================================================*/
 optimizer.zero_grad();
 ls.backward();
 optimizer.step();

}

boxu2018 avatar Jul 22 '26 02:07 boxu2018